Systemd 服务脚本写入文件失败

Systemd 服务脚本写入文件失败

我想要基于用户的服务。因此我创建了[email protected]以下/etc/systemd/system内容。

[Unit]
Description=My Service

[Service]
Type=simple
ExecStart=/bin/bash ${HOME}/userscript
WorkingDirectory=${HOME}
Restart=always
RestartSec=2
User=%i

[Install]
WantedBy=multi-user.target

以下是${HOME}/userscript

#!/bin/bash
while true;
do
    echo $(date +%Y%m%d%a%H%M%S) >> log
    echo $USER >> log
    sleep 2
done

然后我使用以下命令启用并启动该服务:

systemctl enable myservice@john
systemctl start myservice@john

这是我检查服务状态时得到的结果:

[email protected] - myservice
   Loaded: loaded (/etc/systemd/system/[email protected]; enabled; vendor preset: enabled)
   Active: active (running) since Mon 2017-12-11 08:03:54 PST; 6s ago
 Main PID: 11558 (bash)
   CGroup: /system.slice/system-myservice.slice/[email protected]
           ├─11558 /bin/bash /home/john/userscript
           └─11603 sleep 2

Dec 11 08:03:54 my-system-hostname systemd[1]: Started myservice.
Dec 11 08:03:54 my-system-hostname bash[11558]: /home/john/userscript: line 4: log: Permission denied
Dec 11 08:03:54 my-system-hostname bash[11558]: /home/john/userscript: line 5: log: Permission denied
Dec 11 08:03:56 my-system-hostname bash[11558]: /home/john/userscript: line 4: log: Permission denied
Dec 11 08:03:56 my-system-hostname bash[11558]: /home/john/userscript: line 5: log: Permission denied
Dec 11 08:03:58 my-system-hostname bash[11558]: /home/john/userscript: line 4: log: Permission denied
Dec 11 08:03:58 my-system-hostname bash[11558]: /home/john/userscript: line 5: log: Permission denied
Dec 11 08:04:00 my-system-hostname bash[11558]: /home/john/userscript: line 4: log: Permission denied
Dec 11 08:04:00 my-system-hostname bash[11558]: /home/john/userscript: line 5: log: Permission denied

该服务应该每 2 秒写入一次日期时间和用户名,但这不会发生,相反,我收到权限错误。我已确认服务正在以 身份运行,我john可以echo正确设置它。当我尝试写入文件时出现权限问题。

有什么线索吗?

更新 1

以下是输出namei -lx /home/john/log

$ namei -lx /home/john/log
f: /home/john/log
Drwxr-xr-x root root /
drwxr-xr-x root root home
drwxr-xr-x john john john
-rw-rw-r-- john john log

答案1

我终于解决了。我必须添加WorkingDirectory指令,其值为~。它现在可以正常工作,没有任何权限问题。

感谢@muru

相关内容