无需 sudo 即可重启 nginx&gunicorn

无需 sudo 即可重启 nginx&gunicorn

我可以systemctl restart gunicorn && systemctl restart nginx不运行吗sudo?目前我得到:

输出:需要身份验证才能重新加载“gunicorn.service”。

验证身份:myuser

退出: 密码:

# coding: utf-8
from fabric.api import *
from fabric.colors import green, red


def production():
    env.host_string = '159.xxx.xxx.xx'
    env.user = 'myuser'
    path = "/home/myuser/myproject/myproject"
    print(red("Beginning Deploy:"))
    with cd(path):
        with prefix('. /home/myuser/myproject/myenv/bin/activate'):
            run("pwd")
            print(green("Pulling master from git..."))
            run("git pull")
            print(green("Migrate the database..."))
            run("python3 manage.py migrate")
            print(green("Restart the uwsgi process"))
            run("systemctl restart gunicorn && systemctl restart nginx")
        print(red("DONE!"))

答案1

您可以尝试添加 PolicyKit 规则以允许无需身份验证即可重新启动设备。

例如,这将允许任何用户重新启动命名的服务(可能需要一些调整):

polkit.addRule(function(action, subject) {
    if (action.id == "org.freedesktop.systemd1.manage-units") {
        polkit.log("action=" + action)
        polkit.log("subject=" + subject)
        polkit.log("unit="+action.lookup("unit"))
        polkit.log("verb="+action.lookup("verb"))
        if (action.lookup("unit") == "gunicorn.service" ||
            action.lookup("unit") == "nginx.service") {
            var verb = action.lookup("verb");
            if (verb == "start" || verb == "restart") {
                polkit.log("returning YES")
                return polkit.Result.YES;
            }
        }
    }
    polkit.log("returning NO")
});

将您的规则放在目录中的文件中/etc/polkit-1/rules.d,文件名以 结尾.rules

这需要 systemd 226 或更高版本,在 Ubuntu 中意味着 16.04 LTS 或更高版本。

(如果你觉得这看起来像 JavaScript,那是因为它是 JavaScript

您还可以通过检查将其限制为特定用户subject.user,例如:

if (subject.user == "deploy" || subject.user == "me") {

相关内容