SSH Tunneling with joy!

When dealing with several servers that don’t all see each other it is often a bit painful to jump from one SSH session to another, even more so if you have to type some password every time.
In case you are allowed to edit .ssh/authorized_keys (I don’t see a valid reason why you shouldn’t, but in the wonderful world of system administrators.. who knows?) your struggle is about to end. Provided, of course, that you use Linux šŸ™‚

Let’s say you want to reach hostB (unreachable from your own host) by tunneling over hostA (which you have direct access to).

  1. Edit your .ssh/config file to include a stanza for each host; it should look like this:
    Host hostA
    User myUserNameForHostA
    Port 22
    Host hostB
    User root
    ForwardAgent yes
    Port 22
    ProxyCommand ssh hostA nc %h %p

    This will also let you type ssh h<TAB> having the shell auto-complete magic fill the remaining “ost” for you (the remaining A or B is up to you). Right now you may already tunnel over A to reach B, but still you would have to type in passwords for both host A and hostB every time you ssh hostB.

  2. Generate your in case you don’t have one, and add it to the authorized_keys list of both hostA and hostB:
    ssh-keygen -t rsa
    cat ~/.ssh/ | ssh hostA 'cat >> .ssh/authorized_keys'
    cat ~/.ssh/ | ssh hostB 'cat >> .ssh/authorized_keys'

And you’re done! Now you can ssh hostB without having to type any password!

In case hostA and/or hostB don’t have a .ssh folder, you should of course create it by executing

ssh hostA mkdir -p .ssh
ssh hostB mkdir -p .ssh

Nice thing is, you may also add a hostC that is accessible from hostB only by adding an entry to .ssh/config as you’ve done for hostB, carefully switching hostA with hostB and hostB with hostC!

Leave a Reply

Fill in your details below or click an icon to log in: Logo

You are commenting using your account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s