CentOS7关机或重启前执行特定脚本
关机服务脚本
修改/usr/lib/systemd/system/stopSrv.service
服务脚本中 ExecStart
配置项(如果文件不存在则创建新文件并执行后续操作),将 ExecStart
的值改为要执行的脚本目录。如本文中需要在关机或重启前执行/usr/bin/shutdownhook.sh
脚本的相关配置如下:
[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=/usr/bin/shutdownhook.sh
[Install]
WantedBy=halt.target reboot.target shutdown.target
- 编写操作脚本
新建/usr/bin/shutdownhook.sh
脚本,在其中增加需要执行的操作,如本例在关机或重启前打印本次系统开机时间和当前时间到文件做记录,相关脚本如下:
now_time=`date "+%Y-%m-%d %H:%M:%S"`
start_time=`date -d "$(awk -F. '{print $1}' /proc/uptime) second ago" +"%Y-%m-%d %H:%M:%S"`
echo "System will shutdown.Star time=$start_time,now time=$now_time" >> /docker_data/logs/system.log
sync
- 启用配置
给两个脚本赋予可执行文件,然后启用服务即可,相关命令如下:
chmod +x /usr/bin/shutdownhook.sh`
chmod +x /usr/lib/systemd/system/stopSrv.service
systemctl enable stopSrv