Ssh into NATted VM via AutoSSH


Suppose you have a virtual machine running on a natted network connection. It can get out just fine to the Internet.
Now, with the network address translation (NAT), you can’t send traffic in to that network. So you can’t just ssh and get in. You are going to need something a little fancier to accomplish that. This document explains how to do that.

Sample environment

For this document, these example values will be used. The vm is and the system on the main network is The desktop will have port 5000 be forwarded to the vm’s port 22, which is the standard ssh port.

Set up autossh

You need ssh connectivity between the vm and the physical host. Make sure you have an automatic log in from the vm to the physical host. A good way to do that is by having an ssh key. If you need to generate one on the vm and copy it to the physical machine, use these commands.
# on vm
ssh-keygen # follow the prompts

The next step is to copy it to the physical machine.
# still on vm

Check that you can log in automatically with
Once that is done, install autossh and make a systemd service file and enable and start it.
yum -y install autossh
touch "${tf}"; chmod 0644 "${tf}"
cat <<EOF > "${tf}"
Description=AutoSSH tunnel service for ssh
ExecStart=/usr/bin/autossh -M 0 -o "ServerAliveInterval 30" -o "ServerAliveCountMax 3" -N -R 5000:localhost:22 -p 22
systemctl daemon-reload
systemctl enable autossh-ssh.service
systemctl start autossh-ssh.service

Using the reverse tunnel

To connect to, you just need to do this:
ssh centosusername@localhost -p 5000

Bonus: nickname the connection and copy ssh key

What I did was set up my ~/.ssh/config file with the following snippet, so I can just use the nickname “centosvm.”

# in ~/.ssh/config, mode 0600
Host centosvm
 User centosuser
 Hostname localhost
 Port 5000

I then copied my ssh id to that, so I could connect without a password.
ssh-copy-id centosvm



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