SSH config for multiple hops in Linux

2014-01-25
#linux #howto #ssh #config

Often some hosts in corporate network are available only from several gateway machines. The scheme looks like that: you connect to gateway ssh -A gateway.public.net and then to desired host from gateway machines ssh -A host.private.net. But the problem arises when you want to copy or download something from host.private.net. You have to do it in two hops, because host.private.net is not available from your machine directly. The solution is ssh forwarding.

Just add the following (edit according your network settings) lines to ~/.ssh/config:

Host gateway
    User bikulov
    ForwardAgent yes
    HostName gateway.public.net
    IdentityFile ~/.ssh/bikulov_private_key

Host host
    User bikulov
    ForwardAgent yes
    ProxyCommand ssh -4 gateway nc -q 0 host.private.net 22

ForwardAgent options forwards information about your ssh key bikulov_private_key to gateway.public.net. Now you can just type ssh host in terminal. You will be connected to host.private.net through gateway.public.net automatically. And scp now works directly too.