SSH – How to Use ssh-copy-id with Multiple-Hop SSH Tunnel

sshssh-tunneling

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?

Best Answer

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 jump.spack.org leia.spack.org
Welcome to Ubuntu 20.04 LTS (GNU/Linux 5.4.0-42-generic x86_64)
Related Question