如何用 root 權限執行 cron 任務

如果某些工作需要用到root權限,又要利用 cron 排程執行,只需要把工作加入 root 的 crontab 即可:

sudo crontab -e

參考: How to run a cron job using the sudo command - Ask Ubuntu

# 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
43 08 * * 1-5 /media/allenyl/DATA/aifr_share/openvpn.sh >> /media/allenyl/DATA/aifr_share/openvpn_log.txt 2>&1
48 13 * * 1-5 /media/allenyl/DATA/aifr_share/disconnect_openvpn.sh

其中

43 08 * * 1-5

代表執行的時間,可參考 Crontab.guru - The cron schedule expression editor

而後面的 command

/media/allenyl/DATA/aifr_share/openvpn.sh >> /media/allenyl/DATA/aifr_share/openvpn_log.txt 2>&1

有幾點要注意:

1. script 中的所有路徑都必須是絕對路徑,否則很可能會因為環境變數沒有設定的關係,而找不到指令

2. 如果指令有任何輸出到 stdout,預設會 email 到擁有者信箱,但若沒設定,就會在 service cron status 看到錯誤訊息:

 sendmail: fatal: open /etc/postfix/main.cf: No such file or directory

因此,要將 stdout 跟 stderr redirect 到檔案中,參考:server - Cron job not running - postfix/sendmail error - Ask Ubuntu

Notes:

1. 若直接執行  crontab -e 沒有加上 sudo,就會是當前使用者的 crontab

2. 編輯完後會要求存檔,就直接存在他的預設路徑即可

3. 在某些情況下,會需要重新啟動服務,ubuntu 下可以執行

service cron status
service cron stop
service cron start

參考: cron - Verify if crontab works - Ask Ubuntu