gpt4 book ai didi

linux - 如何使用 systemd 激活脚本以在关机时备份文件

转载 作者:太空宇宙 更新时间:2023-11-04 12:44:02 25 4
gpt4 key购买 nike

知道 systemd 的人可以帮我弄清楚我做错了什么吗?

我正在尝试使用 systemd 触发一个脚本,该脚本将在用户关闭计算机时将文件从用户 (mardi) 的主目录同步(备份)到第二个驱动器。我宁愿让它只在关机时发生,但如果它变得太复杂,那么它可能在关机或重启时发生;我同意。 (我知道这不是一个特别好的备份策略,但它是整个过程中的第一步,所以请不要就此不可取性提供反馈;我想这样做,我想学习如何正确使用 systemd 所以请提供有帮助的反馈)

我正在运行 Linux Mint 18 - 基于 Ubuntu 16.04 - 如果这对答案有影响的话。

我在下面包含了我所做的事情,这是阅读 systemd 的手册页以及此处和其他地方的多个(通常是冲突的)论坛页面的结果,但我没有让它工作。

我已经测试了 bash 脚本,当它运行时,它会执行我想要的操作。

我通过运行 systemctl stop mardibackup.service 手动停止了 mardibackup.service,它做了我想要的。

所以我希望我没有正确定义单元或正确调用服务,但我不知道该做什么。

具体问题:

1) 为什么使用 multi-user.target 并在 ExecStop 被触发停止时调用服务?为什么不直接使用 shutdown.target 并在触发 ExecStart 时调用服务?

2) ExecStart=/bin/true 应该做什么?它似乎没有做任何事情,但它在许多推荐的答案中。

帮助??谢谢。

所以,这是我所做的:

1) 创建如下脚本,使用Lucky Backup生成rsync命令,放入/home/mardi/Templates/backupmardi.sh(当我从命令行手动执行它时,这是有效的)

#!/bin/bash

# This program synchronizes the contents of mardi home directory
# to the archives disk in /backups/mardi
#
# It checks if a current version of a file is already copied and if so, does not change anything
# If a file is deleted in the home directory, it is NOT deleted from the archives

rsync -h --progress --stats -r -tgo -p -l -D --update --delete-after /home/mardi /mnt/7b2152a9-af3c-4f63-9287-98aacd9cb8ff/backups/

2)修改脚本文件的权限,使其可执行

chmod +x /home/mardi/Templates/backupmardi.sh

3) 创建如下关机/重启服务来调用备份脚本,放入/etc/systemd/system/mardibackup.service(如果我通过 systemctl stop mardibackup.service 手动“停止”它,这就是我想要的)

[Unit]
Description=Backup Mardi home dir to archives

[Service]
Type=oneshot
RemainAfterExit=true
ExecStart=/bin/true
ExecStop=/bin/bash /home/mardi/Templates/backupmardi.sh

[Install]
WantedBy=multi-user.target

4) 创建系统关闭/重启时将调用关闭/重启脚本的符号链接(symbolic link)

systemctl enable /etc/systemd/system/mardibackup.service
(Note if you ever want to remove the symlink, enter: systemctl disable mardibackup.service)
systemctl start mardibackup.service

5) 关闭系统(我尝试了多次关机但它没有调用备份脚本backupmardi.sh)

有人有想法吗?

最佳答案

感谢@le_me 和他对问题的提交

https://superuser.com/questions/1016827/how-do-i-run-a-script-before-everything-else-on-shutdown-with-systemd

我在 [Unit] 定义中遗漏了一行

RequiresMountsFor=/home /mnt/7b2152a9-af3c-4f63-9287-98aacd9cb8ff

/home 是主驱动器主目录/mnt/7b2152a9-af3c-4f63-9287-98aacd9cb8ff 是我要向其发送备份文件的辅助驱动器

因此,它现在正在使用定义为 /etc/systemd/system/mardibackup.service 的服务

[Unit]
Description=Backup Mardi home dir to archives
RequiresMountsFor=/home /mnt/7b2152a9-af3c-4f63-9287-98aacd9cb8ff

[Service]
Type=oneshot
RemainAfterExit=true
ExecStart=/bin/true
ExecStop=/bin/bash /home/mardi/Templates/backupmardi.sh

[Install]
WantedBy=multi-user.target

上面的其余说明仍然很好。

我猜想在调用服务之前卸载了驱动器,因此服务无法执行它应该执行的操作。

如果有人发现其中的缺陷,请随时发表评论。

关于linux - 如何使用 systemd 激活脚本以在关机时备份文件,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/39316206/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com