樹莓派進階之路 (033) - 開機啟動自定義腳本


因為需求需要,樹莓派開機需要自動運行一些代碼和腳本,並且需要對網絡是否正常進行監測,所以需要做帶網絡監測的自啟動服務。

參考了一下文檔:

Linux開機啟動程序詳解

Linux中設置服務自啟動的三種方式linux服務的開機啟動和運行級別linux系統的7種運行級別ubuntu下設置開機啟動服務,

Ubuntu15.x /CentOS 7.x 以后 設置開機啟動,添加自定義系統服務,自定義開機啟動

Ubuntu14.04設置開機啟動腳本如何添加自定義腳本到開機自啟動linux添加開機自啟動腳本示例詳解linux添加開機自啟動腳本示例詳解 ,幾種設置樹莓派開機自啟的方法

nohup-真正的Shell后台運行讓linux服務器上的程序在后台運行

 

經過上面的文檔:

進入配置開機啟動文件:

cd /etc
sudo vim rc.local

rc.local

 1 #!/bin/sh -e
 2 #
 3 # rc.local
 4 #
 5 # This script is executed at the end of each multiuser runlevel.
 6 # Make sure that the script will "exit 0" on success or any other
 7 # value on error.
 8 #
 9 # In order to enable or disable this script just change the execution
10 # bits.
11 #
12 # By default this script does nothing.
13 
14 # Print the IP address
15 _IP=$(hostname -I) || true
16 if [ "$_IP" ]; then
17   printf "My IP address is %s\n" "$_IP"
18 fi
19 
20 nohup  /etc/init.d/network_test.sh &    #后台啟動自定義腳本
21 
22 exit 0  

 

建立自定義的網絡測試腳本:

vim network_test.sh

把一下文件cp到文件中:

 1 #!/bin/bash
 2 #
 3 #檢測網絡鏈接&&ftp上傳數據
 4 
 5 
 6 declare -i n=0            #在定義變量n前面加上declare -i 表示該變量為數值
 7 while [ $n -ne 1 ]        #判斷
 8 do
 9         ret_code=`curl -I -s --connect-timeout 5 baidu.com -w %{http_code} | tail -n1`    #網絡值
10          if [ "$ret_code" = "200" ]; then
11                 nohup /home/pi/bind &           #網絡連接成功啟動腳本程序腳本
12                 n=1;
13         else
14                 n=0; #失敗等待
15         fi
16 done

把文件cp到rc.local腳本自定的目錄:

sudo mv network_test.sh /etc/init.d

我們在/home/pi目錄中建立自己的啟動腳本 bind 來啟動自定義的腳本。

 

=============================== 腳本實現方法=================================

service.sh

 1 #!/bin/bash
 2 
 3 sudo rm -r pi/
 4 sudo apt-get install git
 5 git clone https://gitee.com/jikexianfeng/pi.git
 6 cd ~/pi/service
 7 sudo mv ./rc.local /etc/rc.local
 8 sudo mv ./network_test.sh /etc/init.d/network_test.sh
 9 mv bind ~
10 cd
11 sudo rm -r pi/
12 rm service.sh
13 sudo reboot

 


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM