0

I created a script that backs up the selected folder to a remote server using rsync. Everything works fine when I manually run the script. But I would like it to be done automatically when the system shuts down. And this is where I get an error:

 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]

The unit looks like this

[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 works via ssh.

Kusalananda
  • 333,661

1 Answers1

0

When a shutdown is initiated (init 0, init 6) that service kicks off a bunch of other services that then kills existing services. If you don't explicitly specify in your custom systemd script to kick off your rsync copy before other things are killed, then your service can happen at any point in time during the shutdown process which is bad. Does it happen before or after the ssh service is killed? Does it happen before or after the file system is unmounted? Before of after the network is killed? And so on.

You want to make sure your rsync backup is, preferably, the very first service that happens after you type reboot or shutdown, and that other services/targets are running such as sshd and network-online.target I believe the answers here in this link below, I think it mostly has your solution but not necessarily in only one answer response. Given your requirements there will be some amount of extra consideration needed in your choices of what you specify for Wanted By and Requires. I get a chance I will post a template type of systemd service you're asking.

How to run a script with systemd right before shutdown?

ron
  • 6,575