2

I am not very used to sys admin and recently created an SSH tunnel between two servers (on Ubuntu 12.4) with the following command:

ssh -fNg -L 3307:127.0.0.1:3306 tunneluser@xx.xx.xx.xx

It worked, I also added this command to /etc/rc.local, and it successfully launch the SSH tunnel at startup. However, I tried to add my tunnel in a file in /etc/init/my_tunnel.conf, and it worked but launched nearly 12 tunnels at every startup! I used the following code:

start on (local-filesystems and net-device-up IFACE=eth0)
stop on runlevel[016]
respawn
exec ssh -fNg -L 3307:127.0.0.1:3306 tunneluser@xx.xx.xx.xx
exit 0

I spent hours on this and do not understand at all why and how this script is executed so many times. I also tried start on[2345], completely read upstart's manual but still the same. I am sure that I am missing something here.

If someone can help me. Thanks.

  • maybe you are missing the respawn description "http://upstart.ubuntu.com/wiki/Stanzas#respawn" Description: set the service and respawn flags for the job. The respawn flag means that the process will be restarted if ended unexpectedly. – c4f4t0r Mar 09 '14 at 22:16

2 Answers2

1

As c4f4t0r commented, respawn will run the command again when the script exits. By using -f it runs in the background, effectively exiting and causing upstart to respawn it. If you remove -f then it will remain in a running state that upstart can observe when it unexpectedly exits.

start on (local-filesystems and net-device-up IFACE=eth0)
stop on runlevel[016]
respawn
exec ssh -Ng -L 3307:127.0.0.1:3306 tunneluser@xx.xx.xx.xx
exit 0
mbrandeis
  • 306
  • 2
  • 2
0

I did exactly the same, this is a great way to setup remote access to a Linux machine : even if the local configuration, or the IP of the connection changes you still keep your remote access.

First of all I wrote a script to set-up the tunnel ONLY if it is not present : (I removed all comments here)

$ cat /root/scripts/tunnels.sh
if [ "$1" == "WAIT" ]; then sleep 20; fi
TUNNELOK=`ps aux | grep ssh | grep 3307 | sed 's/.*3307.*/TUNNELALLOK/' | sort -u`
if [ "$TUNNELOK" != "TUNNELALLOK" ]; then
  ssh -R 8877:localhost:22 -Ng tunnel_eaw@cirrus.hsolutions.ch &
fi

Then, I added it to crontab instead of initab/upstart :

# crontab -l |grep tunnel
@reboot /root/scripts/tunnel.sh WAIT
*/5 * * * * /root/scripts/tunnel.sh

And there it goes... ! In the past I used to use initab/upstart, but the solution above is finally working perfectly. In the worst case you have to wait 5 minutes for the connection to show up again, but you can change that in the crontab. Of course you will have to check that the "ps aux" is suitable to your system.

db_ch
  • 648
  • 5
  • 14
  • 21