天天看點

crontab指令詳解及案例展示

作者:IT運維與實戰

crontab 指令安裝:

-bash: crontab: command not found #Debianapt-get install bcron #Ubuntuapt-get install bcron #Arch Linuxpacman -S cronie #Kali Linuxapt-get install systemd-cron #CentOSyum install cronie #Fedoradnf install cronie #Raspbianapt-get install interchange           

crontab 指令文法:

crontab [-u user] filecrontab [-u user] [-l | -r | -e] [-i] [-s]   1 SHELL=/bin/bash  2 PATH=/sbin:/bin:/usr/sbin:/usr/bin  3 MAILTO=root  4 HOME=/  5   6 # For details see man 4 crontabs  7   8 # Example of job definition:  9 # .---------------- minute (0 - 59) 10 # |  .------------- hour (0 - 23) 11 # |  |  .---------- day of month (1 - 31) 12 # |  |  |  .------- month (1 - 12) OR jan,feb,mar,apr ... 13 # |  |  |  |  .---- day of week (0 - 6) (Sunday=0 or 7) OR sun,mon,tue,wed,thu,fri,s    at 14 # |  |  |  |  | 15 # *  *  *  *  * user-name command to be executed 16  #man crontab[root@Dev_Test etc]$man crontabCRONTAB(1)                   Cronie Users’ Manual                   CRONTAB(1) NAME       crontab - maintain crontab files for individual users SYNOPSIS       crontab [-u user] file       crontab [-u user] [-l | -r | -e] [-i] [-s] DESCRIPTION       Crontab  is  the program used to install, remove or list the tables used       to drive the cron(8) daemon.  Each user can have their own crontab,  and       though  these  are  files  in  /var/spool/ , they are not intended to be       edited directly. For SELinux in mls mode can be even more crontabs - for       each range. For more see selinux(8).        The  cron jobs could be allow or disallow for different users. For clas-       sical  crontab  there  exists  cron.allow  and  cron.deny   files.    If       cron.allow  file  exists, then you must be listed therein in order to be       allowed to use this command.  If the cron.allow file does not exist  but       the  cron.deny  file  does  exist,  then  you  must not be listed in the       cron.deny file in order to use this command.  If neither of these  files       exists,  only  the  super user will be allowed to use this command.  The       second option is using PAM authentication, where you set up users, which       could   or   couldn’t  use  crontab  and  also  system  cron  jobs  from       /etc/cron.d/.        The temporary directory could be set in enviroment  variables.  If  it’s       not set by user than /tmp is used. OPTIONS       -u     Append  the  name of the user whose crontab is to be tweaked.  If              this option is not given, crontab examines "your" crontab,  i.e.,              the crontab of the person executing the command.  Note that su(8)              can confuse crontab and that if you are running inside  of  su(8)              you should always use the -u option for safety’s sake.  The first              form of this command is used to install a new crontab  from  some              named file or standard input if the pseudo-filename "-" is given.        -l     The current crontab will be displayed on standard output.        -r     The current crontab will be removed.        -e     This option is used to edit the current crontab using the  editor              specified  by  the VISUAL or EDITOR environment variables.  After              you exit from the editor, the modified crontab will be  installed              automatically.        -i     This option modifies the -r option to prompt the user for a ’y/Y’              response before actually removing the crontab.        -s     It will append the current SELinux security context string as  an              MLS_LEVEL  setting  to the crontab file before editing / replace-              ment occurs - see the documentation of MLS_LEVEL in crontab(5). SEE ALSO       crontab(5),cron(8) FILES       /etc/cron.allow       /etc/cron.deny STANDARDS       The crontab command conforms to IEEE Std1003.2-1992  (‘‘POSIX’’).   This       new command syntax differs from previous versions of Vixie Cron, as well       as from the classic SVR3 syntax. DIAGNOSTICS       A fairly informative usage message appears if you run it with a bad com-       mand line. AUTHOR       Paul Vixie Marcela Mašláňová                20 July 2009                       CRONTAB(1)           

crontab 指令選項:

-e:編輯該使用者的計時器設定;-l:列出該使用者的計時器設定;-r:删除該使用者的計時器設定;-u<使用者名稱>:指定要設定計時器的使用者名稱。           

crontab 指令參數:

crontab 檔案:指定包含待執行任務的 crontab 檔案。

crontab 補充說明:

crontab指令 被用來送出和管理使用者的需要周期性執行的任務,與 Windows 下的 Task 計劃任務類似,當安裝完成作業系統後,預設會安裝此服務工具,并且會自動啟動 crond 程序,crond 程序每分鐘會定期檢查是否有要執行的任務,如果有要執行的任務,則自動執行該任務。

crontab 指令知識擴充:

Linux下的任務排程分為兩類: 系統任務排程 和 使用者任務排程 。

系統任務排程: 系統周期性所要執行的工作,比如寫緩存資料到硬碟、日志清理等。在 /etc/ 目錄下有一個 crontab 檔案,這個就是系統任務排程的配置檔案。

/etc/crontab 檔案包括下面幾行:

SHELL=/bin/bashPATH=/sbin:/bin:/usr/sbin:/usr/binMAILTO=""HOME=/ # run-parts51 * * * * root run-parts /etc/cron.hourly24 7 * * * root run-parts /etc/cron.daily22 4 * * 0 root run-parts /etc/cron.weekly42 4 1 * * root run-parts /etc/cron.monthly           

前四行是用來配置crond任務運作的環境變量,第一行SHELL變量指定了系統要使用哪個 shell,這裡是 bash,第二行 PATH 變量指定了系統執行指令的路徑,第三行 MAILTO 變量指定了 crond 的任務執行資訊将通過電子郵件發送給 root 使用者,,第四行的 HOME 變量指定了在執行指令或者腳本時使用的主目錄。

使用者任務排程: 使用者定期要執行的工作,比如使用者資料備份、定時郵件提醒等。使用者可以使用 crontab 工具來定制自己的計劃任務。所有使用者定義的crontab檔案都被儲存在/var/spool/cron目錄中。其檔案名與使用者名一緻,使用者權限檔案如下:

/etc/cron.deny     #該檔案中所列使用者不允許使用crontab指令/etc/cron.allow    #該檔案中所列使用者允許使用crontab指令/var/spool/cron/   #所有使用者crontab檔案存放的目錄,以使用者名命名           

:使用者所建立的crontab檔案中,每一行都代表一項任務,每行的每個字段代表一項設定,它的格式共分為六個字段,前五段是時間設定段,第六段是要執行的指令段,格式如下:

minute   hour   day   month   week   command     #順序:分 時 日 月 周           

其中:

  1. minute: 表示分鐘,可以是從0到59之間的任何整數。
  2. hour:表示小時,可以是從0到23之間的任何整數。
  3. day:表示日期,可以是從1到31之間的任何整數。
  4. month:表示月份,可以是從1到12之間的任何整數。
  5. week:表示星期幾,可以是從0到7之間的任何整數,這裡的0或7代表星期日。
  6. command:要執行的指令,可以是系統指令,也可以是自己編寫的腳本檔案。

在以上各個字段中,還可以使用以下特殊字元:

  • 星号(*):代表所有可能的值,例如month字段如果是星号,則表示在滿足其它字段的制約條件後每月都執行該指令操作。
  • 逗号(,):可以用逗号隔開的值指定一個清單範圍,例如,“1,2,5,7,8,9”
  • 中杠(-):可以用整數之間的中杠表示一個整數範圍,例如“2-6”表示“2,3,4,5,6”
  • 正斜線(/):可以用正斜線指定時間的間隔頻率,例如“0-23/2”表示每兩小時執行一次。同時正斜線可以和星号一起使用,例如*/10,如果用在minute字段,表示每十分鐘執行一次。

crond服務

/sbin/service crond start    //啟動服務/sbin/service crond stop     //關閉服務/sbin/service crond restart  //重新開機服務/sbin/service crond reload   //重新載入配置           
crontab指令詳解及案例展示

檢視crontab服務狀态:

[root@Dev_Test etc]$service crond statuscrond (pid  2735) is running...           

手動啟動crontab服務:

service crond start           

檢視crontab服務是否已設定為開機啟動,執行指令:

ntsysv           

加入開機自動啟動:

chkconfig –level 35 crond on           

crontab 指令執行個體:

每1分鐘執行一次command

* * * * * command           

每小時的第3和第15分鐘執行

3,15 * * * * command           

在上午8點到11點的第3和第15分鐘執行

3,15 8-11 * * * command           

每隔兩天的上午8點到11點的第3和第15分鐘執行

3,15 8-11 */2 * * command           

每個星期一的上午8點到11點的第3和第15分鐘執行

3,15 8-11 * * 1 command           

每晚的21:30重新開機smb

30 21 * * * /etc/init.d/smb restart           

每月1、10、22日的4 : 45重新開機smb

45 4 1,10,22 * * /etc/init.d/smb restart           

每周六、周日的1:10重新開機smb

10 1 * * 6,0 /etc/init.d/smb restart           

每天18 : 00至23 : 00之間每隔30分鐘重新開機smb

0,30 18-23 * * * /etc/init.d/smb restart           

每星期六的晚上11:00 pm重新開機smb

0 23 * * 6 /etc/init.d/smb restart           

每一小時重新開機smb

* */1 * * * /etc/init.d/smb restart           

晚上11點到早上7點之間,每隔一小時重新開機smb

* 23-7/1 * * * /etc/init.d/smb restart           

每月的4号與每周一到周三的11點重新開機smb

0 11 4 * mon-wed /etc/init.d/smb restart           

一月一号的4點重新開機smb

0 4 1 jan * /etc/init.d/smb restart           

每小時執行/etc/cron.hourly目錄内的腳本

01 * * * * root run-parts /etc/cron.hourly           

crontab 指令的坑:

注意:crontab裡執行指令是沒有PATH環境變量一說的,是以必須寫絕對路徑,否則crontab是找不到指令的..

注意 crontab 兩個大坑和一個超級大坑!

之前crontab是這樣寫的:

* * * mysqldump -u user -pxxxx database > "/alidata/backup/imyzf.com/$(date +%F\ %T).sql"           

1 首先,是百分号(%)。

在crontab -e中輸入的指令裡,第一個%會被認為是标準輸入的開始,接下來的%都會被認為是換行。是以在這裡原本隻是格式化日期的%被當成了标準輸入,指令就出問題了。解決方案有兩種,一是用sed指令;我采用了另外一種方法,把指令寫到了sh檔案裡(為什麼?因為還有一個大坑)。

2 然後,是環境變量。

即使解決了上面的問題,還是不能正常執行任務,因為 crontab 的環境變量是另外定義的。通過 cat /etc/crontab 你會發現預設的PATH是 /sbin:/bin:/usr/sbin:/usr/bin,而我們的 mysqldump 是在 /alidata/server/mysql/bin裡的。

是以要修改預設設定,或者簡單點,在 sh 檔案裡另外加上一行修改 PATH,最後成了這樣:

#!/bin/bashPATH="$PATH:/alidata/server/mysql/bin"mysqldump -u user -pxxxx database > "/alidata/backup/www.pianyiwan.com/$(date +%F\ %T).sql"           

然後,我的crontab寫成了這樣(使用/dev/null是為了丢棄mysqldump使用标準輸出的提示):

* * * /alidata/backup/www.pianyiwan.com/backup.sh > /dev/null 2>&1           

注意 crontab 的超級大坑來了;

突然發現 crontab 内容丢失了,或者是被清空了:是什麼原因造成的?

坑一:If you issue crontab without any option and then press ctrl-d, it will erase everything in your crontab -- 如果你不帶參數運作 crontab 指令,然後按了 Ctrl+D,則 crontab 内容會被清空!!!這時候退出要用 Ctrl+C,切記!!!

坑二:看了 man crontab 手冊,如果執行 crontab -r,則 crontab 内容會被清空————如果将 crontab -e 敲成了 crontab -r ,内容也沒了,e 和 r 的位置很近……是不是很坑!

找回丢失的 crontab 内容

crontab有運作日志,在日志裡面可以找到執行過的曆史指令。前提是要有root權限。指令如下:

cat /var/log/cron* | grep -i "`which cron`" > ./all_temp cat  ./all_temp | grep -v "" > ./cmd_temp           

用awk讀取cmd_temp,即可得到指令。

[script-02 tmp]$ cat cmd_temp  | grep username | awk -F 'CMD' '{print $2}' | sort | uniq (bash   /home/appadmin/script/security/auto_restart.sh)           

指令是找回了,可是執行周期呢?可以通過檢視執行曆史,如果看到是一分鐘一次,則可以判斷執行周期。總結:平時注意備份 crontab 配置!