无法启动 nginx.service:需要交互式身份验证。使用 crontab

Dor*_*ora 5 linux ubuntu nginx service cron

如果它被停止,我正试图让它crontab开始nginx

我用谷歌搜索并找到了这两个脚本

http://www.akamaras.com/linux/linux-script-to-check-if-a-service-is-running-and-start-it-if-its-stopped/

#!/bin/bash
service=replace_me_with_a_valid_service

if (( $(ps -ef | grep -v grep | grep $service | wc -l) > 0 ))
then
echo "$service is running!!!"
else
/etc/init.d/$service start
fi
Run Code Online (Sandbox Code Playgroud)

不知何故,如果我手动运行它source scriptNamecrontab即使服务停止,在我添加它之后它也能正常工作,它会继续回显nginx is running并且不会启动服务。

然后我在数字海洋中找到了另一个脚本

https://www.digitalocean.com/community/tutorials/how-to-use-a-simple-bash-script-to-restart-server-programs

#!/bin/sh

ps auxw | grep nginx | grep -v grep > /dev/null

if [ $? != 0 ]
then
        /etc/init.d/nginx start > /dev/null
fi
Run Code Online (Sandbox Code Playgroud)

再次,如果我手动运行它,它可以工作,但它会询问用户的密码

==== AUTHENTICATING FOR org.freedesktop.systemd1.manage-units ===
Authentication is required to start 'nginx.service'.
Authenticating as: abc,,, (abc)
Run Code Online (Sandbox Code Playgroud)

在我输入密码后==== AUTHENTICATION COMPLETE === 会显示并启动nginx

然后我将脚本添加到 crontab 中...我收到此权限错误

Failed to start nginx.service: Interactive authentication required.
Run Code Online (Sandbox Code Playgroud)

有谁知道我该如何解决这个问题?

提前感谢您的任何建议。

Mic*_*ton 3

您一直尝试使用的那些脚本已过时,不应在带有 systemd 的现代系统上使用。

尝试使用这样的脚本:

#!/bin/bash
if ! systemctl is-active nginx >/dev/null ; then
    systemctl start nginx
fi
Run Code Online (Sandbox Code Playgroud)

但是,这是一些非常令人讨厌的黑客行为可能没有必要,所以在你这样做之前,尝试让 systemd 在 nginx停止时自动重新启动它。使用systemd drop-in来做到这一点:

[Service]
Restart=always
Run Code Online (Sandbox Code Playgroud)

您将其作为文件放置/etc/systemd/system/nginx.service.d/override.conf(如果不存在则创建目录)。您还可以使用systemctl edit nginx它来创建文件。

当然,无论是创建 systemd 插件,还是将此脚本放入 crontab 中,都必须以 root 身份完成(尝试使用sudo -i长时间运行的 root shell)。