方法一:rc.local
1、由於在centos7中/etc/rc.d/rc.local
的權限被降低了,所以需要賦予其可執行權
chmod +x /etc/rc.d/rc.local
2、賦予腳本可執行權限
假設/opt/script/autostart.sh
是腳本運行路徑,給予可執行權限
chmod +x /opt/script/autostart.sh
3、打開/etc/rc.d/rc/local
文件,在末尾增加如下內容
/opt/script/autostart.sh ### 開機自動啓動腳本
systemctl start sshd ### 開機自動啓動服務
方法二:chkconfig
/etc/init.d
是/etc/rc.d/init.d
的軟鏈接,當Linux啓動時,會尋找這些目錄中的服務腳本,並根據腳本的運行級別確定不同的啓動級別。
1、將腳本移動到/etc/rc.d/init.d
目錄下
mv /opt/script/autostart.sh /etc/rc.d/init.d
2、授予腳本可執行權限
chmod +x /etc/rc.d/init.d/autostart.sh
3、添加腳本到開機自動啓動項目中
cd /etc/rc.d/init.d
chkconfig --add autostart.sh
chkconfig autostart.sh on
方法三:systemd
1、可以通過systemd添加自定義服務啓動
systemctl enable sshd
2、其他systemctl命令
# 啓動sshd服務
systemctl start sshd
# 設置開機自啓動
systemctl enable sshd
# 停止開機自啓動
systemctl disable sshd
# 查看服務當前狀態
systemctl status sshd
# 重新啓動服務
systemctl restart sshd
# 查看所有已啓動的服務
systemctl list-units --type=service