Linux系統設置開機自動運行腳本的方法
方法1 rc.local
/etc/rc.d/rc.local文件會在linux系統各項服務都啟動完畢后再被運行,可以將腳本路徑加到該文件里
1)確保權限
chmod +x /etc/rc.d/rc.local
2)創建腳本
cat /home/zxg/auto_run_1.sh
#!/bin/bash
date >>/home/zxg/dateout.txt
hostname >>/home/zxg/hostnameout.txt
chmod +x /home/zxg/auto_run_1.sh
3)編輯/etc/rc.d/rc.local文件
vim /etc/rc.d/rc.local
/home/zxg/auto_run_1.sh
4)重啟驗證
reboot
[root@localhost zxg]# init 6
Last login: Tue Aug 11 15:00:13 2020 from 10.211.55.2
[root@localhost ~]# cat /home/zxg/hostnameout.txt
localhost
[root@localhost ~]# cat /home/zxg/dateout.txt
Tue Aug 11 15:02:32 CST 2020
[root@localhost ~]#
方法2 計划任務crontab
crontab是linux下的計划任務,當時間達到設定的時間運行任務,crontab有個特殊任務叫@reboot。就是重啟后運行的任務
1)使用crontab -e
crontab -e
@reboot /home/zxg/auto_run_1.sh
2)重啟驗證
reboot
Last login: Tue Aug 11 15:02:33 2020 from 10.211.55.2
[root@localhost ~]# cat /home/zxg/hostnameout.txt
localhost
[root@localhost ~]# cat /home/zxg/dateout.txt
Tue Aug 11 15:05:21 CST 2020
[root@localhost ~]#
方法3 systemd 服務
systemd系統centos7+以后支持,也可以ps aux 查看pid為1的是不是systemd
1)確認能不能使用systemd
[root@localhost ~]# ps -e
PID TTY TIME CMD
1 ? 00:00:01 systemd
2)編輯{xxx.service文件}
創建一個systemd啟動服務,並放在/etc/systemd/system/目錄下
vim auto_run_1.service
[Unit]
Description=Run a Custom Script at Startup
After=default.target
[Service]
ExecStart=/home/zxg/auto_run_1.sh
[Install]
WantedBy=default.target
3)更新配置文件及啟動服務
systemctl daemon-reload
systemctl enable auto_run_1.service
4)重啟驗證
reboot
[root@localhost ~]# cat /home/zxg/dateout.txt
Tue Aug 11 15:05:21 CST 2020
Tue Aug 11 15:07:49 CST 2020
[root@localhost ~]# cat /home/zxg/hostnameout.txt
localhost
localhost
[root@localhost ~]#