Centos7關機和重啓前執行自定義腳本

0. 前言

如果你在linux系統上啓動了很多自己的服務,如果直接執行系統的reboot或者shutdown命令,可能會發生一些異常的現象,所以我們在重啓和關機前,應該按照我們的意願去自定義清理一些服務或者資源等。但是網上的方式大多是以Centos6爲教程,修改chkconfig和rc0.d,rc6.d的內容。在Centos7中以及不適用了。
本文就介紹一下在Centos7系統中,使用systemctl的方式來自定義關機前執行腳本。

1. 創建systemd服務

vi /usr/lib/systemd/system/stopSrv.service
創建該文件然後加入下面的內容,需要把ExecStart=/home/my_script這一行換成自己的腳本路徑

[Unit]
Description=close services before reboot and shutdown
DefaultDependencies=no
Before=shutdown.target reboot.target halt.target
# This works because it is installed in the target and will be
#   executed before the target state is entered
# Also consider kexec.target

[Service]
Type=oneshot
ExecStart=/home/my_script  #your path and filename

[Install]
WantedBy=halt.target reboot.target shutdown.target

2. 啓動服務

然後執行

systemctl enable stopSrv

經過這兩步操作,關機和重啓前,就會自動執行你自定義的腳本了

發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章