在 Debian(及大多数 Linux 发行版)里,“定时器”通常指 systemd timer(现代 Debian 默认),也可能指 cron。下面分别说明权限相关设置和注意事项。
systemd timer 通常由两部分组成:
.timer 文件(定义何时触发).service 文件(定义执行什么)系统级(推荐)
/etc/systemd/system/
权限建议:
sudo chmod 644 /etc/systemd/system/xxx.timer
sudo chmod 644 /etc/systemd/system/xxx.service
sudo chown root:root /etc/systemd/system/xxx.*
用户级
~/.config/systemd/user/
权限:
chmod 600 ~/.config/systemd/user/xxx.timer # 仅自己可读
在 .service 文件中指定用户:
[Service]
User=appuser
Group=appgroup
ExecStart=/usr/local/bin/myscript.sh
⚠️ 注意:
User= 时,系统 timer 默认以 root 运行普通用户可以使用自己的 timer:
systemctl --user enable mytimer.timer
systemctl --user start mytimer.timer
但:
确保执行脚本权限安全:
sudo chown root:root /usr/local/bin/myscript.sh
sudo chmod 755 /usr/local/bin/myscript.sh
/var/spool/cron/crontabs/用户名/etc/cron.d/、/etc/cron.daily/ 等/etc/cron.allow # 白名单
/etc/cron.deny # 黑名单
示例(仅允许 alice):
echo alice > /etc/cron.allow
chmod 700 script.sh
chown user:user script.sh
✅ 推荐做法
User=journalctl -u xxx.service
journalctl -u xxx.timer
❌ 不推荐
如果你能提供:
我可以给你一份可直接用的 .timer + .service 示例。