How to use SSH to copy a file to a remote server under a different user

linuxssh

I have a file on my local computer I wish to copy to a remote server using the SSH program (not scp, not rsync, not sftp), the local file is an SSL private key and I do not want to create any temporary copies on the remote server during the transfer.

The root user on the remote server cannot login via SSH for security reasons, however my remote user (with the same username as my local user) can make root changes through the sudo command after a password prompt.

Problem: How do I copy the local file, login via SSH, switch to the root user with sudo password prompt and then write the file to the remote server in a root user owned directory? And preferably all in a single line command!

Best Answer

cat is your friend:

cat key | ssh user@host sudo "cat > final_location"

But this would require passwordless authentication (might overcome using ControlMaster) and passwordless sudo (NOPASSWD or authentication using pam_ssh_agent_auth -- I recommend to give a try this one, if you are familiar with ssh-agent).

You might also want to temporary allow root logins (with public key -- there is option PermitRootLogin without-password, which does exactly what you want) and then you can simply use the scp method.

Otherwise I don't think there is any other reasonable way, except of Copy Paste method.

Related Question