Transferring read-protected files with rsync and sudo
Laurent Bachelier2 min read
This issue might be familiar to some of you: you have ssh access to a server with sudo rights on it and you want to transfer files with rsync. However, since these files are not directly accessible from your ssh user (because they belong to some other user), the rsync fails with
rsync: mkstemp “XXX” failed: Permission denied (13)
rsync error: some files could not be transferred (code 23)
if you tried to write a file in a protected directory or
rsync: send_files failed to open “XXX”: Permission denied (13)
rsync error: some files could not be transferred (code 23)
if you tried to read a protected file.
Here is the simple procedure to solve this problem and transfer the files in one go:
- Authenticate with sudo, which by default will cache your authorization for a short time
- Then use your favorite transfer program with one small change: use
sudo
on the remote end
Authenticating with sudo
ssh -t user@host “sudo -v”
The -v
option of sudo
option will either give you five more minutes of “free sudoing”, or ask for your password. The -t
option of ssh
forces an interactive session, so that sudo
is able to ask for your password.
If for some reason your password is displayed on your screen, you can run stty -echo
before and stty echo
after to hide it.
Transferring the file
If you want to get the /root/protected.txt file for example, you will then have to use rsync in the following way:
rsync —rsync-path=‘sudo rsync’ user@host:/root/protected.txt ./
You can use any rsync
command as long as you have the correct rsync-path, which by default is just “rsync”.
This tip can work with other programs besides rsync, as long as it lets you change the remote program that will be executed. For instance, you can change the --receive-pack
option for git push
.