创建服务 /usr/lib/systemd/system/
[unit] # 服务描述(自定义,便于识别) description=sftp directory sync service (inotifywait + rsync daemon) # 服务依赖:网络启动后、rsync 服务启动后再启动本服务(确保网络和依赖可用) after=network.target rsyncd.service # 服务文档(可选,指向命令手册) documentation=man:inotifywait(1) man:rsync(1) [service] # 服务类型:simple(前台运行,适合持续监控的脚本) type=simple # 执行服务的用户/组(建议用 root,避免目录、密码文件权限不足) user=root group=root # 工作目录(脚本所在目录,避免相对路径问题) workingdirectory=/usr/local/bin/sftp_sync # 核心:服务启动命令(脚本绝对路径,必须正确) execstart=/usr/local/bin/sftp_sync/sftp_sync_daemon.sh # 服务意外退出时自动重启(确保稳定性,如脚本崩溃后恢复) restart=always # 重启间隔(意外退出后,5秒再重启,避免频繁重启) restartsec=5 # 停止服务时,杀死所有子进程(避免 inotifywait 残留) killmode=control-group # 输出重定向到 journalctl(可通过 journalctl 查看服务运行日志) standardoutput=journal standarderror=journal [install] # 服务安装目标:多用户模式下开机自启(适配服务器环境) wantedby=multi-user.target
设置服务文件权限:所有者读写,其他用户只读
chmod 644 /usr/lib/systemd/system/sftp-sync-daemon.service
systemctl 配置
- 重新加载 systemd 配置
systemctl daemon-reload
- 启动服务
systemctl start sftp-sync-daemon
- 查看服务状态(关键!确认是否正常运行)
systemctl status sftp-sync-daemon -l
总结
以上为个人经验,希望能给大家一个参考,也希望大家多多支持代码网。
发表评论