6

Can I use scp to copy a file from a remote server which my login user can't read, but where I have permission to sudo to root (without password even)? How?

14

Try this:

ssh user@remotehost.domain sudo cat /path/to/restricted_file > /local/path

If your sudo requires typing in a password you will want to add -t just after the ssh in order to type in the sudo password.

What this does is run sudo cat file on the remote host, redirecting the output to a local file. On your local machine the file will be created by your shell with local user privileges.

  • This essentially means typing in your password twice: once for the starting the SSH session, and once for the sudo authentication. – Meredith Feb 25 '15 at 17:05
  • this is great. any idea if you can use this to do the opposite direction? eg take a local file and put it on a remote machine that would normally require sudo to copy for your user. – cavalcade Apr 8 '15 at 8:27
3

You should be able to do this by logging on to the remote machine with ssh and then launching the scp command from the remote machine to your local one:

ssh user@remote sudo scp /path/to/file user@local.machine.com:/local/path
  • I've tried this but it doesn't work in my network (even using the IP instead of local.machine name), there's probably a firewall or NAT between my desktop and the server. Any other options? – Daniel Serodio Jun 26 '13 at 14:43
  • @DanielSerodio that doesn't make sense. Can you scp if you ssh to the server and then switch to root? You will also need to make your local computer accessible by opening port 22 on your router and redirecting it to your machine. – terdon Jun 26 '13 at 14:53
  • 3
    This approach requires 2 ssh connections: local to remote and remote back to local. In other words both machines need to have ssh servers running and accessible. See my answer for a simpler solution. – jw013 Jun 26 '13 at 15:36
  • @jw013 of course, obvious in hindsight and much simpler! – terdon Sep 22 '14 at 10:52
1

I personally needed to gather a number of files I could only read with sudo and I wanted to do it in one go.

ssh user@remote 'cd /path/to; sudo tar zcvf - files*' > files.tar.gz

From there you just have to tar xf the file and get all of the files you want.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

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