Take the 2-minute tour ×
Server Fault is a question and answer site for system and network administrators. It's 100% free, no registration required.

Sometimes my ssh client will take forever to login.

This happens when the server is not responding (overloaded, killed processed, ...). My automated scripts will then fail because the ssh process will never exit.

Is there a ssh configuration value to set a timeout in order to fail if ssh can't login after a predefined number of seconds?

I know there are knobs on the server side, but I have to set this on the client side as the sshd process is not responding, or responding incorrectly.

Thanks!

share|improve this question

2 Answers 2

I've seen cases where even setting ConnectTimeout doesn't work. This can be particularly annoying when using automated ssh connections to large numbers of servers. My solution is to use a wrapper on the client side that kills the ssh process if it doesn't connect and return quickly enough. Something like this (in perl):

$SshCmd = "ssh server.example.com uname -a";
$TimeOut = 120;
eval {
  local $SIG{ALRM} =
    sub {
      # ignore SIGHUP here so the kill only affects children.
  local $SIG{HUP} = 'IGNORE';
  kill 1,(-$$);
  print STDERR "ssh terminated, max run time of $TimeOut seconds exceeded.\n";
    };
  alarm $TimeOut;
  system ($SshCmd) || die "failed to run $SshCmd: $!";
  alarm 0;
};
$SIG{HUP} = 'DEFAULT';

That sets an alarm of $TimeOut seconds, and kills the child (the ssh command) if the alarm is exceeded.

share|improve this answer
    
perl have Net::SSH2, when you set Timeout –  alvosu Feb 7 '11 at 17:59

Set 'ConnectTimeout' in .ssh/config if use ssh(from OpenSSH).

ConnectTimeout

Specifies the timeout (in seconds) used when connecting to the ssh server, instead of using he default system TCP timeout. This value is used only when the target is down or really unreachable, not when it refuses the connection.

Try set 'UseDNS no' in sshd_config.

share|improve this answer
    
I'll explain why he recommended this; if your IP has no PTR record it can cause SSH to hang. –  Jacob Jan 31 '11 at 17:11
    
ConnectTimeout doesn't work, generally, after the connection has been established. When I do that in one case, for example, it waits for the authentication to complete, which can be an indefinite period of time. –  danorton Aug 18 '11 at 15:22

Your Answer

 
discard

By posting your answer, you agree to the privacy policy and terms of service.

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