解决ssh登录后闲置时间过长而断开连接

 ++++++++++++++++++++++++++++

#!/usr/bin/env bash

password_5="Uxxx7"
host_5="129.x.x.176"

token=$1


echo "输入对应编号回车!"
select server in $host_1 $host_2 $host_3 $host_4 $host_5
do
break
done

case $server in
$host_1)
password=$password_1
uName=root
;;
$host_2)
password=$password_2
uName=root
;;

esac

expect -c "

set timeout -1
spawn ssh $uName@$server
set timeout 3000
expect -re "/*password/*" {send "$password "}

interact
"

+++++++++++++++++++++++++++++

在 ~/.ssh/config 中加入以下内容,如果没有这个文件就touch一个,权限需要600才可以生效

Host *
    ControlPersist yes
    ControlMaster auto
    ControlPath ~/.ssh/master-%r@%h:%p
    Compression yes
 
 

时我们通过终端连接服务器时,当鼠标和键盘长时间不操作,服务器就会自动断开连接,我们还的需要重新连接,感觉很麻烦,总结一下解决此问题的方法
方法一、
修改/etc/ssh/sshd_config配置文件,找到ClientAliveCountMax(单位为分钟)修改你想要的值,
执行service sshd reload 
方法二、
找到所在用户的.ssh目录,如root用户该目录在:
/root/.ssh/
在该目录创建config文件
vi /root/.ssh/config
加入下面一句:
ServerAliveInterval 60
保存退出,重新开启root用户的shell,则再ssh远程服务器的时候,
不会因为长时间操作断开。应该是加入这句之后,ssh客户端会每隔一
段时间自动与ssh服务器通信一次,所以长时间操作不会断开。
方法三、
修改/etc/profile配置文件
# vi /etc/profile
增加:TMOUT=1800
这样30分钟没操作就自动LOGOUT
方法四、
利用expect 模拟键盘动作,在闲置时间之内模拟地给个键盘响应,将下列代码保存为xxx,然后用expect执行
#!/usr/bin/expect  
set timeout 60  
spawn ssh user@host   
      interact {          
            timeout 300 {send "x20"}  
      } 
expect xxx
接着按提示输入密码就可以了,这样每隔300秒就会自动打一个空格(x20),具体的时间间隔可以根据具体情况设置。
方法五、
如果你在windows下通过工具连接,可以设置为
secureCRT:选项---终端---反空闲 中设置每隔多少秒发送一个字符串,或者是NO-OP协议包
putty:putty -> Connection -> Seconds between keepalives ( 0 to turn off ), 默认为0, 改为300.

原文地址:https://www.cnblogs.com/SZLLQ2000/p/5749547.html