如何在用户登录后启动 systemd 服务并在用户注销前停止它

如何在用户登录后启动 systemd 服务并在用户注销前停止它

我有一台 Fedora 23 机器。

我有一个目录/文件同步 bash 脚本,可将我的本地 /home 目录同步到远程目录(在 NAS 机器中)。我手动运行它,但我想创建一个 systemd 服务并使其更加灵活,因为其他人使用自己的用户凭据使用我的电脑,我想知道用户何时登录并在之后启动我的服务。

我可以从我的服务的 systemd 文件中执行某些操作吗?或者我必须从脚本中的代码中进行检查?

我只需要确保我可以访问环境变量(如$USER)并将其作为服务运行。

我的主要文档来源是此链接https://access.redhat.com/documentation/en-US/Red_Hat_Enterprise_Linux/7/html/System_Administrators_Guide/sect-Managing_Services_with_systemd-Unit_Files.html

答案1

使用 systemd它已经包含对用户会话的支持,事实上您应该已经(不知不觉地)依赖它了。

创建服务目录

mkdir -p $HOME/.local/share/systemd/user

创建编辑服务文件(vim、gedit、geany - 任何你想要的)

vim $HOME/.local/share/systemd/user/my.service

如果它是一项永久服务,它应该大致看起来像这样。

[Unit]
Description=My very own Service
[Service]
Type=simple
TimeoutStartSec=0
ExecStart=/path/to/start/script arguments
[Install]
WantedBy=default.target

但听起来你宁愿触发一次,然后好好利用它,所以最好使用像这样的一次性配置:

[Service]
Type=oneshot
RemainAfterExit=true
StandardOutput=journal
ExecStart=/path/to/start/script arguments
ExecStop=/path/to/stop/script arguments
[Install]
WantedBy=default.target

当然,这假设你的脚本是可执行的,即:

chmod a+x /path/to/start/script
chmod a+x /path/to/stop/script

否则,您需要在前面添加相应解释器的路径:

ExecStart=/bin/bash /path/to/start/script arguments

现在重新加载 systemd(并重新登录以进行测试)

systemctl --user enable my.service # enables the service
systemctl --user # should display your new unit in the list
journalctl --user should show the log

如果您需要更多信息,请参阅Arch-Wiki例如。 askubuntu 线程有各种想法,顺便提一下,也包括我的想法。

您可以通过全局定义服务将行为扩展至其他用户(如果您是 root 用户)。为此,您需要在以下位置创建服务文件:/usr/share/systemd/用户/不在$HOME/.local/share/systemd/用户

答案2

我知道这个问题已经有几年了,但 anx 的回答帮助了我。所以,我想它仍然有意义。另外,这更像是一条评论,但我没有这个权限,所以我把它发布为“答案”。无论如何……

运行 Linux Mint 19 时,当脚本位于“$HOME/.local/share/systemd/user”时,我无法“启用”该服务。尝试这样做总是会导致错误。但是,我可以从“$HOME/.local/share/systemd/user”目录正常启动它。将脚本移至“/usr/share/systemd/user/”后,systemd 允许我毫无问题地启用它。

相关内容