Copying files to privileged locations with rsync
I work with many remote servers and eventually I need to copy a file (or a
bunch of them) to a directory that requires administrative privileges. My
normal user does not have permissions for that, but I can get it via sudo
.
Copying files to other servers is simple and I usually use
rsync
for that. After copying the
files to a temporary location, I can use ssh
to move files around.
If the remote server is set up to not ask for passwords when using sudo
, this
task can be done easily:
$ scp afile user@host.com:/tmp/
$ ssh user@host.com sudo mv -v /tmp/afile /etc/default/
renamed '/tmp/afile' -> '/etc/default/afile'
The scp
command copies a file to a temporary directory on the remote server
and then we execute sudo mv -v /tmp/afile /etc/default/
via ssh
on the
server to move the file to the final destination.
Note: I used
scp
in this example as it is simpler to type, but scp was deprecated. I usersync
instead.
I really like the -v
flag for mv
in this command, it serves as a
confirmation that the file was indeed copied. -v
is short for --verbose
and, when used, mv
tells you what file is being moved.
But this approach requires typing two commands, while we could use only one
rsync
command:
$ rsync -avzP --rsync-path="sudo rsync" afile user@host.com:/etc/default/
sending incremental file list
afile
3 100% 0.00kB/s 0:00:00 (xfr#1, to-chk=0/1)
sent 107 bytes received 35 bytes 31.56 bytes/sec
total size is 3 speedup is 0.02
The magic words here are --rsync-path="sudo rsync"
. This flag specifies the
path for the rsync
executable on the remote machine. By using sudo rsync
remotely, we can access the directory we want!
Of course, this approach also requires the remote user to be able to sudo
without typing the password.
The other command line flags are:
-a
(short for--archive
): does quite a lot, but in summary is to be recursive and preserve almost all file attributes.-v
(short for--verbose
): to see what is going on with more details.-z
(short for--compress
): to compress the data when transferring files.-P
(short for--partial --progress
): to show transfer progress and keep partial files in case of connection loss.
Summary
--rsync-path="sudo rsync"
is the magical flag to be sudo
on a remote
machine, when the server is configured with passwordless sudo
.