1

I'd like to copy a public ssh key from the ~/.ssh/id_rsa.pub file on my local machine to the ~/.ssh/authorized_keys file on a remote host that is two ssh hops away. In other words, localhost only has ssh access to host1, but host1 has ssh access to host2. I want to copy my public ssh key from localhost to host2.

To copy a an ssh key to a remote host one hop away, the ssh documentation gives the command:

ssh-copy-id -i ~/.ssh/mykey user@host

Is there a way to copy the key to a machine that is two hops away in a single command?

  • You can try the ProxyCommand option but I've always had my key on the 2nd machine so not too sure if this will work. – Praveen Premaratne Feb 11 at 23:00
  • How do you ssh into host2? Personally I use a ~/.ssh/config containing a ProxyJump directive, but this doesn't work for older ssh clients. The best answer may depend on your ssh version. – rexypoo Feb 11 at 23:07
1

I don't think it is possible with ssh-copy-id to do a double hop. You can use scp to jump the file through one server to the third. look at man scp. but then you would still need to do some work to get the text into authorized_keys and set perms

However!

You can use ssh to jump through a server to another server then issue commands there.

Something like this would copy keys from here to there. you will have to copy the .ssh/id_rsa.pub key you wish to send and paste in place of mysupersecretkeyfromhell below and obviously change the names and ip addresses.
Something similar to this will jump through the first server, ssh into the 2nd and run your commands.

ssh -J mark@192.168.1.100 mark@192.168.1.110 echo mySupersecretKeyfromehell >> .ssh/authorized_keys && chmod 700 .ssh && chmod 600 .ssh/authorized_keys

This assumes your running a recent version of ssh.

You could also shorten the last command by putting your key in a variable.
Note back ticks below not single quotes!

MYKEYVAR="echo `cat .ssh/id_rsa.pub`" 
ssh -J mark@192.168.1.100 mark@192.168.1.110 echo $MYKEYVAR >> .ssh/authorized_keys && chmod 700 .ssh && chmod 600 .ssh/authorized_keys
| improve this answer | |
1

You can pass any ssh option to ssh-copy-id with the -o option. By using the ProxyJump option you can use ssh-copy-id to copy your key to a host via jump host.

Here's an example where I copy my ssh key to leia.spack.org via the jump host jump.spack.org:

$ ssh-copy-id -o ProxyJump=jump.spack.org leia.spack.org
adam@leia.spack.org's password:

Number of key(s) added:        1

And then test it with:

$ ssh -J kauri.local leia.groundtruth.co.nz
Welcome to Ubuntu 20.04 LTS (GNU/Linux 5.4.0-42-generic x86_64)
| improve this answer | |

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.