Copying protected files between servers in one line?

It's easier to chain ssh with ssh than to chain ssh with sudo. So changing the ssh server configuration is ok, I suggest opening up ssh for root of each server, but only from localhost. You can do this with a Match clause in sshd_config:

PermitRootLogin no
Match Host localhost
    PermitRootLogin yes

Then you can set up a key-based authentication chain from remote user to local user and from local user to root. You still have an authentication trail so your logs tell you who logged in as root, and the authentication steps are the same as if sudo was involved.

To connect to a server as root, define an alias in ~/.ssh/config like this:

Host server-root
HostName server.example.com
User root
ProxyCommand "ssh server.example.com nc %h %p"

If you insist on using sudo, I believe you'll need separate commands, as sudo insists on reading from a terminal (even if it has a ticket for your account)¹, and none of the usual file copying methods (scp, sftp, rsync) support interacting with a remote terminal.

Sticking with ssh and sudo, your proposed commands could be simplified. On each side, if you have sudo set up not to ask a password again, you can run it once to get over with the password requirement and another time to copy the file. (You can't easily copy the file directly because the password prompt gets in the way.)

ssh -t source 'sudo true'
ssh -t target 'sudo true'
ssh -t source 'sudo cat squid.conf' |
ssh -t target 'sudo tee /etc/squid/squid.conf'

¹ unless you have NOPASSWD, but then you wouldn't be asking this.


You can set up sudo to not ask password next way:

On source:

user    ALL=NOPASSWD:/bin/cat

On target:

user    ALL=NOPASSWD:/usr/bin/tee

And do on yur machine:

ssh source 'sudo cat /test' | ssh target 'sudo tee /test'

But I recommend to use something like puppet. It's much better and easier solves your problem with config files distribution.

PS. By the way, if you'll set up sudo to ask password from user, the string with [sudo] password for user will apear in target file.


Instead of using ssh you can use scp to transfer the file between the servers.

Log into the target server :

Change to the target dir where you want to copy the file.

#scp -r -p -P 22 root@source-ipaddress:/source-path-file-to-copy .

r - recursive p - Preserves modification times, access times, and modes from the original file