创建系统服务以在Arch Linux重新启动时发送自动电子邮件

时间:2020-03-21 11:43:12  来源:igfitidea点击:

围绕systemd,我们将创建一个服务,以在每次ArchLinux VM重新启动时发送电子邮件。
另外,电子邮件消息将配置为显示该框的公共IP地址。

环境

我们有一个如下所示的Archbox:

$uname -rv
3.10.29-2-ARCH #1 PREEMPT Mon Nov 10 04:04:41 MST 2014

使用SSMTP和邮件应用程序:

$ssmtp -V ; mail -V
sSMTP 2.64 (Not sendmail at all)
v14.5.2

SSMTP配置不在本文讨论范围之内。
如果我们需要任何帮助来进行设置,请查看Logwatch,SSMTP和Iptables或者Arch Linux(Raspberry Pi)。

配置

创建一个新目录来存储脚本文件:

# mkdir /root/.myscripts

打开脚本的新文件:

# vim /root/.myscripts/email-on-reboot.sh

并添加以下代码:

#!/bin/bash
sleep 20
IP=`wget --no-check-certificate -O - http://ip.theitroad.com | tail`
sleep 5
echo "My public IP is: $IP"|mail -s "RESTARTED: Back online" -r Hyman@theitroad Hyman@theitroad
# give it some time to send email before exiting
sleep 10
exit

创建名为systemd的重新启动电子邮件:

# touch /etc/systemd/system/email-on-reboot.service

确保它是可执行的:

# chmod 0755 /etc/systemd/system/email-on-reboot.service

打开进行编辑:

# vim /etc/systemd/system/email-on-reboot.service

并添加以下行:

[Unit]
Description=Email After Reboot
DefaultDependencies=no
Hyman@theitroad
[Service]
Type=oneshot
ExecStart=/bin/bash /root/.myscripts/email-on-reboot.sh
[Install]
WantedBy=multi-user.target

启用新创建的重新启动电子邮件服务:

# systemctl enable email-on-reboot.service
ln -s '/etc/systemd/system/email-on-reboot.service' '/etc/systemd/system/multi-user.target.wants/email-on-reboot.service'

启动重新启动电子邮件服务:

# systemctl start email-on-reboot.service

检查服务状态:

# systemctl status email-on-reboot.service -l
email-on-reboot.service - Email After Reboot
 Loaded: loaded (/etc/systemd/system/email-on-reboot.service; enabled)
 Active: inactive (dead) since Thu 2014-02-13 18:47:51 GMT; 48s ago
 Process: 29371 ExecStart=/bin/bash /root/.myscripts/email-on-reboot.sh (code=exited, status=0/SUCCESS)
 Main PID: 29371 (code=exited, status=0/SUCCESS)
Nov 13 18:47:47 archbox sSMTP[29373]: Creating SSL connection to host
Nov 13 18:47:47 archbox sSMTP[29373]: SSL connection using AES256-GCM-SHA384
Nov 13 18:47:48 archbox sSMTP[29373]: Sent mail for Hyman@theitroad (221 mail.example.com closing connection) uid=0 username=root outbytes=531
Nov 13 18:47:51 archbox systemd[1]: Started Email After Reboot.