从 crontab 上的 shell 脚本启动 nginx



我想每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)

我认为命令已触发,但没有任何反应。

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 调用的命令。

launch.sh前面加上sudo

#!/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
<</div> div class="one_answers">

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

最新更新