Saturday, March 6, 2010

ssh tunneling (port forwarding)

The past two places I've worked at have had a single computer that would accept outside ssh communication. However, other computers in the network also had useful things on them but could only be reached from inside the network. How to connect to these other computers directly?

ssh port forwarding allows you to open up an ssh session between you and your gateway computer. Then, you can use that port to interact with the other computers in the network. Here is an example of how to do this:

Open a terminal and type in something like this:
ssh -L<unused_port#>:<final_destination>:22 <gateway_computer>
ssh # e.g.
# you might want to add the -N and -C flags:
ssh -N -C ...
# -N Do not execute a remote command (useful for forwarding ports)
# -C compress (for slow network connections only)

Then, open another terminal and you can interact with the internal server as you normally would, just by interacting with your localhost through the specified port:
# log in to the internal server
ssh -p 22000 localhost
# scp stuff from the internal server
scp -P 22000 localhost:~/somefile.txt ./ # copy files from the internal server to local
# mount a folder from the internal server locally using sshfs
sshfs -p 22000 localhost:/home/<user>/<internal_dir> /home/<user>/mnt -o follow_symlinks

Yes that is localhost. You are connecting to port 22000 on the localhost and that is being tunneled via the gateway computer to the internal server!

This works but isn't the absolute slickest setup. Anyone know the equivalent commands for .ssh/config files?

This site has some alternative methods for mounting across ssh.