CentOS7 关机自动执行命令

需求说明

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
posted @   jiaxzeng  阅读(75)  评论(0编辑  收藏  举报
相关博文:
阅读排行:
· winform 绘制太阳,地球,月球 运作规律
· TypeScript + Deepseek 打造卜卦网站:技术与玄学的结合
· AI 智能体引爆开源社区「GitHub 热点速览」
· Manus的开源复刻OpenManus初探
· 写一个简单的SQL生成工具
点击右上角即可分享
微信分享提示