CentOS7 关机自动执行命令

发布时间 2023-12-18 17:43:23作者: jiaxzeng

需求说明

CentOS7 关机之前自动执行脚本

解决方法

  1. 创建 shutdown-clean 服务
cat <<'EOF' | sudo tee /usr/lib/systemd/system/shutdown-clean.service > /dev/null
[Unit]
Description=close services before reboot and shutdown
DefaultDependencies=no
Before=shutdown.target reboot.target halt.target
#Before=network.target iscsi.service iscsid.service 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/local/src/shutdownScript.sh

[Install]
WantedBy=halt.target reboot.target shutdown.target
EOF
  1. 创建执行脚本

注意:该脚本开头必须写上 #!/bin/bash 解释器

cat <<'EOF' | sudo tee /usr/local/src/shutdownScript.sh > /dev/null
#!/bin/bash

# 取消yum的代理
egrep -q "^[[:space:]]*proxy" /etc/yum.conf
if [[ $? -eq 0 ]];then
  sudo sed -ri '/^[[:space:]]*proxy/d' /etc/yum.conf
fi
EOF

sudo chmod +x /usr/local/src/shutdownScript.sh
  1. shutdown-clean 服务开机自启
sudo systemctl daemon-reload
sudo systemctl enable shutdown-clean