[Linux] 在 CentOS 7 開機時自動執行 script

[Linux] 在 CentOS 7 開機時自動執行 script

在公司有台 CentOS 7,每次開機後都得自己手動加一個 routing,

才能連到 lab 裡的機器,有點麻煩…

今天終於找到一個比較簡單的方法,

可以在開機時自動執行 script 了,那就是透過 /etc/rc.d/rc.local~

 

參考資料:stackoverflow: How to run a shell script at startup

 

1. 修改 /etc/rc.d/rc.local

把要執行的 script 加到 /etc/rc.d/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
/home/testuser/add_lab_route.sh

 

上面的 touch /var/lock/subsys/local 是原本就存在的指令,

我加上了 /home/testuser/add_lab_route.sh~

 

2. 將 /etc/rc.d/rc.local 設定為可執行

預設狀況下 /etc/rc.d/rc.local 是不可執行的,要把它改成可執行才會跑:

sudo chmod +x /etc/rc.d/rc.local

 

都設定好之後,就可以重開機確認看看效果囉~^^

 

(本頁面已被瀏覽過 11,299 次)

2 thoughts on “[Linux] 在 CentOS 7 開機時自動執行 script

  1. 請問這樣設定如果突然終止script該怎麼做?
    我設定完成功了但無法停下來..

    1. 不太懂您的無法停下來是什麼意思?
      再回去修改 /etc/rc.d/rc.local 就可以關掉了。

      如果是說它會導致 CentOS 桌面出不來 (我沒遇過),
      也許可以試試能不能用 ssh 連進去,砍掉不要的 process 再修改 /etc/rc.d/rc.local。

發佈留言

發佈留言必須填寫的電子郵件地址不會公開。 必填欄位標示為 *

這個網站採用 Akismet 服務減少垃圾留言。進一步了解 Akismet 如何處理網站訪客的留言資料