I have a bash script, /home/localuser/backup-script.sh, with this snippet inside of it:
rsync -avzh \ -e "ssh -i /home/localuser/.ssh/id_ed25519" \ /home/localuser/backups/file-to-backup.gz \ [email protected]:/home/remoteuser/backups If I run it directly from shell, everything works like a charm, while if I run it through a systemd service I configured, I get the error [email protected]: Permission denied (publickey,password).
This is the service (/etc/systemd/system/backup.service) I configured:
[Unit] Description=Trigger script to perform backup [Service] Type=oneshot User=localuser ExecStart=/bin/bash /home/localuser/backup-script.sh [Install] WantedBy=multi-user.target And I usually run it via a timer, but I also get the same error if I start it directly via sudo systemctl start backup.service
The ssh service is correctly setup, as confirmed by the success I have running the script directly, or also by launching ssh [email protected].
I cannot figure out what is going on... any clue?
Additional info: I get same error replacing rsync with scp
Edit:
Following the Stewart's comment I tried to directly launch the script by running this command env -i /bin/bash --norc --noprofile backup-script.sh and in this case I'm prompted for the ssh key passphrase, so the problem is exactly what Stewart's comments are pointing to.
To work-around the problem with a simple solution (so avoiding to add ssh-agent as service, automatic keys loading, and automatic passphrase entering on boot), I changed the rsync command in my script, replacing the second line (-e ...) with this one: --rsh="/usr/bin/sshpass -p remoteuser_pwd ssh -o StrictHostKeyChecking=no -l remoteuser":
The result is similar: if I launch it directly, it works fine. If I launch it via the service it doesn't work: but this time with no errors, it simply hangs. And if I launch it by env -i /bin/bash --norc --noprofile backup-script.sh it hangs too, in the same way.
Changing the backup.service by adding --login in this way ExecStart=/bin/bash --login /home/localuser/backup-script.sh won't solve the issue.
remoteuserand the private key~/.ssh/id_ed25519with that host? If so, you can simplify your rsync command by creating a~/.ssh/configfile with a clause associating the username and private key file with that host.localuserand not as another user who can't read the private key file? Perhaps add a command to check, such astouch /tmp/backup.service.test.$$in the script before the rsync command...localuser's home a file is created by the same script, and the owner is correctly set tolocaluser/bin/bash --noprofile --norc /home/localuser/backup-script.sh. If you reproduce the problem from your interactive terminal, then we know where to start looking./etc/profile,~/.bash_profile,~/.bash_login, or~/.profile, then add/bin/bash --login ...to read those. If you have something in/etc/bash.bashrcor~/.bashrc, then consider moving that to one of the previous files.