大网数据广告活动
服务器运维问答

Failed to start nginx.service: Interactive authentication required. with crontab

· 52CE 我爱测

I am trying to make a crontab to start nginx if it is stopped. I googled and found these two scripts http://www.akamaras.com/linux/linux-script-to-check-if-a-service-is-running-and-start-it-if-its-stopped/ #!/bin/bash service=rep…

问题原文

原帖链接 · Dora · CC BY-SA 3.0

I am trying to make a crontab to start nginx if it is stopped.

I googled and found these two scripts

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

somehow if I run it manually it works fine by doing source scriptName after I add it to crontab even if the service is stopped, it keeps on echoing nginx is running and does not start the service.

Then I found another script in digital ocean

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

again if I run it manually it works, but it will ask for the user's password

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

after I typed in the password ==== AUTHENTICATION COMPLETE === will show and starts nginx

then I add the script into crontab...I get this permission error

Failed to start nginx.service: Interactive authentication required.

Does anyone know how I can fix this?

Thanks in advance for any advices.

已采纳解答

原帖链接 · Michael Hampton · CC BY-SA 3.0

Those scripts you have been trying to use are obsolete and shouldn't be used on a modern system with systemd.

Try a script like this instead:

#!/bin/bash
if ! systemctl is-active nginx >/dev/null ; then
    systemctl start nginx
fi

But, that is some terribly nasty hackery and probably not necessary, so before you do that, try having systemd restart nginx automatically if it stops. Do that with a systemd drop-in:

[Service]
Restart=always

which you place as the file /etc/systemd/system/nginx.service.d/override.conf (creating the directory if it doesn't exist). You can also use systemctl edit nginx to create the file.

And of course, either creating the systemd drop-in, or putting this script in crontab, must be done as root (try using sudo -i for a long running root shell).

摘自公开归档,保留原文语言,版式经整理,外部媒体与邮箱地址已移除。

资料来源与适用范围

资料来源
Server Fault
适用范围
以原帖系统、软件版本与发布日期为准(2018-04-06)
内容语言
中文;命令、路径和错误标识保留技术原文
本地收录日期
2026-11-15
授权说明
CC BY-SA 3.0

正文与所需资源由本站本地存储。查看来源及更新记录 ↗

请按适用版本和实际日志确认原因;本站没有对每一种系统或设备逐项执行文中的操作。