SSH ProxyCommand
July 3rd, 2008Here’s an exceedingly useful feature of SSH which I only discovered recently.
Imagine that you have a single ‘gateway’ machine on your network which you can connect to from outside using SSH; I do this all the time. You can then use that machine to connect to other machines inside your network in a variety of ways: using the port-forwarding abilities of SSH (the -L and -R options), for example, or simply by running another SSH command from the gateway machine once you’ve connected to it.
But there’s a much tidier way to do it, using the ProxyCommand option.
To connect to internalmachine.mynet.com, just add something like the following to your ~/.ssh/config:
Host internalmachine.mynet.com
ProxyCommand ssh gateway.mynet.com exec nc %h %p
then you can ssh directly to internalmachine.mynet.com from outside. SSH will connect to the gateway machine and run ‘nc’ to forward the SSH session to the internal machine.
And, of course, you can use it for things layered over SSH, like checkouts from Git or Subversion repositories. Very tidy! I also sometimes add -C to the ssh command so that any access done this way is automatically compressed, even in situations where it was hard to specify that explicitly.
If you’re unlucky enough to find yourself stuck behind a web proxy with no other outgoing access, one very nice-looking use of ProxyCommand is the Corkscrew utility by Pat Padgett.
Hope this is helpful to someone!
July 31st, 2009 at 1:04 am
The *was* useful to someone
. I knew about the ProxyCommand option, and that it was possible to use it to tunnel like this, but didn’t know how to do it; I didn’t know the bit about Netcat!
Thanks!
May 13th, 2010 at 2:21 am
So just to clarify, the nc command expands to “nc internalmachine.mynet.com 22″, granting your local ssh access over stdin and stdout?
May 13th, 2010 at 9:13 am
Yes, that’s right – the nc runs on the gateway machine you’re ssh-ing to, and effectively forwards the connection to the ssh port on the internal machine, so you appear to be connecting to that internal machine directly, especially if you have the appropriate keys installed on those machines so you don’t need passwords.