Syncing local and remote directories using rsync+s

2019-04-06 21:46发布

问题:

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.

回答1:

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


回答2:

To fix the permissions problem you need to run rsync over an an SSH session that logs in remotely as user2:

rsync avz -e 'ssh -i privatekeyfile' /path/to/local/folder/ user2@server1:/path/to/local/folder

The following answer explains how to setup the SSH keys.

  • Ant, download fileset from remote machine


回答3:

Set up password-less access for user1 to access user2@server1, then do:

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