从crontab上的shell脚本启动nginx

时间:2019-06-02 08:59:29

标签: shell ubuntu nginx service cron

我想每隔1分钟检查NGINX是否正在运行。 我的shell脚本是:

#!/bin/sh
ps auxw | grep nginx | grep -v grep > /dev/null
if [ $? != 0 ]
then
echo "NGINX is not running"
/etc/init.d/nginx start
else
echo "NGINX is running"
fi

脚本正确地以sh launch.sh运行(如果NGINX未运行,请运行NGINX)。 问题是当我想通过crontab每1分钟运行一次脚本时,什么也没发生。 Crontab列表在这里:

# Edit this file to introduce tasks to be run by cron.
# 
# Each task to run has to be defined through a single line
# indicating with different fields when the task will be run
# and what command to run for the task
# 
# To define the time you can provide concrete values for
# minute (m), hour (h), day of month (dom), month (mon),
# and day of week (dow) or use '*' in these fields (for 'any').# 
# Notice that tasks will be started based on the cron's system
# daemon's notion of time and timezones.
# 
# Output of the crontab jobs (including errors) is sent through
# email to the user the crontab file belongs to (unless redirected).
# 
# For example, you can run a backup of all your user accounts
# at 5 a.m every week with:
# 0 5 * * 1 tar -zcf /var/backups/home.tgz /home/
# 
# For more information see the manual pages of crontab(5) and cron(8)
# 
# m h  dom mon dow   command

* * * * * ~/sh launch.sh

我测试了* * * * * sh launch.sh* * * * * launch.sh* * * * * ./launch.sh,但是它们都无法正常工作。 我的操作系统是UBUNTU 18.04。

这是日志:

Jun  3 08:28:01 hajitsu-VirtualBox CRON[3239]: (root) CMD (~/launch.sh)
Jun  3 08:28:01 hajitsu-VirtualBox CRON[3240]: (hajitsu) CMD (/home/hajitsu/launch.sh)
Jun  3 08:28:01 hajitsu-VirtualBox CRON[3238]: (CRON) info (No MTA installed, discarding output)
Jun  3 08:28:01 hajitsu-VirtualBox CRON[3237]: (CRON) info (No MTA installed, discarding output)
Jun  3 08:29:01 hajitsu-VirtualBox CRON[3374]: (root) CMD (~/launch.sh)
Jun  3 08:29:01 hajitsu-VirtualBox CRON[3373]: (CRON) info (No MTA installed, discarding output)
Jun  3 08:29:01 hajitsu-VirtualBox CRON[3376]: (hajitsu) CMD (/home/hajitsu/launch.sh)
Jun  3 08:29:01 hajitsu-VirtualBox CRON[3372]: (CRON) info (No MTA installed, discarding output)

我认为命令已触发,但是什么也没发生。

2 个答案:

答案 0 :(得分:0)

NGINX需要sudo特权。

如果您具有sudo特权,则可以修改/etc/sudoers.d/username文件并执行sudo命令,而无需输入密码。

该文件通常包含一个用户以及用户无需指定密码即可运行的命令列表。您可以运行:

sudo /etc/init.d/nginx start

添加或修改您的sudoers文件。 (用您的用户名替换用户名。)

$ EDITOR=nano sudo visudo -f /etc/sudoers.d/username  # EDITOR=nano sets my editor (because I am more comfortable with nano)

复制并粘贴以下内容。 您可以添加更多sudo命令,以逗号分隔。

username ALL=(ALL) NOPASSWD: /etc/init.d/nginx start,/etc/init.d/nginx start

注意:命令将仅以sudo调用。

在您的sudo中添加launch.sh

#!/bin/sh
ps auxw | grep nginx | grep -v grep > /dev/null
if [ $? != 0 ]
then
echo "NGINX is not running"
sudo /etc/init.d/nginx start
else
echo "NGINX is running"
fi

使文件可执行。

$ chmod +x launch.sh

答案 1 :(得分:-1)

在crontab中,

~不会像在交互式shell中那样扩展。请改用/home/username