Auto-reconnecting SSH connections with a specific 'screen' session

10

6

I typically have several terminal windows each of which is connected via ssh to a remote server. In each window I work using the gnu screen program, to ensure persistence of the interactive processes in case of a disconnection.

Currently, whenever the ssh connection drops (such as when I put my client computer to sleep overnight) I have to manually and tediously restart the ssh session inside each window, and then in each window tediously resume the specific screen session (e.g. "screen -r 3453" in one window, "screen -r 3462" in the other etc.)

Is there an elegant way to automate this? Specifically:

  • reconnect the ssh session if it drops, as soon as an Internet connection is detected

  • run the specific screen instance for the terminal window as soon as ssh reconnects

Thanks for any tips on this

GJ.

Posted 2010-09-13T23:16:57.263

Reputation: 8 151

Answers

10

You can run this: ssh -t hostname screen -r 3453 to reconnect. If you want to do it in a loop I use the following in a script.

while true; do
    ssh -t -o BatchMode=yes eeepc-rsi "screen -r 3453"
    sleep 2
done

This works best if you have ssh-keys setup so you can login without typing in your password. I'd also recommend that you look at tmux, a more modern implementation of screen. I actually use the above script with screen. You probably also want to use a named screen session rather than just using the pid like you do in your example.

Jason Axelson

Posted 2010-09-13T23:16:57.263

Reputation: 1 390

Thanks! What exactly is the "-o BatchMode=yes" for? – GJ. – 2010-09-15T11:17:12.887

It will allow you to not prompt for the password. From 'man ssh_config': "passphrase/password querying will be disabled. This option is useful in scripts and other batch jobs where no user is present to supply the password." So only use it if you have ssh-keys already setup. – Jason Axelson – 2010-09-20T03:11:42.163

5

No need to hack bash loops. You need to look into autossh. I haven't used it much myself, but my understanding is that you simply replace ssh with autossh in your command.

Edit: In fact, autossh comes with a script called rscreen which appears to be designed for exactly this purpose.

Ryan C. Thompson

Posted 2010-09-13T23:16:57.263

Reputation: 10 085