Using rsync with SSH keys

Both my server and pc are running Ubuntu 20.04. For accessing my server (ksm-server1) with SSH I use SSH keys. Login into my server over SSH works as expected. But when I copy files from my client pc to my server, it seems it’s not using my SSH keys. Let me explain below.

On my pc I setup my .ssh/config file like this:

Host ksm-server1
  IdentityFile ~/.ssh/ksm-server1_key
  Port 22
  User kees

To login on my server from my pc I use:

ssh ksm-server1

This works as expected: the server let’s me login by using my passphrase.

But when I use rsync like this on my pc:

sudo rsync -a /home/kees/test ksm-server1:/home/kees/documenten/test_rsync

it first asks me for the password for root on the server. What I would expect is that it uses my SSH-key to login to the server and not asking me for a password on the first place, but certainly not the password for root. This is something I don’t understand. Could someone explain this to me?

When I use rsync like this:

sudo rsync -a /home/kees/test kees@ksm-server1:/home/kees/documenten/test_rsync

the server asks me for the password of user kees on the server. If I enter this password, rsync works as expected.

Any help is appreciated!

First, try not using sudo before rsync, because sudo uses your root user’s ssh key, which probably doesn’t exist.

Following that, if that doesn’t work, just do it the manual way

rsync -a -e 'ssh -i /home/kees/.ssh/ksm-server1_key' /home/kees/test kees@ksm-server1:/home/kees/documenten/test_rsync
1 Like

Biky has a good point. If you use sudo, then the SSH keys need to exist for root also.


Yeah, you’re both right. Silly of me I didn’t come up with that myself. It’s obvious that it wants to use root’s ssh-key when you run rsync as sudo. Without sudo it works as expected. Thank you both for taking time to help me :+1:, much appreciated.