如何在CentOS上关闭之前运行Shell脚本

lin*_*bee 4 linux bash shell centos runlevel

我想在系统关闭电子邮件ID时发送电子邮件.我有CentOS 6.4.以下是我的脚本.

cat /ect/init.d/sendshtmail

#!/bin/bash

EMAIL="example@example.com"
SHUTDOWNSUBJECT="["`hostname`"] - System Shutdown"


SHUTDOWNBODY="This is an automated message to notify you that "`hostname`" is shutting down.

LOCKFILE=/var/lock/subsys/SystemEmail
echo "${SHUTDOWNBODY}" | mutt -s "${SHUTDOWNSUBJECT}" ${EMAIL}
Run Code Online (Sandbox Code Playgroud)

它有适当的许可.手动运行时,它运行良好.我刚将它符号链接到/etc/rc0.d/文件夹.通过发出以下命令.

 ln -s /etc/init.d/sendshtmail /etc/rc0.d/K00sendshtmail
Run Code Online (Sandbox Code Playgroud)

但是脚本在关机期间没有发送任何电子邮件.提前致谢.

Mah*_*tam 13

将shell脚本放在带有可执行权限的/etc/init.d中,符号链接名称应以K ##开头.如果要在关闭后立即在第一个位置执行脚本,请使用K00scriptname命名.脚本启动将首先根据升序执行K,然后使用S编写脚本.

ln -s /etc/init.d/script /etc/rc0.d/K00scriptname

Shutdown命令会将停止信号发送到脚本,你的脚本(K00scriptname)应该具有停止功能,例如

stop()
{
  echo "executing scriptname"
  "Your script logic"
}
case "$1" in
  stop)
    stop
    ;;
esac
Run Code Online (Sandbox Code Playgroud)

最重要的是,只有在/ var/lock/subsys文件夹中存在锁定文件时才会执行K00scriptname,因此请执行"touch/var/lock/subsys/scriptname",然后通过执行shutdown来检查.


kon*_*box 1

尝试为您的脚本设置可执行权限。有时您需要这样做才能激活它。

chmod 755 /etc/init.d/sendshtmail
Run Code Online (Sandbox Code Playgroud)

还尝试对命令使用绝对路径,同时引用其他变量。

echo "${SHUTDOWNBODY}" | /usr/bin/mutt -s "${SHUTDOWNSUBJECT}" "${EMAIL}"
Run Code Online (Sandbox Code Playgroud)

另一种尝试是将您的用户切换到当前用户,例如

echo "${SHUTDOWNBODY}" | su -l -c "/usr/bin/mutt -s \"${SHUTDOWNSUBJECT}\" \"${EMAIL}\"" yourusername
Run Code Online (Sandbox Code Playgroud)