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.



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;

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

  • perl have Net::SSH2, when you set Timeout – alvosu Feb 7 '11 at 17:59

I had the same issue and used the Linux "timeout" to kill a hanging scp session.

timeout -s 9 1h command command_arguments

Will send a kill -9 if the command takes over an hour.

FYI the ConnectTimeout option did not work for me.

  • This is the most thorough option. -o ConnectTimeout=x and -o BatchMode=yes will both help, but nothing beats timeout for covering 100% of cases, even ssh client code failure! Though you really shouldn't kill -9 here; there's no need for the -9. – BMDan Sep 19 '15 at 0:26

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


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.

  • 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

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

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