Here’s how to rsync something to a remote host as root without allowing root logins and with directory restriction. I did that because I wanted to sync /srv across servers.
In general it will use rsync over ssh, sudo, rrsync and a remote non-root user. I assume that rsync will run from srv1 to srv2.
First you will need the rrsync (or rrsync.pl) script ad the server side that’s part of the rsync package. In Debian you can find it at /usr/share/doc/rsync/scripts/rrsync.gz. This script acts as the server side and will restrict the destination directory (a’la chroot).
In short the server side will run “rrsync /srv”. Then the client side will do something like this:
# rsync /srv remote:/
and / will be relative to /srv that was defined as a parameter to rrsync.
You can put rrsync under /usr/local/bin.
User on srv2
At the destination server we will need a user that will be used for the ssh session. So go and create a user named ‘syncer’ on srv2. I’d avoid a username of ‘rsync’ as it may be used for other reasons at some point.
sudo on srv2
The user on srv2 should be able to run rrsync with sudo and with the -E parameter. -E is required in order to pass the checks of the rrsync script which checks for SSH_ORIGINAL_COMMAND in the environment. Feel free to make this even more strict to allow only this environment variable if you like.
Sample sudoers entry (e.g. to be put in /etc/sudoers.d/syncer):
syncerÂ Â Â ALL=SETENV:NOPASSWD:/usr/local/bin/rrsync /srv
Obviously we need the user to be able to run this without requiring a password. SETENV will allow for the -E parameter to sudo.
Next step is to allow root@srv1 to ssh as syncer@srv2 using public key. If you don’t have a key pair generated for root@srv1 then go ahead and create it:
Then copy the contents of /root/.ssh/id_rsa.pub and paste them in syncer@srv2’s authorized_keys file which is most probably at /home/srv2/syncer/.ssh/authorized_keys. Create the directory and the file if they don’t exist.
To make rrsync work and make things safer you need to use the command=”..” parameter and you should use the from=”..” parameter. So your authorized_keys file will look something like this:
from="srv1",command="sudo -E /usr/local/bin/rrsync /srv" ssh-rsa AAAA......siW root@srv1
Don’t forget to ssh at least once from srv1 to srv2 by hand in order to accept srv2’s key and let ssh have it in in known_hosts.
Finally you are done and you can do the rsync:
# rsync --rsh=ssh -a --delete /srv syncer@srv2:/