2016-09-04 23 views
0

有誰知道systemd請幫我弄清楚我做錯了什麼?如何使用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)創建下面的腳本,使用幸運備份生成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)創建將調用關機/重啓腳本時系統關閉的符號鏈接/重啓

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)

任何人有一些想法?

回答

0

謝謝@le_me和他提交了這個問題

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

我錯過了我的[單位]一行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 

上面的指令,其餘都還是不錯的。

我猜驅動器在服務被調用之前就被卸載了,所以服務不能完成它應該做的事情。

如果有人發現此漏洞,請隨時發表評論。

+0

以上是應該閱讀「所以,它現在正在工作......」 – Ramblin