如何在Linux下設置腳本啟動

  • 2019 年 11 月 12 日
  • 筆記

1、開機自動運行

假如Python自啟動腳本為auto.py。那麼用root許可權編輯以下文件:

 [root@docker-01 ~]# vim /etc/rc.local   #!/bin/bash   # THIS FILE IS ADDED FOR COMPATIBILITY PURPOSES   #   # It is highly advisable to create own systemd services or udev rules   # to run scripts during boot instead of using this file.   #   # In contrast to previous versions due to parallel execution during boot   # this script will NOT be run after all other services.   #   # Please note that you must run 'chmod +x /etc/rc.d/rc.local' to ensure   # that this script will be executed during boot.     touch/var/lock/subsys/local   /usr/bin/python3 /home/selfcs/auto.py > /home/selfcs/auto.log

2、讓腳本定時啟動

用root許可權編輯以下文件

 [root@docker-01 ~]# vim /etc/crontab   ##創建定時任務   [root@docker-01 ~]# crontab -e -u root ##-e修改 -u指定用戶   */10 * * * * /usr/sbin/ntpdate 0.cn.pool.ntp.org && hwclock --systohc>/dev/null 2>&1

3、& 後台運行

將sh test.sh任務放到後台 ,關閉xshell,對應的任務也跟著停止。

 [root@docker-01 ~]# sh test.sh &   [1] 17717

4、nohup不掛斷的運行

用nohup運行命令可以使命令永久的執行下去,和用戶終端沒有關係,例如我們斷開SSH連接都不會影響他的運行,注意了nohup沒有後台運行的意思;&才是後台運行,通常nuhup和&在一起執行。

 [root@docker-01 ~]# nohup command > myout.file 2>&1 & ##本例子中,0 – stdin (standard input),1 – stdout (standard output),2 – stderr (standard error) ;   2>&1是將標準錯誤(2)重定向到標準輸出(&1),標準輸出(&1)再被重定向輸入到myout.file文件中。

5、創建一個配置文件

創建一個start.sh啟動文件和stop.sh停止文件,把需要執行的命令放到腳本裡面。

 [root@localhost bin]# cat start.sh   /usr/local/bin/mitmdump -p8888-s/home/smgadmin/web_crawler/scripts/dyscripty/bin/dyscripty.py >/dev/null 2>&1 &  ##啟動文件   [root@localhost bin]# sh start.sh   [root@localhost bin]# cat stop.sh   kill-9 `ps auxwww | grep 'mitmdump' | grep '/home/smgadmin/web_crawler/scripts/dyscripty/bin/dyscripty.py' | grep -v grep | awk '{print $2}'` ##停止文件   [root@localhost bin]# sh stop.sh