Systemd:如何仅在关机时执行脚本(而不是在重启时)

ben*_*600 8 linux shutdown arch-linux systemd

这里有很多解决方案可以在关机/重启时执行脚本,但我希望我的脚本只在关机时执行。

我试图把我的脚本在/ usr / lib中/ systemd / systemd关机,并检查1 $参数,因为看到这里,但它不工作。

有任何想法吗 ?

系统:archlinux 与 gnome-shell

$systemctl --version                                                                                                                                                                                 
systemd 229
+PAM -AUDIT -SELINUX -IMA -APPARMOR +SMACK -SYSVINIT +UTMP +LIBCRYPTSETUP +GCRYPT +GNUTLS +ACL +XZ +LZ4 +SECCOMP +BLKID +ELFUTILS +KMOD +IDN
Run Code Online (Sandbox Code Playgroud)

ben*_*600 9

我终于找到了如何做到这一点。

这有点骇人听闻的想法,但它有效。

我已经使用了这个线程的一部分:https : //stackoverflow.com/questions/25166085/how-can-a-systemd-controlled-service-distinguish-between-shutdown-and-reboot

和这个线程: 如何在关机前使用 systemd 运行脚本?

我创建了这个服务 /etc/systemd/system/shutdown_screen.service

[Unit]
Description=runs only upon shutdown
Conflicts=reboot.target
After=network.target

[Service]
Type=oneshot
ExecStart=/bin/true
ExecStop=/bin/bash /usr/local/bin/shutdown_screen
RemainAfterExit=yes

[Install]
WantedBy=multi-user.target
Run Code Online (Sandbox Code Playgroud)

这将在关闭/重启/停止/任何时候执行。(不要忘记启用它)

在我的脚本中,/usr/local/bin/shutdown_screen 我输入了以下内容:

#!/bin/bash
# send a shutdown message only at shutdown (not at reboot)    
/usr/bin/systemctl list-jobs | egrep -q 'reboot.target.*start' || echo "shutdown" | nc 192.168.0.180 4243 -w 1
Run Code Online (Sandbox Code Playgroud)

这将向我的 arduino 发送关闭消息,后者将关闭我的屏幕。


ILM*_*o_7 5

根据systemd.special手册页,您应该使用Before=poweroff.target.

关机目标

A special target unit for shutting down and powering off the system.

Applications wanting to power off the system should start this unit.

runlevel0.target is an alias for this target unit, for compatibility with SysV.
Run Code Online (Sandbox Code Playgroud)

此外,正如我在评论中提到的,您应该将自定义脚本放入/etc/systemd/system/. 该/usr/lib/systemd/system/目录旨在用于系统提供的脚本。

所以,也许是这样的:

[Unit]
Description=runs only upon shutdown
DefaultDependencies=no
Conflicts=reboot.target
Before=shutdown.target
Requires=poweroff.target

[Service]
Type=oneshot
ExecStart=/bin/true
ExecStop=/usr/local/bin/yourscript
RemainAfterExit=yes
Run Code Online (Sandbox Code Playgroud)