系统关闭时使用rsync进行备份

系统关闭时使用rsync进行备份

我创建了一个脚本,使用 rsync 将选定的文件夹备份到远程服务器。当我手动运行脚本时,一切正常。但我希望它在系统关闭时自动完成。这就是我收到错误的地方:

 13:19:12 mx rsync_update.sh[9512]: Host key verification failed.
 13:19:12 mx rsync_update.sh[9506]: rsync: connection unexpectedly closed (0 bytes received so far) [sender]
 13:19:12 mx rsync_update.sh[9506]: rsync error: unexplained error (code 255) at io.c(231) [sender=3.2.7]

单位看起来像这样

[Unit]
Description=Clean on reboot,shutdown
Requires=network.targe rsync.service 
After=multi-user.target

[Service]
Type=oneshot
RemainAfterExit=yes
ExecStart=/bin/true
ExecStop=/usr/local/bin/rsync_backup.sh

[Install]
WantedBy=multi-user.target

Rsync 通过 ssh 工作。

答案1

当一个关闭启动(init 0、init 6)该服务会启动一堆其他服务,然后杀死现有服务。如果您没有在自定义 systemd 脚本中明确指定在rsync其他内容被终止之前启动您的副本,那么您的服务可能会在关闭过程中的任何时间点发生,这是很糟糕的。它发生在ssh服务被杀死之前还是之后?它发生在文件系统卸载之前还是之后?网络被杀死之前或之后?等等。

您希望确保 rsync 备份最好是您键入后发生的第一个服务重启或者关闭,并且其他服务/目标正在运行,例如sshdnetwork-online.target 我相信下面这个链接中的答案,我认为它主要有您的解决方案,但不一定只有一个答案响应。考虑到您的要求,您在选择Wanted By和指定的内容时需要一些额外的考虑Requires。我有机会发布您所要求的 systemd 服务模板类型。

如何在关机前使用 systemd 运行脚本?

相关内容