Systemd:在网络仍在运行时,在关机前运行命令

Systemd:在网络仍在运行时,在关机前运行命令

我试图让 Systemd 运行一个脚本,在计算机关闭之前发送一封电子邮件。我了解 Systemd 以与启动服务相反的顺序终止服务,因此如果您输入After=network.target,您的服务将在 之前关闭network.target

然而,无论我在After=Wants=线路上放置了多少该死的依赖项,网络连接都会在我的电子邮件脚本运行之前断开。有时它会发送电子邮件,但绝大多数时候不会。这告诉我存在竞争条件,Systemd 在关闭网络服务之前不会等待我的脚本完成。

我的单元文件如下所示:

[Unit]
Description=Send email before shutdown
Wants=network.target nss-lookup.target network-online.target networking.service NetworkManager.service network-manager.service
After=network.target nss-lookup.target network-online.target networking.service NetworkManager.service network-manager.service

[Service]
Type=oneshot
RemainAfterExit=true
ExecStart=/bin/true
ExecStop=/home/user1/send_email.sh

[Install]
WantedBy=multi-user.target

该杂志说:

Jun 20 13:13:14 caesar systemd[1]: Stopped Availability of block devices.
Jun 20 13:13:14 caesar NetworkManager[699]: <info>  [1559301194.4305] device (wlx24050fd83726): state change: deactivating -> discon
Jun 20 13:13:14 caesar NetworkManager[699]: <info>  [1559301194.4629] dhcp4 (wlx24050fd83726): canceled DHCP transaction, DHCP clien
Jun 20 13:13:14 caesar NetworkManager[699]: <info>  [1559301194.4629] dhcp4 (wlx24050fd83726): state changed bound -> done
Jun 20 13:13:14 caesar NetworkManager[699]: <info>  [1559301194.4648] manager: NetworkManager state is now DISCONNECTED
Jun 20 13:13:14 caesar NetworkManager[699]: <warn>  [1559301194.4661] sup-iface[0xb4fd40,wlx24050fd83726]: connection disconnected (
Jun 20 13:13:14 caesar NetworkManager[699]: <info>  [1559301194.4662] device (wlx24050fd83726): supplicant interface state: complete
Jun 20 13:13:14 caesar send_email.sh[21782]: s-nail:  Certificate depth 2
Jun 20 13:13:14 caesar send_email.sh[21782]: s-nail:   subject = /C=US/O=DigiCert Inc/OU=www.digicert.com/CN=DigiCert 

....

Jun 20 13:13:56 caesar send_email.sh[21782]: s-nail: could not initiate SSL/TLS connection: error:00000000:lib(0):func

我认为这不应该这么困难。如果有人指出我做错了什么,我将不胜感激。

答案1

您还应该指定“Requires=network.target”行。更多信息请访问https://fedoramagazine.org/systemd-unit-dependency-and-order/

相关内容