MacOS – How to keep an ssh tunnel alive using launchd

launchdmacossshtunnel

I would like to keep an ssh tunnel alive. Below is my launch agent plist file but it only keeps the tunnel up for a day or two at the most. I'm using OS X 10.10.3.

<?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.my.ssh_tunnel</string>
                <key>ProgramArguments</key>
                <array>
                        <string>/usr/bin/ssh</string>
                        <string>-R 0.0.0.0:22221:localhost:22</string>
                        <string>-NTC</string>
                        <string>-f</string>
                        <string>-o ExitOnForwardFailure=yes</string>
                        <string>-o ServerAliveInterval=60</string>
                        <string>user@user.server.com</string>
                </array>
                <key>RunAtLoad</key>
                <true/>
                <key>KeepAlive</key>
                <true/>
        </dict>
</plist>

Best Answer

I think you need to add "ServerAliveCountMax". Since you don't have it set it defaults to 3. Try setting it to something higher than 3 and see if it relives some of your issues. In your case it would disconnect if the server is not responsive for 180 seconds.

From the ssh man page:

 ServerAliveCountMax:

     Sets the number of server alive messages (see below) which may be
     sent without ssh(1) receiving any messages back from the server.
     If this threshold is reached while server alive messages are
     being sent, ssh will disconnect from the server, terminating the
     session.  It is important to note that the use of server alive
     messages is very different from TCPKeepAlive (below).  The server
     alive messages are sent through the encrypted channel and there‐
     fore will not be spoofable.  The TCP keepalive option enabled by
     TCPKeepAlive is spoofable.  The server alive mechanism is valu‐
     able when the client or server depend on knowing when a connec‐
     tion has become inactive.

     The default value is 3.  If, for example, ServerAliveInterval
     (see below) is set to 15 and ServerAliveCountMax is left at the
     default, if the server becomes unresponsive, ssh will disconnect
     after approximately 45 seconds.  This option applies to protocol
     version 2 only.