AutoSSH – Start Reverse Tunnel Automatically on Network Up

bash-scriptsshssh-tunneling

I connect from my home PC thru an Internet server I own to a restricted client (that I also own) using a reverse ssh tunnel.

I have a script that sets up the restricted client to middleman leg of this ssh tunnel. It works fine if I execute the script manually. Here it is:

#!/bin/sh
autossh -M 12399 -oPubkeyAuthentication=yes -oPasswordAuthentication=no -oLogLevel=error  -oUserKnownHostsFile=/dev/null -oStrictHostKeyChecking=no -i ~/.ssh/named_id_rsa -R 12345:localhost:22 client@example.com -p 22

I want to have it run automatically whenever the network is up on this machine.

To accomplish this I thought about saving it as: /etc/network/if-up.d/reverse_ssh_tunnel.sh

I know I would have to remove "~/" and specify the full path to the private key as home/username/.ssh/named_id_rsa.

I suspect I'll have to use su -c my_script_name username, but I can't get that to work. Solving this part of my question is the most important. It needs to be fully automatic & unattended.

To connect from my home, I do two manual steps:

A. ssh home -> middleman
B. ssh middleman -> restricted client

Can A & B be done in a single step? (This would be nice, but not essential.)

In summary:

  1. Ideally, I'd like to do A & B in one step, manually.
  2. And I need the restricted client -> middleman autossh connection to be fully automatic.

Best Answer

OK, finally got it working. The details are in this question: Remote desktop over SSH reverse tunnel to replace TeamViewer

In summary:

On desktop (that will receive support):

su -l -c "autossh -M 5234 -N -f -R 1234:localhost:22 user@middleman.com &" username

On laptop (giving support):

me@laptop:~/.ssh$ nano config

Host family_desktops
  ProxyCommand ssh middleman_fqdn nc localhost %p
  User admin
  PasswordAuthentication no
  IdentityFile ~/.ssh/my_id_rsa

Then I just connect to "remote desktop" in one step:

me@laptop:~$ ssh family_desktops -p 1234

Related Question