How to reliably keep an SSH tunnel open?












214















I use an SSH tunnel from work to go around various idotic firewalls (it's ok with my boss :)). The problem is, after a while the ssh connection usually hangs, and the tunnel is broken.



If I could at least monitor the tunnel automatically, I could restart the tunnel when it hangs, but I haven't even figured a way of doing that.



Bonus points for the one who can tell me how to prevent my ssh connection from hanging, of course!










share|improve this question























  • It is your tunnel dead because inactivity? I had this problem when tunneling ports from my phone so i finally ended spawning dummy commands on the connection to make it "alive" using the watch command like: watch -n1 60 echo "wiiiii". Tunnel will not die unless network is broken or you don't use it.

    – erm3nda
    Feb 10 '17 at 2:07













  • Related: unix.stackexchange.com/q/200239

    – sampablokuper
    Dec 29 '17 at 16:28
















214















I use an SSH tunnel from work to go around various idotic firewalls (it's ok with my boss :)). The problem is, after a while the ssh connection usually hangs, and the tunnel is broken.



If I could at least monitor the tunnel automatically, I could restart the tunnel when it hangs, but I haven't even figured a way of doing that.



Bonus points for the one who can tell me how to prevent my ssh connection from hanging, of course!










share|improve this question























  • It is your tunnel dead because inactivity? I had this problem when tunneling ports from my phone so i finally ended spawning dummy commands on the connection to make it "alive" using the watch command like: watch -n1 60 echo "wiiiii". Tunnel will not die unless network is broken or you don't use it.

    – erm3nda
    Feb 10 '17 at 2:07













  • Related: unix.stackexchange.com/q/200239

    – sampablokuper
    Dec 29 '17 at 16:28














214












214








214


95






I use an SSH tunnel from work to go around various idotic firewalls (it's ok with my boss :)). The problem is, after a while the ssh connection usually hangs, and the tunnel is broken.



If I could at least monitor the tunnel automatically, I could restart the tunnel when it hangs, but I haven't even figured a way of doing that.



Bonus points for the one who can tell me how to prevent my ssh connection from hanging, of course!










share|improve this question














I use an SSH tunnel from work to go around various idotic firewalls (it's ok with my boss :)). The problem is, after a while the ssh connection usually hangs, and the tunnel is broken.



If I could at least monitor the tunnel automatically, I could restart the tunnel when it hangs, but I haven't even figured a way of doing that.



Bonus points for the one who can tell me how to prevent my ssh connection from hanging, of course!







linux networking security ssh shell






share|improve this question













share|improve this question











share|improve this question




share|improve this question










asked Sep 8 '09 at 13:04









PeltierPeltier

2,21953153




2,21953153













  • It is your tunnel dead because inactivity? I had this problem when tunneling ports from my phone so i finally ended spawning dummy commands on the connection to make it "alive" using the watch command like: watch -n1 60 echo "wiiiii". Tunnel will not die unless network is broken or you don't use it.

    – erm3nda
    Feb 10 '17 at 2:07













  • Related: unix.stackexchange.com/q/200239

    – sampablokuper
    Dec 29 '17 at 16:28



















  • It is your tunnel dead because inactivity? I had this problem when tunneling ports from my phone so i finally ended spawning dummy commands on the connection to make it "alive" using the watch command like: watch -n1 60 echo "wiiiii". Tunnel will not die unless network is broken or you don't use it.

    – erm3nda
    Feb 10 '17 at 2:07













  • Related: unix.stackexchange.com/q/200239

    – sampablokuper
    Dec 29 '17 at 16:28

















It is your tunnel dead because inactivity? I had this problem when tunneling ports from my phone so i finally ended spawning dummy commands on the connection to make it "alive" using the watch command like: watch -n1 60 echo "wiiiii". Tunnel will not die unless network is broken or you don't use it.

– erm3nda
Feb 10 '17 at 2:07







It is your tunnel dead because inactivity? I had this problem when tunneling ports from my phone so i finally ended spawning dummy commands on the connection to make it "alive" using the watch command like: watch -n1 60 echo "wiiiii". Tunnel will not die unless network is broken or you don't use it.

– erm3nda
Feb 10 '17 at 2:07















Related: unix.stackexchange.com/q/200239

– sampablokuper
Dec 29 '17 at 16:28





Related: unix.stackexchange.com/q/200239

– sampablokuper
Dec 29 '17 at 16:28










15 Answers
15






active

oldest

votes


















257














Sounds like you need autossh. This will monitor an ssh tunnel and restart it as needed. We've used it for a couple of years and it seems to work well.



autossh -M 20000 -f -N your_public_server -R 1234:localhost:22 -C


More details on the -M parameter here






share|improve this answer





















  • 2





    +1 for autossh, it does what it says on the tin. I believe part of its functionality also is to send keep-alive style packets to prevent any kind of timeout.

    – akent
    Sep 8 '09 at 13:55






  • 27





    Could you put the example tunnel using autossh in the answer?

    – Ehtesh Choudhury
    Dec 20 '12 at 21:45








  • 3





    autossh -f -nNT -i ~/keypair.pem -R 2000:localhost:22 username@myoutsidebox.com You might notice that I set this up using -nNT which doesn't create a remote terminal so that I can put autossh into the background, and the -i option for SSH to use a .pem file. If you're going to be keeping a connection open all the time, I definitely recommend going through the extra setup.

    – juckele
    Aug 31 '15 at 20:01








  • 2





    For what it's worth, it looks like it's typically better to omit the -M parameter: bugs.debian.org/cgi-bin/bugreport.cgi?bug=351162

    – rinogo
    Sep 15 '15 at 22:40








  • 1





    How does that work if I have a passphrase ? would it store that passphrase in a keychain ( for example on a mac ) ?

    – Yannick Y
    Nov 6 '17 at 16:08



















37














All stateful firewalls forget about a connection after not seeing a packet for that connection for some time (to prevent the state tables from becoming full of connections where both ends died without closing the connection). Most TCP implementations will send a keepalive packet after a long time without hearing from the other side (2 hours is a common value). If, however, there is a stateful firewall which forgets about the connection before the keepalive packets can be sent, a long-lived but idle connection will die.



If that is the case, the solution is to prevent the connection from becoming idle. OpenSSH has an option called ServerAliveInterval which can be used to prevent the connection from being idle for too long (as a bonus, it will detect when the peer died sooner even if the connection is idle).






share|improve this answer


























  • The interval specified is in seconds, so you can provide some fine tuning. If your stateful firewall has a 5 minute idle timeout, then 60 or 120 seconds is enough to keep the connection open. It's one of the ways I keep my ssh sessions through my home router open.

    – Darren Hall
    Dec 2 '09 at 21:16











  • Thanks, this helped. But note (from a lower-ranked answer here, superuser.com/a/146641/115515) that if you specify ServerAliveInterval and not ServerAliveCountMax, you may find ssh intentionally disconnecting sooner than you wanted.

    – metamatt
    Jan 26 '12 at 21:54






  • 4





    @metamatt, that lower-ranked answer you reference is lower-ranked for good reason: IT IS WRONG.

    – Lambart
    Feb 20 '14 at 0:14



















23














On your own mac or linux machine configure your ssh keep the server ssh alive every 3 minutes. Open a terminal and go your your invisible .ssh in your home:



cd ~/.ssh/ 


then create a 1 line config file with:



echo "ServerAliveInterval 180" >> config


you should also add:



ServerAliveCountMax xxxx (high number)


the default is 3 so ServerAliveInterval 180 will stop sending after 9 minutes (3 of the 3-minute interval specified by ServerAliveInterval).






share|improve this answer





















  • 2





    Note that your command is not recommended if you already have a config file. Using >> for redirection would be a lot better!

    – Peltier
    Mar 18 '11 at 9:34











  • why does ServerAliveInterval 180 give us 6 minutes? intuition makes me try this : 180/60 == 3. So, does ServerAliveInterval work in multiples of 30 secs?

    – nemesisfixx
    Nov 30 '11 at 14:37











  • @mcnemesis: ServerAliveInterval 180 means 3 minutes. ServerAliveCountMax default of 3 means 3 of those intervals, so 9 minutes.

    – metamatt
    Jan 26 '12 at 21:50






  • 1





    I'm voting this answer up because thanks for mentioning ServerAliveCountMax, and what happens if you specify ServerAliveInterval without ServerAliveCountMax. But like the preceding comments, I notice the calculation on "will stop sending after" is wrong, and I think this answer would serve better if it just gave the information on these options, not telling us how to apply them with cd and echo commands.

    – metamatt
    Jan 26 '12 at 21:51






  • 16





    Downvoting because it makes no sense to set ServerAliveCountMax to a "high number". ServerAliveCountMax specifies how many times it will try to send the "keepalive" message before giving up. The default is 3, so with ServerAliveInterval 180, it will stop sending ONLY if the server has NOT RESPONDED after 9 minutes, in which case your connection is probably well and truly dead.

    – Lambart
    Feb 20 '14 at 0:13



















20














I've used the following Bash script to keep spawning new ssh tunnels when the previous one dies. Using a script is handy when you don't want or can't install additional packages or use compiler.



while true
do
ssh <ssh_options> [user@]hostname
sleep 15
done


Note that this requires a keyfile to establish the connection automatically but that is the case with autossh, too.






share|improve this answer



















  • 1





    You should add any reasons that you'd use this script over autossh, or is it just that it's easier this way?

    – kyrias
    Oct 20 '12 at 17:25






  • 4





    This wouldn't help if ssh itself freezes, would it?

    – nafg
    Nov 25 '13 at 23:59






  • 1





    It helps if you can't install things in the server. autossh doesn't come preinstalled and bureucracy it's sometimes very obtuse.

    – quarkex
    Mar 13 '17 at 15:13











  • Yes, preferable not to have to install things. I've been doing it this way for a year as my only way to keep a remote machine accessible (even set crontab to run it upon reboot). It's never failed, and more importantly, I know why it will never fail.

    – sudo
    Apr 2 '18 at 6:42





















13














Systemd is ideally suited for this.



Create a service file /etc/systemd/system/sshtunnel.service containing:



[Unit]
Description=SSH Tunnel
After=network.target

[Service]
Restart=always
RestartSec=20
User=sshtunnel
ExecStart=/bin/ssh -NT -o ServerAliveInterval=60 -L 5900:localhost:5900 user@otherserver

[Install]
WantedBy=multi-user.target


(Modify the ssh command to suit)




  • this will run as user sshtunnel so make sure that user exists first

  • issue systemctl enable sshtunnel to set it to start at boot time

  • issue systemctl start sshtunnel to start immediately




Update Jan 2018: some distros (e.g. Fedora 27) may use SELinux policy to prevent the use of SSH from systemd init, in which case a custom policy will need to be created to provide the necessary exemptions.






share|improve this answer





















  • 2





    This looks very similar to my gist: gist.github.com/guettli/… Feedback is welcome!

    – guettli
    Dec 22 '17 at 11:47











  • Excellent for a systemd system. If one uses Restart=on-failure then manually killing the SSH client will not result in a restart-by-systemd as the SSH client with exit with success.

    – David Tonhofer
    Mar 22 '18 at 19:36











  • If you want to start ssh from a (bash) script given as argument to ExecStart for example to build the ssh argument list, do basic checks etc then call it from the script like so exec /bin/ssh -N .... Here is my command: exec /bin/ssh -N -oExitOnForwardFailure=Yes -oTCPKeepAlive=no -oServerAliveInterval=5 -oServerAliveCountMax=6 -i "${LOCAL_PRIVATE_KEY}" -L "${TUNNEL_INLET}:${TUNNEL_OUTLET}" "${REMOTE_USER}@${REMOTE_MACHINE}" where TUNNEL_INLET="127.0.0.1:3307" and TUNNEL_OUTLET="127.0.0.1:3306"

    – David Tonhofer
    Mar 22 '18 at 19:42





















9














It sure looks to me that you're all misinterpreting ServerAliveCountMax. As I understand the docs, it is the number of server alive messages which can go unanswered without the connection being terminated. So in cases like we're discussing here, setting it to a high value will just ensure that a hung connection will not be detected and terminated!



Simply setting ServerAliveInterval should be sufficient to solve the problem with a firewall forgetting about the connection, and leaving ServerAliveCountMax low will allow the originating end to notice the failure and terminate if the connection fails anyway.



What you want is, 1) for the connection to stay open permanently under normal circumstances, 2) for connection failure to be detected and the originating side to exit on failure, and 3) for the ssh command to be re-issued every time it exits (how you do that is very platform dependent, the "while true" script suggested by Jawa is one way, on OS X I actually set up a launchd item).






share|improve this answer































    9














    Always use ServerAliveInterval SSH option in case the tunnel issues are generated by expired NAT sessions.



    Always use a respawning method in case the connectivity goes down entirely, you have at least three options here:




    • autossh program

    • bash script (while true do ssh ...; sleep 5; done) do not remove the sleep command, ssh may fail quickly and you'll respawn too many processes


    • /etc/inittab, to have access to a box shipped and installed in another country, behind NAT, without port forwarding to the box, you can configure it to create an ssh tunnel back to you:



      tun1:2345:respawn:/usr/bin/ssh -i /path/to/rsaKey -f -N -o "ServerAliveInterval 180" -R 55002:localhost:22 user@publicip 'sleep 365d'



    • upstart script on Ubuntu, where /etc/inittab is not available:



      start on net-device-up IFACE=eth0
      stop on runlevel [01S6]
      respawn
      respawn limit 180 900
      exec ssh -i /path/to/rsaKey -N -o "ServerAliveInterval 180" -R 55002:localhost:22 user@publicip
      post-stop script
      sleep 5
      end script



    or always use both methods.






    share|improve this answer





















    • 1





      +1 for inline option in case you don't want it for all of your SSH connections

      – user1146334
      Jul 7 '14 at 14:29











    • You write "in case connectivity goes down entirely". Now I don't understand, what problems does autossh fix itself, and what does it not? I thought, of course, it would take care of any broken connection, like unplugging the cable for a few hours, but perhaps not?

      – Mads Skjern
      May 12 '16 at 19:02





















    6














    I solved this problem with this:



    Edit



    ~/.ssh/config


    And add



    ServerAliveInterval 15
    ServerAliveCountMax 4


    According to man page for ssh_config:



    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.

    ServerAliveInterval
    Sets a timeout interval in seconds after which if no data has
    been received from the server, ssh(1) will send a message through
    the encrypted channel to request a response from the server. The
    default is 0, indicating that these messages will not be sent to
    the server. This option applies to protocol version 2 only.





    share|improve this answer


























    • Every 15 seconds seems pretty often to ping the server.

      – Lambart
      Feb 20 '14 at 0:08











    • @Lambart but if the connection is really flaky and drops connections often, it at least detects a dead connection and gives the opportunity to retry earlier.

      – binki
      Dec 13 '14 at 2:00



















    3














    ExitOnForwardFailure yes is a good adjunct to the other suggestions. If it connects but can't establish the port forwarding it's just as useless to you as if it hadn't connected at all.






    share|improve this answer


























    • This is a very good idea. Even autossh is useless if the previous connection is perceived as timed out earlier in the remote side than in the local host, since in this case the local host will try to connect again, but the forwarding cannot be established because the port is still open.

      – Raúl Salinas-Monteagudo
      May 24 '17 at 7:42



















    1














    I've had a need to maintain an SSH-tunnel long-term. My solution was running from a Linux server, and it's just a small C program that respawns ssh using key-based authentication.



    I'm not sure about the hanging, but I've had tunnels die due to timeouts.



    I would love to provide the code for the respawner, but I can't seem to find it right now.






    share|improve this answer































      1














      while there are tools like autossh that helps to restart ssh session... what i find to be really useful is to run the 'screen' command. It allows you to RESUME your ssh sessions even after you disconnect. Especially useful if your connection is not as reliable as it should be.




      • http://www.howtogeek.com/howto/ubuntu/keep-your-ssh-session-running-when-you-disconnect/


      ...don't forget to mark this is the 'correct' answer if it helps you k! ;-)






      share|improve this answer



















      • 5





        ... but the question was about how to keep SSH tunnels open, not just a terminal session. Screen IS great though!

        – akent
        Sep 8 '09 at 14:15











      • I already use screen, but it doesn't solve my problem :-/ Thanks for your answer, though.

        – Peltier
        Sep 8 '09 at 14:15



















      1














      A bit of a hack, but I like to use screen to keep this. I currently have a remote forward that has been running for weeks.



      Example, starting locally:



      screen
      ssh -R ......


      When the remote forward is applied, and you have a shell on the remote computer:



      screen
      Ctrl + a + d


      You now have an uninterrupted remote forward. The trick is to run screen on both ends






      share|improve this answer































        1














        Recently had this issue myself, because these solutions require you to re-enter the password every time if you use a password login I used sshpass in a loop along with a text prompt to avoid having the password in the batch file.



        Thought I'd share my solution on this thead in case anyone else has the same issue:



        #!/bin/bash
        read -s -p "Password: " pass
        while true
        do
        sshpass -p "$pass" ssh user@address -p port
        sleep 1
        done





        share|improve this answer

































          0














          I have had similar problems with my previous ISP.
          For me it was the same with any tcp connection, visiting websites or sending mail.



          The solution was to configure a VPN connection over UDP(I was using OpenVPN). This connection was more tolerant to whatever caused the disconnections. Then you can run any service through this connection.



          There can still be issues with the connection but since the tunnel will be more tolerant any ssh session will feel a short holdup rather than being disconnected.



          To do this you will need a VPN service online which you can setup on your own server.






          share|improve this answer































            0














            As autossh does not meet our needs (it exists with error if it can't connect to the server at the very first attempt), we've written a pure bash application: https://github.com/aktos-io/link-with-server



            It creates a reverse tunnel for the NODE's sshd port (22) on the server by default. If you need to perform any other actions (like forwarding additional ports, sending mails on connection, etc...) you can place your scripts on-connect and on-disconnect folders.






            share|improve this answer























              Your Answer








              StackExchange.ready(function() {
              var channelOptions = {
              tags: "".split(" "),
              id: "3"
              };
              initTagRenderer("".split(" "), "".split(" "), channelOptions);

              StackExchange.using("externalEditor", function() {
              // Have to fire editor after snippets, if snippets enabled
              if (StackExchange.settings.snippets.snippetsEnabled) {
              StackExchange.using("snippets", function() {
              createEditor();
              });
              }
              else {
              createEditor();
              }
              });

              function createEditor() {
              StackExchange.prepareEditor({
              heartbeatType: 'answer',
              autoActivateHeartbeat: false,
              convertImagesToLinks: true,
              noModals: true,
              showLowRepImageUploadWarning: true,
              reputationToPostImages: 10,
              bindNavPrevention: true,
              postfix: "",
              imageUploader: {
              brandingHtml: "Powered by u003ca class="icon-imgur-white" href="https://imgur.com/"u003eu003c/au003e",
              contentPolicyHtml: "User contributions licensed under u003ca href="https://creativecommons.org/licenses/by-sa/3.0/"u003ecc by-sa 3.0 with attribution requiredu003c/au003e u003ca href="https://stackoverflow.com/legal/content-policy"u003e(content policy)u003c/au003e",
              allowUrls: true
              },
              onDemand: true,
              discardSelector: ".discard-answer"
              ,immediatelyShowMarkdownHelp:true
              });


              }
              });














              draft saved

              draft discarded


















              StackExchange.ready(
              function () {
              StackExchange.openid.initPostLogin('.new-post-login', 'https%3a%2f%2fsuperuser.com%2fquestions%2f37738%2fhow-to-reliably-keep-an-ssh-tunnel-open%23new-answer', 'question_page');
              }
              );

              Post as a guest















              Required, but never shown

























              15 Answers
              15






              active

              oldest

              votes








              15 Answers
              15






              active

              oldest

              votes









              active

              oldest

              votes






              active

              oldest

              votes









              257














              Sounds like you need autossh. This will monitor an ssh tunnel and restart it as needed. We've used it for a couple of years and it seems to work well.



              autossh -M 20000 -f -N your_public_server -R 1234:localhost:22 -C


              More details on the -M parameter here






              share|improve this answer





















              • 2





                +1 for autossh, it does what it says on the tin. I believe part of its functionality also is to send keep-alive style packets to prevent any kind of timeout.

                – akent
                Sep 8 '09 at 13:55






              • 27





                Could you put the example tunnel using autossh in the answer?

                – Ehtesh Choudhury
                Dec 20 '12 at 21:45








              • 3





                autossh -f -nNT -i ~/keypair.pem -R 2000:localhost:22 username@myoutsidebox.com You might notice that I set this up using -nNT which doesn't create a remote terminal so that I can put autossh into the background, and the -i option for SSH to use a .pem file. If you're going to be keeping a connection open all the time, I definitely recommend going through the extra setup.

                – juckele
                Aug 31 '15 at 20:01








              • 2





                For what it's worth, it looks like it's typically better to omit the -M parameter: bugs.debian.org/cgi-bin/bugreport.cgi?bug=351162

                – rinogo
                Sep 15 '15 at 22:40








              • 1





                How does that work if I have a passphrase ? would it store that passphrase in a keychain ( for example on a mac ) ?

                – Yannick Y
                Nov 6 '17 at 16:08
















              257














              Sounds like you need autossh. This will monitor an ssh tunnel and restart it as needed. We've used it for a couple of years and it seems to work well.



              autossh -M 20000 -f -N your_public_server -R 1234:localhost:22 -C


              More details on the -M parameter here






              share|improve this answer





















              • 2





                +1 for autossh, it does what it says on the tin. I believe part of its functionality also is to send keep-alive style packets to prevent any kind of timeout.

                – akent
                Sep 8 '09 at 13:55






              • 27





                Could you put the example tunnel using autossh in the answer?

                – Ehtesh Choudhury
                Dec 20 '12 at 21:45








              • 3





                autossh -f -nNT -i ~/keypair.pem -R 2000:localhost:22 username@myoutsidebox.com You might notice that I set this up using -nNT which doesn't create a remote terminal so that I can put autossh into the background, and the -i option for SSH to use a .pem file. If you're going to be keeping a connection open all the time, I definitely recommend going through the extra setup.

                – juckele
                Aug 31 '15 at 20:01








              • 2





                For what it's worth, it looks like it's typically better to omit the -M parameter: bugs.debian.org/cgi-bin/bugreport.cgi?bug=351162

                – rinogo
                Sep 15 '15 at 22:40








              • 1





                How does that work if I have a passphrase ? would it store that passphrase in a keychain ( for example on a mac ) ?

                – Yannick Y
                Nov 6 '17 at 16:08














              257












              257








              257







              Sounds like you need autossh. This will monitor an ssh tunnel and restart it as needed. We've used it for a couple of years and it seems to work well.



              autossh -M 20000 -f -N your_public_server -R 1234:localhost:22 -C


              More details on the -M parameter here






              share|improve this answer















              Sounds like you need autossh. This will monitor an ssh tunnel and restart it as needed. We've used it for a couple of years and it seems to work well.



              autossh -M 20000 -f -N your_public_server -R 1234:localhost:22 -C


              More details on the -M parameter here







              share|improve this answer














              share|improve this answer



              share|improve this answer








              edited May 18 '18 at 19:39









              Run5k

              11.1k73152




              11.1k73152










              answered Sep 8 '09 at 13:43









              KeithBKeithB

              7,79611813




              7,79611813








              • 2





                +1 for autossh, it does what it says on the tin. I believe part of its functionality also is to send keep-alive style packets to prevent any kind of timeout.

                – akent
                Sep 8 '09 at 13:55






              • 27





                Could you put the example tunnel using autossh in the answer?

                – Ehtesh Choudhury
                Dec 20 '12 at 21:45








              • 3





                autossh -f -nNT -i ~/keypair.pem -R 2000:localhost:22 username@myoutsidebox.com You might notice that I set this up using -nNT which doesn't create a remote terminal so that I can put autossh into the background, and the -i option for SSH to use a .pem file. If you're going to be keeping a connection open all the time, I definitely recommend going through the extra setup.

                – juckele
                Aug 31 '15 at 20:01








              • 2





                For what it's worth, it looks like it's typically better to omit the -M parameter: bugs.debian.org/cgi-bin/bugreport.cgi?bug=351162

                – rinogo
                Sep 15 '15 at 22:40








              • 1





                How does that work if I have a passphrase ? would it store that passphrase in a keychain ( for example on a mac ) ?

                – Yannick Y
                Nov 6 '17 at 16:08














              • 2





                +1 for autossh, it does what it says on the tin. I believe part of its functionality also is to send keep-alive style packets to prevent any kind of timeout.

                – akent
                Sep 8 '09 at 13:55






              • 27





                Could you put the example tunnel using autossh in the answer?

                – Ehtesh Choudhury
                Dec 20 '12 at 21:45








              • 3





                autossh -f -nNT -i ~/keypair.pem -R 2000:localhost:22 username@myoutsidebox.com You might notice that I set this up using -nNT which doesn't create a remote terminal so that I can put autossh into the background, and the -i option for SSH to use a .pem file. If you're going to be keeping a connection open all the time, I definitely recommend going through the extra setup.

                – juckele
                Aug 31 '15 at 20:01








              • 2





                For what it's worth, it looks like it's typically better to omit the -M parameter: bugs.debian.org/cgi-bin/bugreport.cgi?bug=351162

                – rinogo
                Sep 15 '15 at 22:40








              • 1





                How does that work if I have a passphrase ? would it store that passphrase in a keychain ( for example on a mac ) ?

                – Yannick Y
                Nov 6 '17 at 16:08








              2




              2





              +1 for autossh, it does what it says on the tin. I believe part of its functionality also is to send keep-alive style packets to prevent any kind of timeout.

              – akent
              Sep 8 '09 at 13:55





              +1 for autossh, it does what it says on the tin. I believe part of its functionality also is to send keep-alive style packets to prevent any kind of timeout.

              – akent
              Sep 8 '09 at 13:55




              27




              27





              Could you put the example tunnel using autossh in the answer?

              – Ehtesh Choudhury
              Dec 20 '12 at 21:45







              Could you put the example tunnel using autossh in the answer?

              – Ehtesh Choudhury
              Dec 20 '12 at 21:45






              3




              3





              autossh -f -nNT -i ~/keypair.pem -R 2000:localhost:22 username@myoutsidebox.com You might notice that I set this up using -nNT which doesn't create a remote terminal so that I can put autossh into the background, and the -i option for SSH to use a .pem file. If you're going to be keeping a connection open all the time, I definitely recommend going through the extra setup.

              – juckele
              Aug 31 '15 at 20:01







              autossh -f -nNT -i ~/keypair.pem -R 2000:localhost:22 username@myoutsidebox.com You might notice that I set this up using -nNT which doesn't create a remote terminal so that I can put autossh into the background, and the -i option for SSH to use a .pem file. If you're going to be keeping a connection open all the time, I definitely recommend going through the extra setup.

              – juckele
              Aug 31 '15 at 20:01






              2




              2





              For what it's worth, it looks like it's typically better to omit the -M parameter: bugs.debian.org/cgi-bin/bugreport.cgi?bug=351162

              – rinogo
              Sep 15 '15 at 22:40







              For what it's worth, it looks like it's typically better to omit the -M parameter: bugs.debian.org/cgi-bin/bugreport.cgi?bug=351162

              – rinogo
              Sep 15 '15 at 22:40






              1




              1





              How does that work if I have a passphrase ? would it store that passphrase in a keychain ( for example on a mac ) ?

              – Yannick Y
              Nov 6 '17 at 16:08





              How does that work if I have a passphrase ? would it store that passphrase in a keychain ( for example on a mac ) ?

              – Yannick Y
              Nov 6 '17 at 16:08













              37














              All stateful firewalls forget about a connection after not seeing a packet for that connection for some time (to prevent the state tables from becoming full of connections where both ends died without closing the connection). Most TCP implementations will send a keepalive packet after a long time without hearing from the other side (2 hours is a common value). If, however, there is a stateful firewall which forgets about the connection before the keepalive packets can be sent, a long-lived but idle connection will die.



              If that is the case, the solution is to prevent the connection from becoming idle. OpenSSH has an option called ServerAliveInterval which can be used to prevent the connection from being idle for too long (as a bonus, it will detect when the peer died sooner even if the connection is idle).






              share|improve this answer


























              • The interval specified is in seconds, so you can provide some fine tuning. If your stateful firewall has a 5 minute idle timeout, then 60 or 120 seconds is enough to keep the connection open. It's one of the ways I keep my ssh sessions through my home router open.

                – Darren Hall
                Dec 2 '09 at 21:16











              • Thanks, this helped. But note (from a lower-ranked answer here, superuser.com/a/146641/115515) that if you specify ServerAliveInterval and not ServerAliveCountMax, you may find ssh intentionally disconnecting sooner than you wanted.

                – metamatt
                Jan 26 '12 at 21:54






              • 4





                @metamatt, that lower-ranked answer you reference is lower-ranked for good reason: IT IS WRONG.

                – Lambart
                Feb 20 '14 at 0:14
















              37














              All stateful firewalls forget about a connection after not seeing a packet for that connection for some time (to prevent the state tables from becoming full of connections where both ends died without closing the connection). Most TCP implementations will send a keepalive packet after a long time without hearing from the other side (2 hours is a common value). If, however, there is a stateful firewall which forgets about the connection before the keepalive packets can be sent, a long-lived but idle connection will die.



              If that is the case, the solution is to prevent the connection from becoming idle. OpenSSH has an option called ServerAliveInterval which can be used to prevent the connection from being idle for too long (as a bonus, it will detect when the peer died sooner even if the connection is idle).






              share|improve this answer


























              • The interval specified is in seconds, so you can provide some fine tuning. If your stateful firewall has a 5 minute idle timeout, then 60 or 120 seconds is enough to keep the connection open. It's one of the ways I keep my ssh sessions through my home router open.

                – Darren Hall
                Dec 2 '09 at 21:16











              • Thanks, this helped. But note (from a lower-ranked answer here, superuser.com/a/146641/115515) that if you specify ServerAliveInterval and not ServerAliveCountMax, you may find ssh intentionally disconnecting sooner than you wanted.

                – metamatt
                Jan 26 '12 at 21:54






              • 4





                @metamatt, that lower-ranked answer you reference is lower-ranked for good reason: IT IS WRONG.

                – Lambart
                Feb 20 '14 at 0:14














              37












              37








              37







              All stateful firewalls forget about a connection after not seeing a packet for that connection for some time (to prevent the state tables from becoming full of connections where both ends died without closing the connection). Most TCP implementations will send a keepalive packet after a long time without hearing from the other side (2 hours is a common value). If, however, there is a stateful firewall which forgets about the connection before the keepalive packets can be sent, a long-lived but idle connection will die.



              If that is the case, the solution is to prevent the connection from becoming idle. OpenSSH has an option called ServerAliveInterval which can be used to prevent the connection from being idle for too long (as a bonus, it will detect when the peer died sooner even if the connection is idle).






              share|improve this answer















              All stateful firewalls forget about a connection after not seeing a packet for that connection for some time (to prevent the state tables from becoming full of connections where both ends died without closing the connection). Most TCP implementations will send a keepalive packet after a long time without hearing from the other side (2 hours is a common value). If, however, there is a stateful firewall which forgets about the connection before the keepalive packets can be sent, a long-lived but idle connection will die.



              If that is the case, the solution is to prevent the connection from becoming idle. OpenSSH has an option called ServerAliveInterval which can be used to prevent the connection from being idle for too long (as a bonus, it will detect when the peer died sooner even if the connection is idle).







              share|improve this answer














              share|improve this answer



              share|improve this answer








              edited Jan 25 at 2:32









              Xilexio

              1033




              1033










              answered Sep 28 '09 at 13:47









              CesarBCesarB

              3,98512222




              3,98512222













              • The interval specified is in seconds, so you can provide some fine tuning. If your stateful firewall has a 5 minute idle timeout, then 60 or 120 seconds is enough to keep the connection open. It's one of the ways I keep my ssh sessions through my home router open.

                – Darren Hall
                Dec 2 '09 at 21:16











              • Thanks, this helped. But note (from a lower-ranked answer here, superuser.com/a/146641/115515) that if you specify ServerAliveInterval and not ServerAliveCountMax, you may find ssh intentionally disconnecting sooner than you wanted.

                – metamatt
                Jan 26 '12 at 21:54






              • 4





                @metamatt, that lower-ranked answer you reference is lower-ranked for good reason: IT IS WRONG.

                – Lambart
                Feb 20 '14 at 0:14



















              • The interval specified is in seconds, so you can provide some fine tuning. If your stateful firewall has a 5 minute idle timeout, then 60 or 120 seconds is enough to keep the connection open. It's one of the ways I keep my ssh sessions through my home router open.

                – Darren Hall
                Dec 2 '09 at 21:16











              • Thanks, this helped. But note (from a lower-ranked answer here, superuser.com/a/146641/115515) that if you specify ServerAliveInterval and not ServerAliveCountMax, you may find ssh intentionally disconnecting sooner than you wanted.

                – metamatt
                Jan 26 '12 at 21:54






              • 4





                @metamatt, that lower-ranked answer you reference is lower-ranked for good reason: IT IS WRONG.

                – Lambart
                Feb 20 '14 at 0:14

















              The interval specified is in seconds, so you can provide some fine tuning. If your stateful firewall has a 5 minute idle timeout, then 60 or 120 seconds is enough to keep the connection open. It's one of the ways I keep my ssh sessions through my home router open.

              – Darren Hall
              Dec 2 '09 at 21:16





              The interval specified is in seconds, so you can provide some fine tuning. If your stateful firewall has a 5 minute idle timeout, then 60 or 120 seconds is enough to keep the connection open. It's one of the ways I keep my ssh sessions through my home router open.

              – Darren Hall
              Dec 2 '09 at 21:16













              Thanks, this helped. But note (from a lower-ranked answer here, superuser.com/a/146641/115515) that if you specify ServerAliveInterval and not ServerAliveCountMax, you may find ssh intentionally disconnecting sooner than you wanted.

              – metamatt
              Jan 26 '12 at 21:54





              Thanks, this helped. But note (from a lower-ranked answer here, superuser.com/a/146641/115515) that if you specify ServerAliveInterval and not ServerAliveCountMax, you may find ssh intentionally disconnecting sooner than you wanted.

              – metamatt
              Jan 26 '12 at 21:54




              4




              4





              @metamatt, that lower-ranked answer you reference is lower-ranked for good reason: IT IS WRONG.

              – Lambart
              Feb 20 '14 at 0:14





              @metamatt, that lower-ranked answer you reference is lower-ranked for good reason: IT IS WRONG.

              – Lambart
              Feb 20 '14 at 0:14











              23














              On your own mac or linux machine configure your ssh keep the server ssh alive every 3 minutes. Open a terminal and go your your invisible .ssh in your home:



              cd ~/.ssh/ 


              then create a 1 line config file with:



              echo "ServerAliveInterval 180" >> config


              you should also add:



              ServerAliveCountMax xxxx (high number)


              the default is 3 so ServerAliveInterval 180 will stop sending after 9 minutes (3 of the 3-minute interval specified by ServerAliveInterval).






              share|improve this answer





















              • 2





                Note that your command is not recommended if you already have a config file. Using >> for redirection would be a lot better!

                – Peltier
                Mar 18 '11 at 9:34











              • why does ServerAliveInterval 180 give us 6 minutes? intuition makes me try this : 180/60 == 3. So, does ServerAliveInterval work in multiples of 30 secs?

                – nemesisfixx
                Nov 30 '11 at 14:37











              • @mcnemesis: ServerAliveInterval 180 means 3 minutes. ServerAliveCountMax default of 3 means 3 of those intervals, so 9 minutes.

                – metamatt
                Jan 26 '12 at 21:50






              • 1





                I'm voting this answer up because thanks for mentioning ServerAliveCountMax, and what happens if you specify ServerAliveInterval without ServerAliveCountMax. But like the preceding comments, I notice the calculation on "will stop sending after" is wrong, and I think this answer would serve better if it just gave the information on these options, not telling us how to apply them with cd and echo commands.

                – metamatt
                Jan 26 '12 at 21:51






              • 16





                Downvoting because it makes no sense to set ServerAliveCountMax to a "high number". ServerAliveCountMax specifies how many times it will try to send the "keepalive" message before giving up. The default is 3, so with ServerAliveInterval 180, it will stop sending ONLY if the server has NOT RESPONDED after 9 minutes, in which case your connection is probably well and truly dead.

                – Lambart
                Feb 20 '14 at 0:13
















              23














              On your own mac or linux machine configure your ssh keep the server ssh alive every 3 minutes. Open a terminal and go your your invisible .ssh in your home:



              cd ~/.ssh/ 


              then create a 1 line config file with:



              echo "ServerAliveInterval 180" >> config


              you should also add:



              ServerAliveCountMax xxxx (high number)


              the default is 3 so ServerAliveInterval 180 will stop sending after 9 minutes (3 of the 3-minute interval specified by ServerAliveInterval).






              share|improve this answer





















              • 2





                Note that your command is not recommended if you already have a config file. Using >> for redirection would be a lot better!

                – Peltier
                Mar 18 '11 at 9:34











              • why does ServerAliveInterval 180 give us 6 minutes? intuition makes me try this : 180/60 == 3. So, does ServerAliveInterval work in multiples of 30 secs?

                – nemesisfixx
                Nov 30 '11 at 14:37











              • @mcnemesis: ServerAliveInterval 180 means 3 minutes. ServerAliveCountMax default of 3 means 3 of those intervals, so 9 minutes.

                – metamatt
                Jan 26 '12 at 21:50






              • 1





                I'm voting this answer up because thanks for mentioning ServerAliveCountMax, and what happens if you specify ServerAliveInterval without ServerAliveCountMax. But like the preceding comments, I notice the calculation on "will stop sending after" is wrong, and I think this answer would serve better if it just gave the information on these options, not telling us how to apply them with cd and echo commands.

                – metamatt
                Jan 26 '12 at 21:51






              • 16





                Downvoting because it makes no sense to set ServerAliveCountMax to a "high number". ServerAliveCountMax specifies how many times it will try to send the "keepalive" message before giving up. The default is 3, so with ServerAliveInterval 180, it will stop sending ONLY if the server has NOT RESPONDED after 9 minutes, in which case your connection is probably well and truly dead.

                – Lambart
                Feb 20 '14 at 0:13














              23












              23








              23







              On your own mac or linux machine configure your ssh keep the server ssh alive every 3 minutes. Open a terminal and go your your invisible .ssh in your home:



              cd ~/.ssh/ 


              then create a 1 line config file with:



              echo "ServerAliveInterval 180" >> config


              you should also add:



              ServerAliveCountMax xxxx (high number)


              the default is 3 so ServerAliveInterval 180 will stop sending after 9 minutes (3 of the 3-minute interval specified by ServerAliveInterval).






              share|improve this answer















              On your own mac or linux machine configure your ssh keep the server ssh alive every 3 minutes. Open a terminal and go your your invisible .ssh in your home:



              cd ~/.ssh/ 


              then create a 1 line config file with:



              echo "ServerAliveInterval 180" >> config


              you should also add:



              ServerAliveCountMax xxxx (high number)


              the default is 3 so ServerAliveInterval 180 will stop sending after 9 minutes (3 of the 3-minute interval specified by ServerAliveInterval).







              share|improve this answer














              share|improve this answer



              share|improve this answer








              edited Jan 26 '12 at 21:55









              metamatt

              1035




              1035










              answered May 29 '10 at 13:45









              David ShawDavid Shaw

              25522




              25522








              • 2





                Note that your command is not recommended if you already have a config file. Using >> for redirection would be a lot better!

                – Peltier
                Mar 18 '11 at 9:34











              • why does ServerAliveInterval 180 give us 6 minutes? intuition makes me try this : 180/60 == 3. So, does ServerAliveInterval work in multiples of 30 secs?

                – nemesisfixx
                Nov 30 '11 at 14:37











              • @mcnemesis: ServerAliveInterval 180 means 3 minutes. ServerAliveCountMax default of 3 means 3 of those intervals, so 9 minutes.

                – metamatt
                Jan 26 '12 at 21:50






              • 1





                I'm voting this answer up because thanks for mentioning ServerAliveCountMax, and what happens if you specify ServerAliveInterval without ServerAliveCountMax. But like the preceding comments, I notice the calculation on "will stop sending after" is wrong, and I think this answer would serve better if it just gave the information on these options, not telling us how to apply them with cd and echo commands.

                – metamatt
                Jan 26 '12 at 21:51






              • 16





                Downvoting because it makes no sense to set ServerAliveCountMax to a "high number". ServerAliveCountMax specifies how many times it will try to send the "keepalive" message before giving up. The default is 3, so with ServerAliveInterval 180, it will stop sending ONLY if the server has NOT RESPONDED after 9 minutes, in which case your connection is probably well and truly dead.

                – Lambart
                Feb 20 '14 at 0:13














              • 2





                Note that your command is not recommended if you already have a config file. Using >> for redirection would be a lot better!

                – Peltier
                Mar 18 '11 at 9:34











              • why does ServerAliveInterval 180 give us 6 minutes? intuition makes me try this : 180/60 == 3. So, does ServerAliveInterval work in multiples of 30 secs?

                – nemesisfixx
                Nov 30 '11 at 14:37











              • @mcnemesis: ServerAliveInterval 180 means 3 minutes. ServerAliveCountMax default of 3 means 3 of those intervals, so 9 minutes.

                – metamatt
                Jan 26 '12 at 21:50






              • 1





                I'm voting this answer up because thanks for mentioning ServerAliveCountMax, and what happens if you specify ServerAliveInterval without ServerAliveCountMax. But like the preceding comments, I notice the calculation on "will stop sending after" is wrong, and I think this answer would serve better if it just gave the information on these options, not telling us how to apply them with cd and echo commands.

                – metamatt
                Jan 26 '12 at 21:51






              • 16





                Downvoting because it makes no sense to set ServerAliveCountMax to a "high number". ServerAliveCountMax specifies how many times it will try to send the "keepalive" message before giving up. The default is 3, so with ServerAliveInterval 180, it will stop sending ONLY if the server has NOT RESPONDED after 9 minutes, in which case your connection is probably well and truly dead.

                – Lambart
                Feb 20 '14 at 0:13








              2




              2





              Note that your command is not recommended if you already have a config file. Using >> for redirection would be a lot better!

              – Peltier
              Mar 18 '11 at 9:34





              Note that your command is not recommended if you already have a config file. Using >> for redirection would be a lot better!

              – Peltier
              Mar 18 '11 at 9:34













              why does ServerAliveInterval 180 give us 6 minutes? intuition makes me try this : 180/60 == 3. So, does ServerAliveInterval work in multiples of 30 secs?

              – nemesisfixx
              Nov 30 '11 at 14:37





              why does ServerAliveInterval 180 give us 6 minutes? intuition makes me try this : 180/60 == 3. So, does ServerAliveInterval work in multiples of 30 secs?

              – nemesisfixx
              Nov 30 '11 at 14:37













              @mcnemesis: ServerAliveInterval 180 means 3 minutes. ServerAliveCountMax default of 3 means 3 of those intervals, so 9 minutes.

              – metamatt
              Jan 26 '12 at 21:50





              @mcnemesis: ServerAliveInterval 180 means 3 minutes. ServerAliveCountMax default of 3 means 3 of those intervals, so 9 minutes.

              – metamatt
              Jan 26 '12 at 21:50




              1




              1





              I'm voting this answer up because thanks for mentioning ServerAliveCountMax, and what happens if you specify ServerAliveInterval without ServerAliveCountMax. But like the preceding comments, I notice the calculation on "will stop sending after" is wrong, and I think this answer would serve better if it just gave the information on these options, not telling us how to apply them with cd and echo commands.

              – metamatt
              Jan 26 '12 at 21:51





              I'm voting this answer up because thanks for mentioning ServerAliveCountMax, and what happens if you specify ServerAliveInterval without ServerAliveCountMax. But like the preceding comments, I notice the calculation on "will stop sending after" is wrong, and I think this answer would serve better if it just gave the information on these options, not telling us how to apply them with cd and echo commands.

              – metamatt
              Jan 26 '12 at 21:51




              16




              16





              Downvoting because it makes no sense to set ServerAliveCountMax to a "high number". ServerAliveCountMax specifies how many times it will try to send the "keepalive" message before giving up. The default is 3, so with ServerAliveInterval 180, it will stop sending ONLY if the server has NOT RESPONDED after 9 minutes, in which case your connection is probably well and truly dead.

              – Lambart
              Feb 20 '14 at 0:13





              Downvoting because it makes no sense to set ServerAliveCountMax to a "high number". ServerAliveCountMax specifies how many times it will try to send the "keepalive" message before giving up. The default is 3, so with ServerAliveInterval 180, it will stop sending ONLY if the server has NOT RESPONDED after 9 minutes, in which case your connection is probably well and truly dead.

              – Lambart
              Feb 20 '14 at 0:13











              20














              I've used the following Bash script to keep spawning new ssh tunnels when the previous one dies. Using a script is handy when you don't want or can't install additional packages or use compiler.



              while true
              do
              ssh <ssh_options> [user@]hostname
              sleep 15
              done


              Note that this requires a keyfile to establish the connection automatically but that is the case with autossh, too.






              share|improve this answer



















              • 1





                You should add any reasons that you'd use this script over autossh, or is it just that it's easier this way?

                – kyrias
                Oct 20 '12 at 17:25






              • 4





                This wouldn't help if ssh itself freezes, would it?

                – nafg
                Nov 25 '13 at 23:59






              • 1





                It helps if you can't install things in the server. autossh doesn't come preinstalled and bureucracy it's sometimes very obtuse.

                – quarkex
                Mar 13 '17 at 15:13











              • Yes, preferable not to have to install things. I've been doing it this way for a year as my only way to keep a remote machine accessible (even set crontab to run it upon reboot). It's never failed, and more importantly, I know why it will never fail.

                – sudo
                Apr 2 '18 at 6:42


















              20














              I've used the following Bash script to keep spawning new ssh tunnels when the previous one dies. Using a script is handy when you don't want or can't install additional packages or use compiler.



              while true
              do
              ssh <ssh_options> [user@]hostname
              sleep 15
              done


              Note that this requires a keyfile to establish the connection automatically but that is the case with autossh, too.






              share|improve this answer



















              • 1





                You should add any reasons that you'd use this script over autossh, or is it just that it's easier this way?

                – kyrias
                Oct 20 '12 at 17:25






              • 4





                This wouldn't help if ssh itself freezes, would it?

                – nafg
                Nov 25 '13 at 23:59






              • 1





                It helps if you can't install things in the server. autossh doesn't come preinstalled and bureucracy it's sometimes very obtuse.

                – quarkex
                Mar 13 '17 at 15:13











              • Yes, preferable not to have to install things. I've been doing it this way for a year as my only way to keep a remote machine accessible (even set crontab to run it upon reboot). It's never failed, and more importantly, I know why it will never fail.

                – sudo
                Apr 2 '18 at 6:42
















              20












              20








              20







              I've used the following Bash script to keep spawning new ssh tunnels when the previous one dies. Using a script is handy when you don't want or can't install additional packages or use compiler.



              while true
              do
              ssh <ssh_options> [user@]hostname
              sleep 15
              done


              Note that this requires a keyfile to establish the connection automatically but that is the case with autossh, too.






              share|improve this answer













              I've used the following Bash script to keep spawning new ssh tunnels when the previous one dies. Using a script is handy when you don't want or can't install additional packages or use compiler.



              while true
              do
              ssh <ssh_options> [user@]hostname
              sleep 15
              done


              Note that this requires a keyfile to establish the connection automatically but that is the case with autossh, too.







              share|improve this answer












              share|improve this answer



              share|improve this answer










              answered Sep 22 '09 at 14:58









              JawaJawa

              3,15982435




              3,15982435








              • 1





                You should add any reasons that you'd use this script over autossh, or is it just that it's easier this way?

                – kyrias
                Oct 20 '12 at 17:25






              • 4





                This wouldn't help if ssh itself freezes, would it?

                – nafg
                Nov 25 '13 at 23:59






              • 1





                It helps if you can't install things in the server. autossh doesn't come preinstalled and bureucracy it's sometimes very obtuse.

                – quarkex
                Mar 13 '17 at 15:13











              • Yes, preferable not to have to install things. I've been doing it this way for a year as my only way to keep a remote machine accessible (even set crontab to run it upon reboot). It's never failed, and more importantly, I know why it will never fail.

                – sudo
                Apr 2 '18 at 6:42
















              • 1





                You should add any reasons that you'd use this script over autossh, or is it just that it's easier this way?

                – kyrias
                Oct 20 '12 at 17:25






              • 4





                This wouldn't help if ssh itself freezes, would it?

                – nafg
                Nov 25 '13 at 23:59






              • 1





                It helps if you can't install things in the server. autossh doesn't come preinstalled and bureucracy it's sometimes very obtuse.

                – quarkex
                Mar 13 '17 at 15:13











              • Yes, preferable not to have to install things. I've been doing it this way for a year as my only way to keep a remote machine accessible (even set crontab to run it upon reboot). It's never failed, and more importantly, I know why it will never fail.

                – sudo
                Apr 2 '18 at 6:42










              1




              1





              You should add any reasons that you'd use this script over autossh, or is it just that it's easier this way?

              – kyrias
              Oct 20 '12 at 17:25





              You should add any reasons that you'd use this script over autossh, or is it just that it's easier this way?

              – kyrias
              Oct 20 '12 at 17:25




              4




              4





              This wouldn't help if ssh itself freezes, would it?

              – nafg
              Nov 25 '13 at 23:59





              This wouldn't help if ssh itself freezes, would it?

              – nafg
              Nov 25 '13 at 23:59




              1




              1





              It helps if you can't install things in the server. autossh doesn't come preinstalled and bureucracy it's sometimes very obtuse.

              – quarkex
              Mar 13 '17 at 15:13





              It helps if you can't install things in the server. autossh doesn't come preinstalled and bureucracy it's sometimes very obtuse.

              – quarkex
              Mar 13 '17 at 15:13













              Yes, preferable not to have to install things. I've been doing it this way for a year as my only way to keep a remote machine accessible (even set crontab to run it upon reboot). It's never failed, and more importantly, I know why it will never fail.

              – sudo
              Apr 2 '18 at 6:42







              Yes, preferable not to have to install things. I've been doing it this way for a year as my only way to keep a remote machine accessible (even set crontab to run it upon reboot). It's never failed, and more importantly, I know why it will never fail.

              – sudo
              Apr 2 '18 at 6:42













              13














              Systemd is ideally suited for this.



              Create a service file /etc/systemd/system/sshtunnel.service containing:



              [Unit]
              Description=SSH Tunnel
              After=network.target

              [Service]
              Restart=always
              RestartSec=20
              User=sshtunnel
              ExecStart=/bin/ssh -NT -o ServerAliveInterval=60 -L 5900:localhost:5900 user@otherserver

              [Install]
              WantedBy=multi-user.target


              (Modify the ssh command to suit)




              • this will run as user sshtunnel so make sure that user exists first

              • issue systemctl enable sshtunnel to set it to start at boot time

              • issue systemctl start sshtunnel to start immediately




              Update Jan 2018: some distros (e.g. Fedora 27) may use SELinux policy to prevent the use of SSH from systemd init, in which case a custom policy will need to be created to provide the necessary exemptions.






              share|improve this answer





















              • 2





                This looks very similar to my gist: gist.github.com/guettli/… Feedback is welcome!

                – guettli
                Dec 22 '17 at 11:47











              • Excellent for a systemd system. If one uses Restart=on-failure then manually killing the SSH client will not result in a restart-by-systemd as the SSH client with exit with success.

                – David Tonhofer
                Mar 22 '18 at 19:36











              • If you want to start ssh from a (bash) script given as argument to ExecStart for example to build the ssh argument list, do basic checks etc then call it from the script like so exec /bin/ssh -N .... Here is my command: exec /bin/ssh -N -oExitOnForwardFailure=Yes -oTCPKeepAlive=no -oServerAliveInterval=5 -oServerAliveCountMax=6 -i "${LOCAL_PRIVATE_KEY}" -L "${TUNNEL_INLET}:${TUNNEL_OUTLET}" "${REMOTE_USER}@${REMOTE_MACHINE}" where TUNNEL_INLET="127.0.0.1:3307" and TUNNEL_OUTLET="127.0.0.1:3306"

                – David Tonhofer
                Mar 22 '18 at 19:42


















              13














              Systemd is ideally suited for this.



              Create a service file /etc/systemd/system/sshtunnel.service containing:



              [Unit]
              Description=SSH Tunnel
              After=network.target

              [Service]
              Restart=always
              RestartSec=20
              User=sshtunnel
              ExecStart=/bin/ssh -NT -o ServerAliveInterval=60 -L 5900:localhost:5900 user@otherserver

              [Install]
              WantedBy=multi-user.target


              (Modify the ssh command to suit)




              • this will run as user sshtunnel so make sure that user exists first

              • issue systemctl enable sshtunnel to set it to start at boot time

              • issue systemctl start sshtunnel to start immediately




              Update Jan 2018: some distros (e.g. Fedora 27) may use SELinux policy to prevent the use of SSH from systemd init, in which case a custom policy will need to be created to provide the necessary exemptions.






              share|improve this answer





















              • 2





                This looks very similar to my gist: gist.github.com/guettli/… Feedback is welcome!

                – guettli
                Dec 22 '17 at 11:47











              • Excellent for a systemd system. If one uses Restart=on-failure then manually killing the SSH client will not result in a restart-by-systemd as the SSH client with exit with success.

                – David Tonhofer
                Mar 22 '18 at 19:36











              • If you want to start ssh from a (bash) script given as argument to ExecStart for example to build the ssh argument list, do basic checks etc then call it from the script like so exec /bin/ssh -N .... Here is my command: exec /bin/ssh -N -oExitOnForwardFailure=Yes -oTCPKeepAlive=no -oServerAliveInterval=5 -oServerAliveCountMax=6 -i "${LOCAL_PRIVATE_KEY}" -L "${TUNNEL_INLET}:${TUNNEL_OUTLET}" "${REMOTE_USER}@${REMOTE_MACHINE}" where TUNNEL_INLET="127.0.0.1:3307" and TUNNEL_OUTLET="127.0.0.1:3306"

                – David Tonhofer
                Mar 22 '18 at 19:42
















              13












              13








              13







              Systemd is ideally suited for this.



              Create a service file /etc/systemd/system/sshtunnel.service containing:



              [Unit]
              Description=SSH Tunnel
              After=network.target

              [Service]
              Restart=always
              RestartSec=20
              User=sshtunnel
              ExecStart=/bin/ssh -NT -o ServerAliveInterval=60 -L 5900:localhost:5900 user@otherserver

              [Install]
              WantedBy=multi-user.target


              (Modify the ssh command to suit)




              • this will run as user sshtunnel so make sure that user exists first

              • issue systemctl enable sshtunnel to set it to start at boot time

              • issue systemctl start sshtunnel to start immediately




              Update Jan 2018: some distros (e.g. Fedora 27) may use SELinux policy to prevent the use of SSH from systemd init, in which case a custom policy will need to be created to provide the necessary exemptions.






              share|improve this answer















              Systemd is ideally suited for this.



              Create a service file /etc/systemd/system/sshtunnel.service containing:



              [Unit]
              Description=SSH Tunnel
              After=network.target

              [Service]
              Restart=always
              RestartSec=20
              User=sshtunnel
              ExecStart=/bin/ssh -NT -o ServerAliveInterval=60 -L 5900:localhost:5900 user@otherserver

              [Install]
              WantedBy=multi-user.target


              (Modify the ssh command to suit)




              • this will run as user sshtunnel so make sure that user exists first

              • issue systemctl enable sshtunnel to set it to start at boot time

              • issue systemctl start sshtunnel to start immediately




              Update Jan 2018: some distros (e.g. Fedora 27) may use SELinux policy to prevent the use of SSH from systemd init, in which case a custom policy will need to be created to provide the necessary exemptions.







              share|improve this answer














              share|improve this answer



              share|improve this answer








              edited Jan 14 '18 at 3:39

























              answered Jul 28 '16 at 6:10









              IanBIanB

              28528




              28528








              • 2





                This looks very similar to my gist: gist.github.com/guettli/… Feedback is welcome!

                – guettli
                Dec 22 '17 at 11:47











              • Excellent for a systemd system. If one uses Restart=on-failure then manually killing the SSH client will not result in a restart-by-systemd as the SSH client with exit with success.

                – David Tonhofer
                Mar 22 '18 at 19:36











              • If you want to start ssh from a (bash) script given as argument to ExecStart for example to build the ssh argument list, do basic checks etc then call it from the script like so exec /bin/ssh -N .... Here is my command: exec /bin/ssh -N -oExitOnForwardFailure=Yes -oTCPKeepAlive=no -oServerAliveInterval=5 -oServerAliveCountMax=6 -i "${LOCAL_PRIVATE_KEY}" -L "${TUNNEL_INLET}:${TUNNEL_OUTLET}" "${REMOTE_USER}@${REMOTE_MACHINE}" where TUNNEL_INLET="127.0.0.1:3307" and TUNNEL_OUTLET="127.0.0.1:3306"

                – David Tonhofer
                Mar 22 '18 at 19:42
















              • 2





                This looks very similar to my gist: gist.github.com/guettli/… Feedback is welcome!

                – guettli
                Dec 22 '17 at 11:47











              • Excellent for a systemd system. If one uses Restart=on-failure then manually killing the SSH client will not result in a restart-by-systemd as the SSH client with exit with success.

                – David Tonhofer
                Mar 22 '18 at 19:36











              • If you want to start ssh from a (bash) script given as argument to ExecStart for example to build the ssh argument list, do basic checks etc then call it from the script like so exec /bin/ssh -N .... Here is my command: exec /bin/ssh -N -oExitOnForwardFailure=Yes -oTCPKeepAlive=no -oServerAliveInterval=5 -oServerAliveCountMax=6 -i "${LOCAL_PRIVATE_KEY}" -L "${TUNNEL_INLET}:${TUNNEL_OUTLET}" "${REMOTE_USER}@${REMOTE_MACHINE}" where TUNNEL_INLET="127.0.0.1:3307" and TUNNEL_OUTLET="127.0.0.1:3306"

                – David Tonhofer
                Mar 22 '18 at 19:42










              2




              2





              This looks very similar to my gist: gist.github.com/guettli/… Feedback is welcome!

              – guettli
              Dec 22 '17 at 11:47





              This looks very similar to my gist: gist.github.com/guettli/… Feedback is welcome!

              – guettli
              Dec 22 '17 at 11:47













              Excellent for a systemd system. If one uses Restart=on-failure then manually killing the SSH client will not result in a restart-by-systemd as the SSH client with exit with success.

              – David Tonhofer
              Mar 22 '18 at 19:36





              Excellent for a systemd system. If one uses Restart=on-failure then manually killing the SSH client will not result in a restart-by-systemd as the SSH client with exit with success.

              – David Tonhofer
              Mar 22 '18 at 19:36













              If you want to start ssh from a (bash) script given as argument to ExecStart for example to build the ssh argument list, do basic checks etc then call it from the script like so exec /bin/ssh -N .... Here is my command: exec /bin/ssh -N -oExitOnForwardFailure=Yes -oTCPKeepAlive=no -oServerAliveInterval=5 -oServerAliveCountMax=6 -i "${LOCAL_PRIVATE_KEY}" -L "${TUNNEL_INLET}:${TUNNEL_OUTLET}" "${REMOTE_USER}@${REMOTE_MACHINE}" where TUNNEL_INLET="127.0.0.1:3307" and TUNNEL_OUTLET="127.0.0.1:3306"

              – David Tonhofer
              Mar 22 '18 at 19:42







              If you want to start ssh from a (bash) script given as argument to ExecStart for example to build the ssh argument list, do basic checks etc then call it from the script like so exec /bin/ssh -N .... Here is my command: exec /bin/ssh -N -oExitOnForwardFailure=Yes -oTCPKeepAlive=no -oServerAliveInterval=5 -oServerAliveCountMax=6 -i "${LOCAL_PRIVATE_KEY}" -L "${TUNNEL_INLET}:${TUNNEL_OUTLET}" "${REMOTE_USER}@${REMOTE_MACHINE}" where TUNNEL_INLET="127.0.0.1:3307" and TUNNEL_OUTLET="127.0.0.1:3306"

              – David Tonhofer
              Mar 22 '18 at 19:42













              9














              It sure looks to me that you're all misinterpreting ServerAliveCountMax. As I understand the docs, it is the number of server alive messages which can go unanswered without the connection being terminated. So in cases like we're discussing here, setting it to a high value will just ensure that a hung connection will not be detected and terminated!



              Simply setting ServerAliveInterval should be sufficient to solve the problem with a firewall forgetting about the connection, and leaving ServerAliveCountMax low will allow the originating end to notice the failure and terminate if the connection fails anyway.



              What you want is, 1) for the connection to stay open permanently under normal circumstances, 2) for connection failure to be detected and the originating side to exit on failure, and 3) for the ssh command to be re-issued every time it exits (how you do that is very platform dependent, the "while true" script suggested by Jawa is one way, on OS X I actually set up a launchd item).






              share|improve this answer




























                9














                It sure looks to me that you're all misinterpreting ServerAliveCountMax. As I understand the docs, it is the number of server alive messages which can go unanswered without the connection being terminated. So in cases like we're discussing here, setting it to a high value will just ensure that a hung connection will not be detected and terminated!



                Simply setting ServerAliveInterval should be sufficient to solve the problem with a firewall forgetting about the connection, and leaving ServerAliveCountMax low will allow the originating end to notice the failure and terminate if the connection fails anyway.



                What you want is, 1) for the connection to stay open permanently under normal circumstances, 2) for connection failure to be detected and the originating side to exit on failure, and 3) for the ssh command to be re-issued every time it exits (how you do that is very platform dependent, the "while true" script suggested by Jawa is one way, on OS X I actually set up a launchd item).






                share|improve this answer


























                  9












                  9








                  9







                  It sure looks to me that you're all misinterpreting ServerAliveCountMax. As I understand the docs, it is the number of server alive messages which can go unanswered without the connection being terminated. So in cases like we're discussing here, setting it to a high value will just ensure that a hung connection will not be detected and terminated!



                  Simply setting ServerAliveInterval should be sufficient to solve the problem with a firewall forgetting about the connection, and leaving ServerAliveCountMax low will allow the originating end to notice the failure and terminate if the connection fails anyway.



                  What you want is, 1) for the connection to stay open permanently under normal circumstances, 2) for connection failure to be detected and the originating side to exit on failure, and 3) for the ssh command to be re-issued every time it exits (how you do that is very platform dependent, the "while true" script suggested by Jawa is one way, on OS X I actually set up a launchd item).






                  share|improve this answer













                  It sure looks to me that you're all misinterpreting ServerAliveCountMax. As I understand the docs, it is the number of server alive messages which can go unanswered without the connection being terminated. So in cases like we're discussing here, setting it to a high value will just ensure that a hung connection will not be detected and terminated!



                  Simply setting ServerAliveInterval should be sufficient to solve the problem with a firewall forgetting about the connection, and leaving ServerAliveCountMax low will allow the originating end to notice the failure and terminate if the connection fails anyway.



                  What you want is, 1) for the connection to stay open permanently under normal circumstances, 2) for connection failure to be detected and the originating side to exit on failure, and 3) for the ssh command to be re-issued every time it exits (how you do that is very platform dependent, the "while true" script suggested by Jawa is one way, on OS X I actually set up a launchd item).







                  share|improve this answer












                  share|improve this answer



                  share|improve this answer










                  answered Nov 28 '13 at 1:04









                  user2793784user2793784

                  9111




                  9111























                      9














                      Always use ServerAliveInterval SSH option in case the tunnel issues are generated by expired NAT sessions.



                      Always use a respawning method in case the connectivity goes down entirely, you have at least three options here:




                      • autossh program

                      • bash script (while true do ssh ...; sleep 5; done) do not remove the sleep command, ssh may fail quickly and you'll respawn too many processes


                      • /etc/inittab, to have access to a box shipped and installed in another country, behind NAT, without port forwarding to the box, you can configure it to create an ssh tunnel back to you:



                        tun1:2345:respawn:/usr/bin/ssh -i /path/to/rsaKey -f -N -o "ServerAliveInterval 180" -R 55002:localhost:22 user@publicip 'sleep 365d'



                      • upstart script on Ubuntu, where /etc/inittab is not available:



                        start on net-device-up IFACE=eth0
                        stop on runlevel [01S6]
                        respawn
                        respawn limit 180 900
                        exec ssh -i /path/to/rsaKey -N -o "ServerAliveInterval 180" -R 55002:localhost:22 user@publicip
                        post-stop script
                        sleep 5
                        end script



                      or always use both methods.






                      share|improve this answer





















                      • 1





                        +1 for inline option in case you don't want it for all of your SSH connections

                        – user1146334
                        Jul 7 '14 at 14:29











                      • You write "in case connectivity goes down entirely". Now I don't understand, what problems does autossh fix itself, and what does it not? I thought, of course, it would take care of any broken connection, like unplugging the cable for a few hours, but perhaps not?

                        – Mads Skjern
                        May 12 '16 at 19:02


















                      9














                      Always use ServerAliveInterval SSH option in case the tunnel issues are generated by expired NAT sessions.



                      Always use a respawning method in case the connectivity goes down entirely, you have at least three options here:




                      • autossh program

                      • bash script (while true do ssh ...; sleep 5; done) do not remove the sleep command, ssh may fail quickly and you'll respawn too many processes


                      • /etc/inittab, to have access to a box shipped and installed in another country, behind NAT, without port forwarding to the box, you can configure it to create an ssh tunnel back to you:



                        tun1:2345:respawn:/usr/bin/ssh -i /path/to/rsaKey -f -N -o "ServerAliveInterval 180" -R 55002:localhost:22 user@publicip 'sleep 365d'



                      • upstart script on Ubuntu, where /etc/inittab is not available:



                        start on net-device-up IFACE=eth0
                        stop on runlevel [01S6]
                        respawn
                        respawn limit 180 900
                        exec ssh -i /path/to/rsaKey -N -o "ServerAliveInterval 180" -R 55002:localhost:22 user@publicip
                        post-stop script
                        sleep 5
                        end script



                      or always use both methods.






                      share|improve this answer





















                      • 1





                        +1 for inline option in case you don't want it for all of your SSH connections

                        – user1146334
                        Jul 7 '14 at 14:29











                      • You write "in case connectivity goes down entirely". Now I don't understand, what problems does autossh fix itself, and what does it not? I thought, of course, it would take care of any broken connection, like unplugging the cable for a few hours, but perhaps not?

                        – Mads Skjern
                        May 12 '16 at 19:02
















                      9












                      9








                      9







                      Always use ServerAliveInterval SSH option in case the tunnel issues are generated by expired NAT sessions.



                      Always use a respawning method in case the connectivity goes down entirely, you have at least three options here:




                      • autossh program

                      • bash script (while true do ssh ...; sleep 5; done) do not remove the sleep command, ssh may fail quickly and you'll respawn too many processes


                      • /etc/inittab, to have access to a box shipped and installed in another country, behind NAT, without port forwarding to the box, you can configure it to create an ssh tunnel back to you:



                        tun1:2345:respawn:/usr/bin/ssh -i /path/to/rsaKey -f -N -o "ServerAliveInterval 180" -R 55002:localhost:22 user@publicip 'sleep 365d'



                      • upstart script on Ubuntu, where /etc/inittab is not available:



                        start on net-device-up IFACE=eth0
                        stop on runlevel [01S6]
                        respawn
                        respawn limit 180 900
                        exec ssh -i /path/to/rsaKey -N -o "ServerAliveInterval 180" -R 55002:localhost:22 user@publicip
                        post-stop script
                        sleep 5
                        end script



                      or always use both methods.






                      share|improve this answer















                      Always use ServerAliveInterval SSH option in case the tunnel issues are generated by expired NAT sessions.



                      Always use a respawning method in case the connectivity goes down entirely, you have at least three options here:




                      • autossh program

                      • bash script (while true do ssh ...; sleep 5; done) do not remove the sleep command, ssh may fail quickly and you'll respawn too many processes


                      • /etc/inittab, to have access to a box shipped and installed in another country, behind NAT, without port forwarding to the box, you can configure it to create an ssh tunnel back to you:



                        tun1:2345:respawn:/usr/bin/ssh -i /path/to/rsaKey -f -N -o "ServerAliveInterval 180" -R 55002:localhost:22 user@publicip 'sleep 365d'



                      • upstart script on Ubuntu, where /etc/inittab is not available:



                        start on net-device-up IFACE=eth0
                        stop on runlevel [01S6]
                        respawn
                        respawn limit 180 900
                        exec ssh -i /path/to/rsaKey -N -o "ServerAliveInterval 180" -R 55002:localhost:22 user@publicip
                        post-stop script
                        sleep 5
                        end script



                      or always use both methods.







                      share|improve this answer














                      share|improve this answer



                      share|improve this answer








                      edited Apr 18 '15 at 1:03









                      Roger Dueck

                      1033




                      1033










                      answered Mar 8 '14 at 21:30









                      claudiufclaudiuf

                      32122




                      32122








                      • 1





                        +1 for inline option in case you don't want it for all of your SSH connections

                        – user1146334
                        Jul 7 '14 at 14:29











                      • You write "in case connectivity goes down entirely". Now I don't understand, what problems does autossh fix itself, and what does it not? I thought, of course, it would take care of any broken connection, like unplugging the cable for a few hours, but perhaps not?

                        – Mads Skjern
                        May 12 '16 at 19:02
















                      • 1





                        +1 for inline option in case you don't want it for all of your SSH connections

                        – user1146334
                        Jul 7 '14 at 14:29











                      • You write "in case connectivity goes down entirely". Now I don't understand, what problems does autossh fix itself, and what does it not? I thought, of course, it would take care of any broken connection, like unplugging the cable for a few hours, but perhaps not?

                        – Mads Skjern
                        May 12 '16 at 19:02










                      1




                      1





                      +1 for inline option in case you don't want it for all of your SSH connections

                      – user1146334
                      Jul 7 '14 at 14:29





                      +1 for inline option in case you don't want it for all of your SSH connections

                      – user1146334
                      Jul 7 '14 at 14:29













                      You write "in case connectivity goes down entirely". Now I don't understand, what problems does autossh fix itself, and what does it not? I thought, of course, it would take care of any broken connection, like unplugging the cable for a few hours, but perhaps not?

                      – Mads Skjern
                      May 12 '16 at 19:02







                      You write "in case connectivity goes down entirely". Now I don't understand, what problems does autossh fix itself, and what does it not? I thought, of course, it would take care of any broken connection, like unplugging the cable for a few hours, but perhaps not?

                      – Mads Skjern
                      May 12 '16 at 19:02













                      6














                      I solved this problem with this:



                      Edit



                      ~/.ssh/config


                      And add



                      ServerAliveInterval 15
                      ServerAliveCountMax 4


                      According to man page for ssh_config:



                      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.

                      ServerAliveInterval
                      Sets a timeout interval in seconds after which if no data has
                      been received from the server, ssh(1) will send a message through
                      the encrypted channel to request a response from the server. The
                      default is 0, indicating that these messages will not be sent to
                      the server. This option applies to protocol version 2 only.





                      share|improve this answer


























                      • Every 15 seconds seems pretty often to ping the server.

                        – Lambart
                        Feb 20 '14 at 0:08











                      • @Lambart but if the connection is really flaky and drops connections often, it at least detects a dead connection and gives the opportunity to retry earlier.

                        – binki
                        Dec 13 '14 at 2:00
















                      6














                      I solved this problem with this:



                      Edit



                      ~/.ssh/config


                      And add



                      ServerAliveInterval 15
                      ServerAliveCountMax 4


                      According to man page for ssh_config:



                      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.

                      ServerAliveInterval
                      Sets a timeout interval in seconds after which if no data has
                      been received from the server, ssh(1) will send a message through
                      the encrypted channel to request a response from the server. The
                      default is 0, indicating that these messages will not be sent to
                      the server. This option applies to protocol version 2 only.





                      share|improve this answer


























                      • Every 15 seconds seems pretty often to ping the server.

                        – Lambart
                        Feb 20 '14 at 0:08











                      • @Lambart but if the connection is really flaky and drops connections often, it at least detects a dead connection and gives the opportunity to retry earlier.

                        – binki
                        Dec 13 '14 at 2:00














                      6












                      6








                      6







                      I solved this problem with this:



                      Edit



                      ~/.ssh/config


                      And add



                      ServerAliveInterval 15
                      ServerAliveCountMax 4


                      According to man page for ssh_config:



                      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.

                      ServerAliveInterval
                      Sets a timeout interval in seconds after which if no data has
                      been received from the server, ssh(1) will send a message through
                      the encrypted channel to request a response from the server. The
                      default is 0, indicating that these messages will not be sent to
                      the server. This option applies to protocol version 2 only.





                      share|improve this answer















                      I solved this problem with this:



                      Edit



                      ~/.ssh/config


                      And add



                      ServerAliveInterval 15
                      ServerAliveCountMax 4


                      According to man page for ssh_config:



                      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.

                      ServerAliveInterval
                      Sets a timeout interval in seconds after which if no data has
                      been received from the server, ssh(1) will send a message through
                      the encrypted channel to request a response from the server. The
                      default is 0, indicating that these messages will not be sent to
                      the server. This option applies to protocol version 2 only.






                      share|improve this answer














                      share|improve this answer



                      share|improve this answer








                      edited Nov 13 '15 at 19:39









                      kokbira

                      4,123113465




                      4,123113465










                      answered May 30 '13 at 13:32









                      nachopronachopro

                      16113




                      16113













                      • Every 15 seconds seems pretty often to ping the server.

                        – Lambart
                        Feb 20 '14 at 0:08











                      • @Lambart but if the connection is really flaky and drops connections often, it at least detects a dead connection and gives the opportunity to retry earlier.

                        – binki
                        Dec 13 '14 at 2:00



















                      • Every 15 seconds seems pretty often to ping the server.

                        – Lambart
                        Feb 20 '14 at 0:08











                      • @Lambart but if the connection is really flaky and drops connections often, it at least detects a dead connection and gives the opportunity to retry earlier.

                        – binki
                        Dec 13 '14 at 2:00

















                      Every 15 seconds seems pretty often to ping the server.

                      – Lambart
                      Feb 20 '14 at 0:08





                      Every 15 seconds seems pretty often to ping the server.

                      – Lambart
                      Feb 20 '14 at 0:08













                      @Lambart but if the connection is really flaky and drops connections often, it at least detects a dead connection and gives the opportunity to retry earlier.

                      – binki
                      Dec 13 '14 at 2:00





                      @Lambart but if the connection is really flaky and drops connections often, it at least detects a dead connection and gives the opportunity to retry earlier.

                      – binki
                      Dec 13 '14 at 2:00











                      3














                      ExitOnForwardFailure yes is a good adjunct to the other suggestions. If it connects but can't establish the port forwarding it's just as useless to you as if it hadn't connected at all.






                      share|improve this answer


























                      • This is a very good idea. Even autossh is useless if the previous connection is perceived as timed out earlier in the remote side than in the local host, since in this case the local host will try to connect again, but the forwarding cannot be established because the port is still open.

                        – Raúl Salinas-Monteagudo
                        May 24 '17 at 7:42
















                      3














                      ExitOnForwardFailure yes is a good adjunct to the other suggestions. If it connects but can't establish the port forwarding it's just as useless to you as if it hadn't connected at all.






                      share|improve this answer


























                      • This is a very good idea. Even autossh is useless if the previous connection is perceived as timed out earlier in the remote side than in the local host, since in this case the local host will try to connect again, but the forwarding cannot be established because the port is still open.

                        – Raúl Salinas-Monteagudo
                        May 24 '17 at 7:42














                      3












                      3








                      3







                      ExitOnForwardFailure yes is a good adjunct to the other suggestions. If it connects but can't establish the port forwarding it's just as useless to you as if it hadn't connected at all.






                      share|improve this answer















                      ExitOnForwardFailure yes is a good adjunct to the other suggestions. If it connects but can't establish the port forwarding it's just as useless to you as if it hadn't connected at all.







                      share|improve this answer














                      share|improve this answer



                      share|improve this answer








                      edited Jun 6 '15 at 23:52

























                      answered Jun 6 '15 at 23:41









                      jcomeau_ictxjcomeau_ictx

                      539612




                      539612













                      • This is a very good idea. Even autossh is useless if the previous connection is perceived as timed out earlier in the remote side than in the local host, since in this case the local host will try to connect again, but the forwarding cannot be established because the port is still open.

                        – Raúl Salinas-Monteagudo
                        May 24 '17 at 7:42



















                      • This is a very good idea. Even autossh is useless if the previous connection is perceived as timed out earlier in the remote side than in the local host, since in this case the local host will try to connect again, but the forwarding cannot be established because the port is still open.

                        – Raúl Salinas-Monteagudo
                        May 24 '17 at 7:42

















                      This is a very good idea. Even autossh is useless if the previous connection is perceived as timed out earlier in the remote side than in the local host, since in this case the local host will try to connect again, but the forwarding cannot be established because the port is still open.

                      – Raúl Salinas-Monteagudo
                      May 24 '17 at 7:42





                      This is a very good idea. Even autossh is useless if the previous connection is perceived as timed out earlier in the remote side than in the local host, since in this case the local host will try to connect again, but the forwarding cannot be established because the port is still open.

                      – Raúl Salinas-Monteagudo
                      May 24 '17 at 7:42











                      1














                      I've had a need to maintain an SSH-tunnel long-term. My solution was running from a Linux server, and it's just a small C program that respawns ssh using key-based authentication.



                      I'm not sure about the hanging, but I've had tunnels die due to timeouts.



                      I would love to provide the code for the respawner, but I can't seem to find it right now.






                      share|improve this answer




























                        1














                        I've had a need to maintain an SSH-tunnel long-term. My solution was running from a Linux server, and it's just a small C program that respawns ssh using key-based authentication.



                        I'm not sure about the hanging, but I've had tunnels die due to timeouts.



                        I would love to provide the code for the respawner, but I can't seem to find it right now.






                        share|improve this answer


























                          1












                          1








                          1







                          I've had a need to maintain an SSH-tunnel long-term. My solution was running from a Linux server, and it's just a small C program that respawns ssh using key-based authentication.



                          I'm not sure about the hanging, but I've had tunnels die due to timeouts.



                          I would love to provide the code for the respawner, but I can't seem to find it right now.






                          share|improve this answer













                          I've had a need to maintain an SSH-tunnel long-term. My solution was running from a Linux server, and it's just a small C program that respawns ssh using key-based authentication.



                          I'm not sure about the hanging, but I've had tunnels die due to timeouts.



                          I would love to provide the code for the respawner, but I can't seem to find it right now.







                          share|improve this answer












                          share|improve this answer



                          share|improve this answer










                          answered Sep 8 '09 at 13:17









                          baumgartbaumgart

                          1,156613




                          1,156613























                              1














                              while there are tools like autossh that helps to restart ssh session... what i find to be really useful is to run the 'screen' command. It allows you to RESUME your ssh sessions even after you disconnect. Especially useful if your connection is not as reliable as it should be.




                              • http://www.howtogeek.com/howto/ubuntu/keep-your-ssh-session-running-when-you-disconnect/


                              ...don't forget to mark this is the 'correct' answer if it helps you k! ;-)






                              share|improve this answer



















                              • 5





                                ... but the question was about how to keep SSH tunnels open, not just a terminal session. Screen IS great though!

                                – akent
                                Sep 8 '09 at 14:15











                              • I already use screen, but it doesn't solve my problem :-/ Thanks for your answer, though.

                                – Peltier
                                Sep 8 '09 at 14:15
















                              1














                              while there are tools like autossh that helps to restart ssh session... what i find to be really useful is to run the 'screen' command. It allows you to RESUME your ssh sessions even after you disconnect. Especially useful if your connection is not as reliable as it should be.




                              • http://www.howtogeek.com/howto/ubuntu/keep-your-ssh-session-running-when-you-disconnect/


                              ...don't forget to mark this is the 'correct' answer if it helps you k! ;-)






                              share|improve this answer



















                              • 5





                                ... but the question was about how to keep SSH tunnels open, not just a terminal session. Screen IS great though!

                                – akent
                                Sep 8 '09 at 14:15











                              • I already use screen, but it doesn't solve my problem :-/ Thanks for your answer, though.

                                – Peltier
                                Sep 8 '09 at 14:15














                              1












                              1








                              1







                              while there are tools like autossh that helps to restart ssh session... what i find to be really useful is to run the 'screen' command. It allows you to RESUME your ssh sessions even after you disconnect. Especially useful if your connection is not as reliable as it should be.




                              • http://www.howtogeek.com/howto/ubuntu/keep-your-ssh-session-running-when-you-disconnect/


                              ...don't forget to mark this is the 'correct' answer if it helps you k! ;-)






                              share|improve this answer













                              while there are tools like autossh that helps to restart ssh session... what i find to be really useful is to run the 'screen' command. It allows you to RESUME your ssh sessions even after you disconnect. Especially useful if your connection is not as reliable as it should be.




                              • http://www.howtogeek.com/howto/ubuntu/keep-your-ssh-session-running-when-you-disconnect/


                              ...don't forget to mark this is the 'correct' answer if it helps you k! ;-)







                              share|improve this answer












                              share|improve this answer



                              share|improve this answer










                              answered Sep 8 '09 at 14:09









                              kosskoss

                              16414




                              16414








                              • 5





                                ... but the question was about how to keep SSH tunnels open, not just a terminal session. Screen IS great though!

                                – akent
                                Sep 8 '09 at 14:15











                              • I already use screen, but it doesn't solve my problem :-/ Thanks for your answer, though.

                                – Peltier
                                Sep 8 '09 at 14:15














                              • 5





                                ... but the question was about how to keep SSH tunnels open, not just a terminal session. Screen IS great though!

                                – akent
                                Sep 8 '09 at 14:15











                              • I already use screen, but it doesn't solve my problem :-/ Thanks for your answer, though.

                                – Peltier
                                Sep 8 '09 at 14:15








                              5




                              5





                              ... but the question was about how to keep SSH tunnels open, not just a terminal session. Screen IS great though!

                              – akent
                              Sep 8 '09 at 14:15





                              ... but the question was about how to keep SSH tunnels open, not just a terminal session. Screen IS great though!

                              – akent
                              Sep 8 '09 at 14:15













                              I already use screen, but it doesn't solve my problem :-/ Thanks for your answer, though.

                              – Peltier
                              Sep 8 '09 at 14:15





                              I already use screen, but it doesn't solve my problem :-/ Thanks for your answer, though.

                              – Peltier
                              Sep 8 '09 at 14:15











                              1














                              A bit of a hack, but I like to use screen to keep this. I currently have a remote forward that has been running for weeks.



                              Example, starting locally:



                              screen
                              ssh -R ......


                              When the remote forward is applied, and you have a shell on the remote computer:



                              screen
                              Ctrl + a + d


                              You now have an uninterrupted remote forward. The trick is to run screen on both ends






                              share|improve this answer




























                                1














                                A bit of a hack, but I like to use screen to keep this. I currently have a remote forward that has been running for weeks.



                                Example, starting locally:



                                screen
                                ssh -R ......


                                When the remote forward is applied, and you have a shell on the remote computer:



                                screen
                                Ctrl + a + d


                                You now have an uninterrupted remote forward. The trick is to run screen on both ends






                                share|improve this answer


























                                  1












                                  1








                                  1







                                  A bit of a hack, but I like to use screen to keep this. I currently have a remote forward that has been running for weeks.



                                  Example, starting locally:



                                  screen
                                  ssh -R ......


                                  When the remote forward is applied, and you have a shell on the remote computer:



                                  screen
                                  Ctrl + a + d


                                  You now have an uninterrupted remote forward. The trick is to run screen on both ends






                                  share|improve this answer













                                  A bit of a hack, but I like to use screen to keep this. I currently have a remote forward that has been running for weeks.



                                  Example, starting locally:



                                  screen
                                  ssh -R ......


                                  When the remote forward is applied, and you have a shell on the remote computer:



                                  screen
                                  Ctrl + a + d


                                  You now have an uninterrupted remote forward. The trick is to run screen on both ends







                                  share|improve this answer












                                  share|improve this answer



                                  share|improve this answer










                                  answered Mar 13 '12 at 12:11









                                  landyprolandypro

                                  211




                                  211























                                      1














                                      Recently had this issue myself, because these solutions require you to re-enter the password every time if you use a password login I used sshpass in a loop along with a text prompt to avoid having the password in the batch file.



                                      Thought I'd share my solution on this thead in case anyone else has the same issue:



                                      #!/bin/bash
                                      read -s -p "Password: " pass
                                      while true
                                      do
                                      sshpass -p "$pass" ssh user@address -p port
                                      sleep 1
                                      done





                                      share|improve this answer






























                                        1














                                        Recently had this issue myself, because these solutions require you to re-enter the password every time if you use a password login I used sshpass in a loop along with a text prompt to avoid having the password in the batch file.



                                        Thought I'd share my solution on this thead in case anyone else has the same issue:



                                        #!/bin/bash
                                        read -s -p "Password: " pass
                                        while true
                                        do
                                        sshpass -p "$pass" ssh user@address -p port
                                        sleep 1
                                        done





                                        share|improve this answer




























                                          1












                                          1








                                          1







                                          Recently had this issue myself, because these solutions require you to re-enter the password every time if you use a password login I used sshpass in a loop along with a text prompt to avoid having the password in the batch file.



                                          Thought I'd share my solution on this thead in case anyone else has the same issue:



                                          #!/bin/bash
                                          read -s -p "Password: " pass
                                          while true
                                          do
                                          sshpass -p "$pass" ssh user@address -p port
                                          sleep 1
                                          done





                                          share|improve this answer















                                          Recently had this issue myself, because these solutions require you to re-enter the password every time if you use a password login I used sshpass in a loop along with a text prompt to avoid having the password in the batch file.



                                          Thought I'd share my solution on this thead in case anyone else has the same issue:



                                          #!/bin/bash
                                          read -s -p "Password: " pass
                                          while true
                                          do
                                          sshpass -p "$pass" ssh user@address -p port
                                          sleep 1
                                          done






                                          share|improve this answer














                                          share|improve this answer



                                          share|improve this answer








                                          edited Jul 30 '15 at 14:24

























                                          answered Jul 30 '15 at 14:02









                                          BrainfloatBrainfloat

                                          1112




                                          1112























                                              0














                                              I have had similar problems with my previous ISP.
                                              For me it was the same with any tcp connection, visiting websites or sending mail.



                                              The solution was to configure a VPN connection over UDP(I was using OpenVPN). This connection was more tolerant to whatever caused the disconnections. Then you can run any service through this connection.



                                              There can still be issues with the connection but since the tunnel will be more tolerant any ssh session will feel a short holdup rather than being disconnected.



                                              To do this you will need a VPN service online which you can setup on your own server.






                                              share|improve this answer




























                                                0














                                                I have had similar problems with my previous ISP.
                                                For me it was the same with any tcp connection, visiting websites or sending mail.



                                                The solution was to configure a VPN connection over UDP(I was using OpenVPN). This connection was more tolerant to whatever caused the disconnections. Then you can run any service through this connection.



                                                There can still be issues with the connection but since the tunnel will be more tolerant any ssh session will feel a short holdup rather than being disconnected.



                                                To do this you will need a VPN service online which you can setup on your own server.






                                                share|improve this answer


























                                                  0












                                                  0








                                                  0







                                                  I have had similar problems with my previous ISP.
                                                  For me it was the same with any tcp connection, visiting websites or sending mail.



                                                  The solution was to configure a VPN connection over UDP(I was using OpenVPN). This connection was more tolerant to whatever caused the disconnections. Then you can run any service through this connection.



                                                  There can still be issues with the connection but since the tunnel will be more tolerant any ssh session will feel a short holdup rather than being disconnected.



                                                  To do this you will need a VPN service online which you can setup on your own server.






                                                  share|improve this answer













                                                  I have had similar problems with my previous ISP.
                                                  For me it was the same with any tcp connection, visiting websites or sending mail.



                                                  The solution was to configure a VPN connection over UDP(I was using OpenVPN). This connection was more tolerant to whatever caused the disconnections. Then you can run any service through this connection.



                                                  There can still be issues with the connection but since the tunnel will be more tolerant any ssh session will feel a short holdup rather than being disconnected.



                                                  To do this you will need a VPN service online which you can setup on your own server.







                                                  share|improve this answer












                                                  share|improve this answer



                                                  share|improve this answer










                                                  answered Sep 28 '09 at 10:27









                                                  hultqvisthultqvist

                                                  267210




                                                  267210























                                                      0














                                                      As autossh does not meet our needs (it exists with error if it can't connect to the server at the very first attempt), we've written a pure bash application: https://github.com/aktos-io/link-with-server



                                                      It creates a reverse tunnel for the NODE's sshd port (22) on the server by default. If you need to perform any other actions (like forwarding additional ports, sending mails on connection, etc...) you can place your scripts on-connect and on-disconnect folders.






                                                      share|improve this answer




























                                                        0














                                                        As autossh does not meet our needs (it exists with error if it can't connect to the server at the very first attempt), we've written a pure bash application: https://github.com/aktos-io/link-with-server



                                                        It creates a reverse tunnel for the NODE's sshd port (22) on the server by default. If you need to perform any other actions (like forwarding additional ports, sending mails on connection, etc...) you can place your scripts on-connect and on-disconnect folders.






                                                        share|improve this answer


























                                                          0












                                                          0








                                                          0







                                                          As autossh does not meet our needs (it exists with error if it can't connect to the server at the very first attempt), we've written a pure bash application: https://github.com/aktos-io/link-with-server



                                                          It creates a reverse tunnel for the NODE's sshd port (22) on the server by default. If you need to perform any other actions (like forwarding additional ports, sending mails on connection, etc...) you can place your scripts on-connect and on-disconnect folders.






                                                          share|improve this answer













                                                          As autossh does not meet our needs (it exists with error if it can't connect to the server at the very first attempt), we've written a pure bash application: https://github.com/aktos-io/link-with-server



                                                          It creates a reverse tunnel for the NODE's sshd port (22) on the server by default. If you need to perform any other actions (like forwarding additional ports, sending mails on connection, etc...) you can place your scripts on-connect and on-disconnect folders.







                                                          share|improve this answer












                                                          share|improve this answer



                                                          share|improve this answer










                                                          answered Jul 15 '17 at 0:04









                                                          ceremcemceremcem

                                                          206314




                                                          206314






























                                                              draft saved

                                                              draft discarded




















































                                                              Thanks for contributing an answer to Super User!


                                                              • Please be sure to answer the question. Provide details and share your research!

                                                              But avoid



                                                              • Asking for help, clarification, or responding to other answers.

                                                              • Making statements based on opinion; back them up with references or personal experience.


                                                              To learn more, see our tips on writing great answers.




                                                              draft saved


                                                              draft discarded














                                                              StackExchange.ready(
                                                              function () {
                                                              StackExchange.openid.initPostLogin('.new-post-login', 'https%3a%2f%2fsuperuser.com%2fquestions%2f37738%2fhow-to-reliably-keep-an-ssh-tunnel-open%23new-answer', 'question_page');
                                                              }
                                                              );

                                                              Post as a guest















                                                              Required, but never shown





















































                                                              Required, but never shown














                                                              Required, but never shown












                                                              Required, but never shown







                                                              Required, but never shown

































                                                              Required, but never shown














                                                              Required, but never shown












                                                              Required, but never shown







                                                              Required, but never shown







                                                              Popular posts from this blog

                                                              How to reconfigure Docker Trusted Registry 2.x.x to use CEPH FS mount instead of NFS and other traditional...

                                                              is 'sed' thread safe

                                                              How to make a Squid Proxy server?