如何在linux centos系统关机前自动执行指定脚本

在 CentOS 系统中,可以使用 Systemd 服务来在关机前自动执行指定脚本。下面是创建一个名为 pre-shutdown-script.service 的 Systemd 服务的步骤:

  1. 创建一个新的 Systemd 服务文件:


sudo vi /etc/systemd/system/pre-shutdown-script.service
  1. 将以下内容粘贴到该文件中:


[Unit]
Description=Pre-shutdown script
Before=shutdown.target reboot.target halt.target
StopWhenUnneeded=yes

[Service]
Type=oneshot
RemainAfterExit=yes
ExecStart=/bin/true
ExecStop=/path/to/your/script.sh

[Install]
WantedBy=multi-user.target

在这里,将 /path/to/your/script.sh 替换为要在关机前执行的脚本的路径。

  1. 保存并退出文件。
  2. 设置文件权限:


sudo chmod 664 /etc/systemd/system/pre-shutdown-script.service
  1. 重新加载 Systemd 配置并启用新服务:


sudo systemctl daemon-reload
sudo systemctl enable pre-shutdown-script.service

现在,在每次系统关机、重启或停机之前,指定脚本都会自动执行。

举报
评论 0