Reconnecting to SSH servers

In my work I'm often in situation where I want to restart remote server, and then immediately connect to it over ssh.

This can be done by repeating ssh HOST in shell, but it gets tedious.

I can also write a simple loop, like:

while true
    ssh HOST true &> /dev/null && break
    echo -n .
    sleep 1
ssh HOST

But it always hides errors, and is not really elegant.

So, I wrote a simple tool that wraps this, and some additional logic: ressh.

It's usage is very simple:

=$ ressh -t 1 -i 12
2021-01-06 11:59:55 : Trying to connect to, with timeout: 1, initial: 12, sleep: 1 : ..........
2021-01-06 12:00:14 : (+10) ..
2021-01-06 12:00:19 : 12 tries passed, disabling hiding of errors.
2021-01-06 12:00:19 : #13 : Connection timed out during banner exchange
2021-01-06 12:00:21 : #14 : Connection timed out during banner exchange
2021-01-06 12:00:23 : #15 : Connection timed out during banner exchange
2021-01-06 12:00:34 : Successfully logged in, after 39 seconds.
Last login: Wed Jan  6 11:22:28 2021 from
12:00:34 depesz@test ~

There are options to configure how long to wait for each ssh try (-t), how many times to try while hiding errors (-i), and how long to sleep between tries (-s):

=$ ./ressh -h
    ./ressh [-t TIMEOUT] [-i INITIAL] [-s SLEEP] [-h] HOSTNAME
    -t - how many seconds to wait to connect, default: 5
    -i - after how many tries start showing errors, default: 30
    -i - how many seconds to sleep between tries, default: 1
    -h - show this help page
    ./ressh will try to connect to given HOSTNAME, retrying every couple of
    seconds, until it will succeed.

Hope you'll find it useful.

One thought on “Reconnecting to SSH servers”

  1. Nice. I love how you think. You have solved a problem I didn’t even realize I had. I normally just use the “grin and bear it” method.

Comments are closed.