scp to remote server with sudo
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?
17 Answers
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/destinationIf 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 6 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:/rootNote: This does require NOPASSWD sudo configuration. If you have to enter the password for sudo, then the two step way is needed.
To copy directory, you need to add -r parameter. And -v for verbose output.
To use above method with credentials, you need to add them into your ~/.ssh/config file, e.g.
Host SERVER2 HostName server2.example.colm User USER #IdentityFile ~/.ssh/custom_key.pem 4 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 - --preserveThis 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.
3You can use sftp with sudo command, for instance:
sftp -s 'sudo -u REMOTE_SUDO_USER /usr/libexec/openssh/sftp-server' REMOTE_USER@HOST 2 First, you need to copy the file to a place where you have write access without sudo, You can do the following two steps.
Step 1:scp filename newserver
Step 2:ssh newserver sudo mv filename /path/to/the/destination
for more information read scp tutorial
If you need to type password for sudo every-time, you can save it to a file:
echo "Enter password: "; read -s password; echo $password > password_fileand then send it along with the source file.
cat password_file source_file | ssh remote_host 'sudo -S sponge target_file'You can use tee instead of sponge if you don’t have moreutils.
current server $ sudo scp username@server:source/path/filename /tmp/It will copy specific file from source to /tmp/ in current server
3