给我发送有关计算机关机的电子邮件

给我发送有关计算机关机的电子邮件

我希望计算机每次启动或关闭时都给我发送一封电子邮件。我发现此代码为 CENTOS 编写并正在尝试使其适应 Ubuntu。

代码如下:

#!/bin/sh
# chkconfig: 2345 99 01
# Description: Sends an email at system start and shutdown

#############################################
#                                           #
# Send an email on system start/stop to     #
# a user.                                   #
#                                           #
#############################################

EMAIL="[email protected]"
RESTARTSUBJECT="["`hostname`"] - System Startup"
SHUTDOWNSUBJECT="["`hostname`"] - System Shutdown"
RESTARTBODY="This is an automated message to notify you that "`hostname`" started successfully.

Start up Date and Time: "`date`
SHUTDOWNBODY="This is an automated message to notify you that "`hostname`" is shutting down.
Shutdown Date and Time: "`date`
LOCKFILE=/var/lock/subsys/SystemEmail
RETVAL=0

# Source function library.
. /lib/lsb/init-functions

stop()
{
echo -n $"Sending Shutdown Email: "
echo "${SHUTDOWNBODY}" | mail -s "${SHUTDOWNSUBJECT}" ${EMAIL}
RETVAL=$?

if [ ${RETVAL} -eq 0 ]; then
rm -f ${LOCKFILE}
success
else
failure
fi
echo
return ${RETVAL}
}

start()
{
echo -n $"Sending Startup Email: "
echo "${RESTARTBODY}" | mail -s "${RESTARTSUBJECT}" ${EMAIL}
RETVAL=$?

if [ ${RETVAL} -eq 0 ]; then
touch ${LOCKFILE}
success
else
failure
fi
echo
return ${RETVAL}
}

case $1 in
stop)
stop
;;

start)
start
;;

*)

esac
exit ${RETVAL}

与原始代码不同的地方/lib/lsb/init-functions是为了兼容 Ubuntu。

我在尝试运行此程序时遇到的错误是(文件的名称是mailme

Unit mailme.service failed to load: No such file or directory

我该怎么做才能让这段代码在 Ubuntu 上运行?修改幅度大吗?

答案1

从您的错误消息来看,您运行的 Ubuntu 版本似乎使用了 systemd。我认为,如果您将邮件发送部分分离到单独的脚本中并使用 systemd 服务执行它会更容易。

因此,删除邮寄部分(并简化它):

#! /bin/sh
EMAIL="[email protected]"
SUBJECT="[$HOSTNAME] - System $1"

if [ "$1" = startup ]
then
    ACTION="started successfully"
else
    ACTION="is shutting down"
fi

# a printf format string to simplify a long body
BODY="This is an automated message to notify you that %s %s.\nDate and Time: %s\n"

printf "$BODY" "$HOSTNAME" "$ACTION" "$(date)" | mail -s "${SUBJECT}" "${EMAIL}"

将其另存为,例如/usr/local/bin/bootmail.sh,使其可执行,等等。

然后,要创建 systemd 服务,请创建一个/etc/systemd/system扩展名的文件.service(例如/etc/systemd/system/bootmail.service),其中包含:

[Unit]
Description=Run Scripts at Start and Stop

[Service]
Type=oneshot
RemainAfterExit=true
ExecStart=/usr/local/bin/bootmail.sh startup
ExecStop=/usr/local/bin/bootmail.sh shutdown

[Install]
WantedBy=multi-user.target

现在,执行以下操作:

systemctl daemon-reload
systemctl enable bootmail.service

现在,您应该在启动和关闭时收到邮件(假设邮件配置正确等)。

相关内容