Automatically reconnect to ssh after suspend

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?

Answers:

Thank you for visiting the Q&A section on Magenaut. Please note that all the answers may not help you solve the issue immediately. So please treat them as advisements. If you found the post helpful (or not), leave a comment & I’ll get back to you as soon as possible.

Method 1

I used to have a “reverse ssh” script like

laddr=*:0
<a href="https://getridbug.com/cdn-cgi/l/email-protection" class="__cf_email__" data-cfemail="660e0915125b15090b0339131503142615090b03480e0915124805090b">[email protected]</a>
port=some_port

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)))"
done

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.


All methods was sourced from stackoverflow.com or stackexchange.com, is licensed under cc by-sa 2.5, cc by-sa 3.0 and cc by-sa 4.0

0 0 votes
Article Rating
Subscribe
Notify of
guest

0 Comments
Oldest
Newest Most Voted
Inline Feedbacks
View all comments
0
Would love your thoughts, please comment.x
()
x