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

Geo*_*Kaf 17 linux fedora bash systemd

我有一台 Fedora 23 机器。

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

我可以从我的服务的 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

小智 21

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

创建服务目录

mkdir -p $HOME/.local/share/systemd/user
Run Code Online (Sandbox Code Playgroud)

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

vim $HOME/.local/share/systemd/user/my.service
Run Code Online (Sandbox Code Playgroud)

如果它是一项永久性服务,它应该大致如下所示。

[Unit]
Description=My very own Service
[Service]
Type=simple
TimeoutStartSec=0
ExecStart=/path/to/start/script arguments
[Install]
WantedBy=default.target
Run Code Online (Sandbox Code Playgroud)

但听起来你更愿意触发一次,然后用好它,所以宁愿使用这样的 oneshot 配置:

[Service]
Type=oneshot
RemainAfterExit=true
StandardOutput=journal
ExecStart=/path/to/start/script arguments
ExecStop=/path/to/stop/script arguments
[Install]
WantedBy=default.target
Run Code Online (Sandbox Code Playgroud)

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

chmod a+x /path/to/start/script
chmod a+x /path/to/stop/script
Run Code Online (Sandbox Code Playgroud)

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

ExecStart=/bin/bash /path/to/start/script arguments
Run Code Online (Sandbox Code Playgroud)

现在重新加载 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
Run Code Online (Sandbox Code Playgroud)

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

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

  • 启用服务时需要 --user 标志。“systemctl --user 启用 my.service” (4认同)
  • 你好,答案很好。但它只有在服务应该在 **first** 登录时启动并在 **last** 用户会话时停止时才有效。 (2认同)
  • 警报 - 在您登录之前,无法告诉系统不要处理您的 .config/systemd/user 服务 - 这意味着如果您的 HOME 目录在您输入登录密码之前被加密,那么它就不起作用。 (2认同)