Take the 2-minute tour ×
Super User is a question and answer site for computer enthusiasts and power users. It's 100% free, no registration required.

I have a file on server A (which is behind a NAT so not directly addressable). The file needs to be copied to server B in a directory restricted to root. I have an account on server B with sudo privileges. What is the syntax for the scp command?

share|improve this question
i've closed the older question as a duplicate of this one, since the question asker never regained ownership of that question. –  quack quixote May 8 '10 at 0:51
add comment

5 Answers

up vote 23 down vote accepted

First, you need to copy the file to a place where you have write access without sudo,

scp yourfile serverb:

Then move the file using sudo

ssh serverb sudo mv yourfile /path/to/the/destination

If you do not have a writable place, make a temporary dir with write permission for your user.

ssh serverb sudo mkdir tempdir && sudo chmod 777 tempdir
scp yourfile serverb:tempdir
ssh serverb mv tempdir/yourfile /path/to/the/destination
share|improve this answer
/tmp is a good place for writing temporary files that (usually) all users have access to. –  Doug Harris May 7 '10 at 23:28
@Doug: Note that /tmp could be in RAM or in / mounting point, and not necessarily large enough to host big files. –  Ravachol Dec 12 '11 at 16:38
add comment

You can use ssh and tar to work around this:

ssh -t host 'sudo -v'
ssh -C host 'cd /; sudo tar cf - path/to/file/or/dir' | tar xpsf - --preserve

This first updates your sudo timestamp (asking for a password if necessary, which requires a tty (ssh -t)), and then uses sudo to create a tarball remotely and extract it locally.

"tar" on RedHat 5 requires the "--preserve" options to come after the "xpsf -" command.

share|improve this answer
Just a note: if you get tar: Invalid replacement string, removing -s in the seems to fix it (not sure what you need the s for anyway). Many thanks; this is awesome. –  RecursivelyIronic Feb 15 '13 at 21:55
add comment

With SCP, you have to do in two steps, however, you can do it in one with rsync as follows:

rsync --rsync-path="sudo rsync" <LOCALFILE> USER@SERVER2:/root

Edit: This does require NOPASSWD sudo. If you have to enter the password for sudo, then the two step way is needed.

share|improve this answer
add comment

I've written a short program for this. You will need python 2.7 and fabric.


share|improve this answer
add comment
ssh user@serverB

user@serverB: sudo scp user@remote:/path/file   /path/tofileonB
share|improve this answer
add comment

Your Answer


By posting your answer, you agree to the privacy policy and terms of service.

Not the answer you're looking for? Browse other questions tagged or ask your own question.