Skip to content

Instantly share code, notes, and snippets.

@mdp
Last active December 14, 2015 14:29
Show Gist options
  • Star 3 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save mdp/5100620 to your computer and use it in GitHub Desktop.
Save mdp/5100620 to your computer and use it in GitHub Desktop.

Keep and SSH tunnel up and running on OSX

This is my trick to keep a tunnel running on an OSX host. It's setup so that a network state change will trigger the connection. In practice I've found that it's actually very reliable. Certainly beats starting them by hand.

Notes

  • This uses a 'tunnel' user on your remote host. Because we need to start the tunnel with a passwordless ssh key, it's safer to use a key that just used for this purpose.
  • The remote tunnel user should not have priviledges to login. You only need them to be able to forward ports, shell login is not needed to do this.

Installation and Use

On your Mac

  1. Create a new passwordless ssh key for use with the tunnel script.

     $ ssh-keygen -N '' -f ~/.ssh/tunnel
    
  2. Update and add the included plist file to ~/Library/LaunchAgents

On the server

  1. Create a new user called 'tunnel' that can't login

     $ adduser --create-home --shell /bin/false tunnel
    
  2. Add your tunnel.pub key to /home/tunnel/.ssh/authorized_keys

     $ sudo su
     $ cd /home/tunnel
     $ mkdir .ssh
     $ vim .ssh/authorized_keys # Copy your pub key in here
     $ chown tunnel:tunnel -R .ssh
    

Launch the script

Now you just need to make the script load at startup

$ launchctl load -w ~/Library/LaunchAgents/com.domain.tunnel.irc
<?xml version="1.0" encoding="UTF-8"?>
<!DOCTYPE plist PUBLIC "-//Apple//DTD PLIST 1.0//EN" "http://www.apple.com/DTDs/PropertyList-1.0.dtd">
<plist version="1.0">
<dict>
<key>Label</key>
<string>com.yourdomain.tunnel.irc</string>
<key>OnDemand</key>
<false/>
<key>ProgramArguments</key>
<array>
<string>/usr/bin/ssh</string>
<string>-N</string>
<string>-L</string>
<string>7777:localhost:7777</string>
<string>tunnel@yourdomain.com</string>
<string>-i</string>
<string>/Users/youruser/.ssh/tunnel</string>
</array>
<key>KeepAlive</key>
<dict>
<key>NetworkState</key>
<true/>
</dict>
<key>RunAtLoad</key>
<true/>
</dict>
</plist>
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment