sshrsync

rsync remote files over SSH to my local machine, using sudo privileges on local side, and my personal SSH key


I want to sync a directory /var/sites/example.net/ from a remote machine to a directory at the same path on my local machine.

The remote machine only authenticates SSH connections with keys, not passwords.

On my local machine I have an alias set up in ~/.ssh/config so that I can easily run ssh myserver to get in.

I'm trying rsync -a myserver:/var/sites/example.net/ /var/sites/example.net/ but it fails because my local user does not have permission to edit the local directory /var/sites/example.net/.

If I try sudo rsync -a myserver:/var/sites/example.net/ /var/sites/example.net/ (just adding sudo), I can fix the local permission issue, but then I encounter a different issue -- my local root user does not see the proper ssh key or ssh alias.

Is there a way I can accomplish this file sync by modifying this rsync command? I'd like to avoid changing anything else (e.g. no changes to file perms or ssh setup)


Solution

  • Try this:

    sudo rsync -e "sudo -u localuser ssh" -a myserver:/var/sites/example.net/ /var/sites/example.net/
    

    This runs rsync as root, but the -e flag causes rsync to run ssh as your local user (using sudo -u localuser), so the ssh command has access to the necessary credentials. Rsync itself is still running as root, so it has the necessary filesystem permissions.