在systemd中使用mail发送邮件失败的坑

Posted by Remilia Scarlet on July 17, 2019

目标:写一个自动发送邮件的shell脚本,用systemd去定时执行,结果systemd发送邮件时失败,单独运行shell脚本却可以成功运行

定时器教程https://www.ruanyifeng.com/blog/2018/03/systemd-timer.html

发送邮件脚本mail.sh:

#!/usr/bin/env bash

echo "This is the body" | /usr/bin/mail -s "Subject" someone@example.com

定时器的mytimer.service内容:

[Unit]
Description=MyTimer

[Service]
ExecStart=/bin/bash /path/to/mail.sh

原因:mail在发送邮件的时候会fork出一个sendmail的进程来实现功能,而sendmail会变成一个守护进程。systemd在执行玩这个任务的时候会杀死其进程组下的所有进程,所以sendmail也被直接杀死,导致了邮件无法发送。解决的办法是在service单元下修改killmode为process。process表示只杀主进程,这样在退出后sendmail也不会被systemd强制杀死。

修改后的mytimer.service内容为:

[Unit]
Description=MyTimer

[Service]
KillMode=process
ExecStart=/bin/bash /path/to/mail.sh

参考链接:

https://unix.stackexchange.com/questions/231200/usr-bin-mail-call-in-execstart-not-sending-any-mail

https://www.ruanyifeng.com/blog/2016/03/systemd-tutorial-part-two.html


| 访问量: