首页 文章

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

提问于
浏览
0

有谁知道systemd请帮我弄清楚我做错了什么?

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

我正在运行Linux Mint 18 - 基于Ubuntu 16.04 - 如果这对答案产生影响 .

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

我已经测试了bash脚本,当它运行时,它会做我想要的 .

我已经通过运行systemctl stop mardibackup.service手动停止了mardibackup.service,它可以实现我想要的 .

所以我希望我没有正确定义单元或正确调用服务,但我无法弄清楚该怎么做 .

具体问题:

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

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)创建在系统关闭/重新启动时调用shutdown / restart脚本的符号链接

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)

有想法的人吗?

1 回答

  • 0

    感谢@le_me和他提交的问题

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

    我在[Unit] definiiton中错过了一行

    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
    

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

    我想在调用服务之前驱动器已被卸载,因此服务无法完成预期的操作 .

    如果有人看到这方面的缺陷,请随时发表评论 .

相关问题