1. 程式人生 > >【Linux】開機自動啟動指令碼

【Linux】開機自動啟動指令碼

  Linux下(以RedHat為範本)新增開機開機自動啟動指令碼有兩種方式;

  本例系統:Linux(CentOS 7.2)

方法一

  使用 /etc/rc.d/rc.local,自動啟動指令碼

 1 #!/bin/bash                                                                                                
 2 # THIS FILE IS ADDED FOR COMPATIBILITY PURPOSES                                                            
3 # 4 # It is highly advisable to create own systemd services or udev rules 5 # to run scripts during boot instead of using this file.
6 # 7 # In contrast to previous versions due to parallel execution during boot 8 # this script will NOT be run after all other services.
9 # 10 # Please note that you must run 'chmod +x /etc/rc.d/rc.local' to ensure 11 # that this script will be executed during boot. 12 13 touch /var/lock/subsys/local

  1、授予 /etc/rc.d/rc.local 檔案執行許可權

    命令:chmod +x /etc/rc.d/rc.local

  2、在檔案檔案底部新增指令碼

  3、重啟伺服器,檢視指令碼是否啟動

  注意:/etc/rc.d/rc.local指令碼執行,在/etc/profile之前,若/etc/rc.d/rc.local用到/etc/profile的環境變數,Shell無法執行成功

方法二

  1、編輯服務指令碼 xxxx(指令碼名),增加內容(要在服務指令碼中實現POSIX規範中的函式:start() stop()等),命令:vim /etc/init.d/xxxx

  2、給指令碼增加可執行許可權,命令:chmod a+x /etc/init.d/xxxx

  3、註冊xxxx服務名,命令:chkconfig --add xxxx

 1 注意執行命令:chkconfig --add xxxx
 2 常常會出現
 3 
 4 service myservice does not support chkconfig
 5 我們一般在指令碼開頭加入下面兩句就好了
 6 #vim /etc/init.d/xxxx
 7 新增下面兩句到 #!/bin/bash 之後。
 8 
 9 # chkconfig: 2345 10 90 
10 # description: xxxx ....
11 其中2345是預設啟動級別,級別有0-6共7個級別。
12 
13   等級0表示:表示關機   
14 
15   等級1表示:單使用者模式   
16 
17   等級2表示:無網路連線的多使用者命令列模式   
18 
19   等級3表示:有網路連線的多使用者命令列模式   
20 
21   等級4表示:不可用   
22 
23   等級5表示:帶圖形介面的多使用者模式   
24 
25   等級6表示:重新啟動
26 
27 10是啟動優先順序,90是停止優先順序,優先順序範圍是0-100,數字越大,優先順序越低

    配置系統啟動時該指令碼預設啟動,命令:chkconfig xxxx on   

    配置系統啟動時該指令碼預設關閉,命令:chkconfig xxxx off

  4、列出當前的服務和他們的配置,命令:chkconfig --list

  5、重啟伺服器,檢視指令碼是否啟動