我正在远程主机上执行一个通过无密码SSH连接的脚本。我想设置一个超时,这样如果远程主机运行的时间是无限长的,我就想退出ssh会话,继续sh脚本中的其他行。

如何设置超时?


当前回答

使用-o ConnectTimeout和-o BatchMode=yes -o StrictHostKeyChecking=no。

ConnectTimeout使脚本不挂起,BatchMode使脚本不挂起Host unknown, YES添加到known_hosts, StrictHostKeyChecking自动添加指纹。

**** NOTE **** The "StrictHostKeyChecking" was only intended for internal networks where you trust you hosts. Depending on the version of the SSH client, the "Are you sure you want to add your fingerprint" can cause the client to hang indefinitely (mainly old versions running on AIX). Most modern versions do not suffer from this issue. If you have to deal with fingerprints with multiple hosts, I recommend maintaining the known_hosts file with some sort of configuration management tool like puppet/ansible/chef/salt/etc.

其他回答

你也可以用flag -o ServerAliveInterval=<secs>来连接 因此SSH客户端将每<secs>秒向服务器发送一个空包,只是为了保持连接存活。 在Linux中,也可以在/etc/ssh/ssh_config中全局设置,或在~/.ssh/config中每个用户设置。

使用-o ConnectTimeout和-o BatchMode=yes -o StrictHostKeyChecking=no。

ConnectTimeout使脚本不挂起,BatchMode使脚本不挂起Host unknown, YES添加到known_hosts, StrictHostKeyChecking自动添加指纹。

**** NOTE **** The "StrictHostKeyChecking" was only intended for internal networks where you trust you hosts. Depending on the version of the SSH client, the "Are you sure you want to add your fingerprint" can cause the client to hang indefinitely (mainly old versions running on AIX). Most modern versions do not suffer from this issue. If you have to deal with fingerprints with multiple hosts, I recommend maintaining the known_hosts file with some sort of configuration management tool like puppet/ansible/chef/salt/etc.

如果所有这些都失败了(包括没有timeout命令),这个shell脚本中的概念将工作:

 #!/bin/bash
 set -u
 ssh $1 "sleep 10 ; uptime" > /tmp/outputfile 2>&1 & PIDssh=$!
 Count=0
 while test $Count -lt 5 && ps -p $PIDssh > /dev/null
 do
    echo -n .
    sleep 1
    Count=$((Count+1))
 done
 echo ""

 if ps -p $PIDssh > /dev/null
 then
    echo "ssh still running, killing it"
    kill -HUP $PIDssh
 else
    echo "Exited"
 fi

"timeout 5 SSH user@machine"对我来说很好。

试试这个:

timeout 5 ssh user@ip

timeout执行ssh命令(带args),如果ssh在5秒后没有返回,则发送一个SIGTERM。 有关超时的详细信息,请阅读本文档: http://man7.org/linux/man-pages/man1/timeout.1.html

或者你可以使用ssh的参数:

ssh -o ConnectTimeout=3 user@ip