需要长时间ssh到服务器,为防止长时间没有请求而被服务器自动断开,可以在~/.ssh/config中加入下面的配置:
1 2 |
Host * ServerAliveInterval 60 |
其作用是当ssh链接闲置60秒的时候,客户端会自动发送一条keepalive的请求,避免服务器端自动断开。
但是如果发生意外导致链接中断怎么办?以前是用shell脚本自动监控,一旦发现链接断掉,就自动重新链接:
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 |
function make_proxy() { PROXY_ID=$(pgrep -f "ssh -D port user@host") if [[ $PROXY_ID != 0 ]];then ssh -D port user@host ; fi } function test_proxy() { curl -s -I --socks5 localhost:7972 http://www.yahoo.com/ > /dev/null; } SHORT=5 LONG=300 count=0 while true; do test_proxy; if [[ $? != 0 ]];then make_proxy; duration=$SHORT; ((count++)); else count=0; duration=$LONG; fi if [[ $count == 5 ]];then notify-send -t 3000 -u critical "Proxy Failed" "Couldn't connect to proxy"; exit -1; fi sleep $duration; don |
这个脚本就是每300秒通过ssh tunnel链接一下yahoo,测试是否成功,如果不成功就认为ssh链接已经断开,会自动尝试ssh链接5次,如果全部失败,就发送信息。
现在有了一个更简单的方法,就是使用autossh。autossh使用起来非常简单,它只有两个参数:
-
-M
- 设置监控的端口。 -t
- 设置autossh后台运行,需要注意的是如果使用此参数的话,ssh就无法请求输入password或者passphase了,不过一般情况大家都会使用ssh-agent。
使用autossh就可以大大简化上面的脚本:
1 2 3 |
export AUTOSSH_DEBUG=DEBUG export AUTOSSH_LOGFILE=~/.autohssh.log autossh -M 9000 -f -q -D port user@host |
这里 -q 和 -D 都是ssh的参数,autossh 可以使用ssh的任何参数(好像除了-f)。
Autossh也接受环境变量的设置,像上面的AUTOSSH_DEBUG设置了log级别为debug,AUTOSSH_LOGFILE设置日志文件位置。更多的环境变量的解释可以参考readme。
转载地址:http://yuanmuqiuyu2000.i.sohu.com/blog/view/230879798.htm
本文介绍如何使用Autossh替代复杂脚本来管理SSH连接,实现自动重连及保持连接状态,简化了SSH连接的维护过程。
1025

被折叠的 条评论
为什么被折叠?



