SSH connect timeout for reaching interactive session

in flag

When connecting to a misbehaving SSH server, is there a flag or config setting I can use to tell the client to give up earlier if an interactive console isn't reached in a short period of time?

I am aware of -o ConnectTimeout which will abort the connection when the host is unreachable. In this case, the host is reachable and the initial connection occurs quickly ("Server accepts key" in less than 1s) but then a breakdown in some layer of PAM means I may get an actual command prompt in 3 seconds, 12 seconds, or never. The connection stalls until I send Ctrl+C or wait 90 seconds for "Connection to [host] port 22 timed out"

Until the underlying cause is fixed (which I am not looking to solve with this question), is there anything I can do to mitigate the symptom? I want to automatically disconnect if we don't land at a useful prompt in 5 seconds.

in flag

If the connection stalls before port forwarding is set up, we can leverage a socket as a semaphore and hack together our own watchdog:

set -m

function watchdog {
    sleep $1
    if [[ ! -S "/tmp/lfg.$2" ]]; then
        kill -STOP $3

ssh -L /tmp/lfg.$$:localhost:1234 $1 && rm -f /tmp/lfg.$$ &
watchdog $2 $$ $! &
fg %-


lfg grumpy-host 5

lfg first enables job control, then initiates ssh requesting local socket /tmp/lfg.nnn forwarded to an arbitrary remote port. Putting this job in the background, we ask the watchdog function to wait 5 seconds then look for the socket. If it's not there, kill the stalled ssh process. fg %- puts ssh back in the foreground so as soon as it's interactive, we're in; if that takes longer than 5 seconds we're back at our local prompt.

in flag

If the underlying connection is stable and our main goal is to open multiple sessions without playing PAM roulette, "master" mode may help:

ssh -M -S /tmp/reusable.sock user@host

Once you win the Ctrl+C/90-second timeout fight the first time, other terminals may be opened rapidly with:

ssh -S /tmp/reusable.sock user@host

This works as long as the original connection is held open. Reduction in connection time assumes the problem is in the authentication step (since multiplexing the socket like this bypasses re-auth)


Post an answer

Most people don’t grasp that asking a lot of questions unlocks learning and improves interpersonal bonding. In Alison’s studies, for example, though people could accurately recall how many questions had been asked in their conversations, they didn’t intuit the link between questions and liking. Across four studies, in which participants were engaged in conversations themselves or read transcripts of others’ conversations, people tended not to realize that question asking would influence—or had influenced—the level of amity between the conversationalists.