Unix – Syncing local and remote directories using rsync+ssh+public key as a user different to the ssh key owner

deploymentpermissionsrsyncsshunix

The goal is to sync local and remote folders over ssh.

My current user is user1, and I have a password-less access setup over ssh to a server server1.
I want to sync local folder with a folder on server1 by means of rsync utility.
Normally I would run:

rsync -rtvz /path/to/local/folder server1:/path/to/remote/folder

ssh access works as expected, rsync is able to connect over ssh, but it returns "Permission denied" error because on server1 the folder /path/to/remote/folder is owned by user2:user2. File permissions of the folder do not allow it to be altered by anyone else.
user1 is a sudoer on server1 so sudo su - user2 works during ssh session.
How to forse rsync to switch the user when it ssh'ed to the server?

Adding user1 to the group user2 is not an option because all user/group management on the server is done automatically and replicated from a central repo every X mins, that I have not access to.

Same for changing permissions/ownership of the destination folder: it is updated automatically on a regular basis with a reset of all permissions.

Possible solution coming to my mind is a script that syncs the local folder with a temporary intermediate remote folder owned by user1 on the server, and then syncs two remotes folders as user2.

Googling for a shorter and prettier solution did not yield any success.

Best Answer

I have not tried it by myself, but how about using rsync's '--rsync-path' option?

rsync -rtvz --rsync-path='sudo -u user2 rsync' /path/to/local/folder server1:/path/to/remote/folder