Rsync as another user (www-data)

I usually use a graphical SSH client to sync a local and remote directory. And I have to set the ownership of all the files from root to www-data.

Can I do the same with Rsync, only that I do it as www-data instead of root, so that I dont have to set the ownership afterwards?


It's not clear what you want to do, so let me assume that you want the local files to be owned by user A and the remote files to be owned by user B. If you run the following command as user A:

rsync [options] [email protected]:/path/to/remote/dir /path/to/local/dir

this would have the effect you want. But it's not really an rsync issue (so I'm not elaborating on what the above command will do, I'm focusing on your question); even with your graphical SSH client you should be able to do the same if you run it as user A and set it to log on to the remote system as user B.


Provided that you are running as root, use the chown option that is build into rsync:

sudo rsync --chown=www-data:group user@remoteIP:/var/www/html/ /var/www/html

(replace 'group' with your desired group, or just use --chown=www-data, also replace user, remoteIP and change the folders to your liking)

If you don't run the command as root the file ownership will not be changed since you need sudo for that. So you would have to run the command as www-data indeed, but that leads to other complications.


if you can sudo -u www-data then you can run rsync with that user. if your destination is on a different server, then you also need to set --rsync-path to the same (sudo -u www-data rsync). you also need to work around the tty issue (by using -t in your ssh), although depending on your distribution and ssh server settings, it could be very tricky. personally i think it is easier just to use root and do a chown afterwards, unless the server does not permit remote root login.