I'm using ssh as a SOCKS5 proxy, connecting to my personal server. When my system is suspended or I lose internet connection, the ssh will eventually time out, forcing me to manually reconnect. How can I configure my system to automatically reconnect as soon as an internet connection is established?

  • Did you happen to try any solutions yet that didn't happen to work? – cutrightjm Mar 8 '20 at 3:29
  • I wrote a bash script for the ssh however right now I am manually executing it. I'm unsure about how I would get this script to run automatically when an internet connection is established. – prophet Mar 8 '20 at 3:32
  • you mean while ping -c 1 remotehost; do ssh remoteuser@remotehost; done does not work? – Jetchisel Mar 8 '20 at 5:45
  • Check out autossh ... – 0xC0000022L Mar 8 '20 at 10:04

I used to have a "reverse ssh" script like


while :; do
    t0=$(date +%s)

    ssh -R "$laddr:localhost:22" \
       -o BatchMode=yes \
       -o CheckHostIP=no \
       -o ExitOnForwardFailure=yes \
       -o ServerAliveInterval=15 \
       -o ConnectTimeout=15 \
       -p "$port" "$host"

    t1=$(date +%s)
    sleep "$((60 / (t1 - t0 + 1)))"

which was supposed to try to connect immediately after the connection was lost, but wait a minute if ssh was terminating immediately, in order not to hammer the server or run a wild loop.

But I have long time ago replaced it with something better -- "service"-like.

Systemd & co are probably offering similar features.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.