Ubuntu – Problems starting autossh on boot [ubuntu]

MySQLssh-tunnelUbuntu

I'm trying to automatically start an SSH tunnel to my server on boot from a ubuntu box. I have an ubuntu box that's mounted on an 18-wheeler and is networked behind an air card. The box hosts a mysql database that i'm trying to have replicated when the aircard is connected. As I can never be sure of my IP and how many or which routers I'm behind I'm connected to my replication server with an SSH tunnel. I got that working using the following command:

ssh -R 3307:localhost:3307 myuser@myserver.com

Now I'd like that to start whenever the box is, and be alive all the time, so I installed auto-ssh and setup this little script:

ID=xkenneth
HOST=erdosmiller.com
AUTOSSH_POLL=15
AUTOSSH_PORT=20000
AUTOSSH_GATETIME=30
AUTOSSH_DEBUG=yes
AUTOSSH_PATH=/usr/bin/ssh
export AUTOSSH_POLL AUTOSSH_DEBUG AUTOSSH_PATH AUTOSSH_GATETIME AUTOSSH_PORT
autossh -2 -fN -M 20000 -R 3307:localhost:3306 ${ID}@${HOST}

I've tried putting this scrip in /etc/init.d/ and using a post-up command in /etc/network/interfaces as well as putting it in /etc/network/if-up.d/. In both situations the script starts on boot, but the tunnel doesn't appear to be correctly established. The script works when run manually.

Best Answer

If it is running properly but not connecting, I would suspect that it is getting ahead of itself and not waiting until the network is connected. Try delaying the tunnel by adding a sleep at the beginning of the script. sleep 60 would probably do the job, not sure how fast your connection establishes.

I suspect this since autossh gives up if the first attempt is not successful. From the README:

If the ssh session fails with an exit status of 1 on the very first 
try, autossh will assume that there is some problem with syntax or
the connection setup, and will exit rather than retrying;

Note that it also says you can set AUTOSSH_GATETIME to 0 to disable that behaviour.