0.说明
前面讲了怎么使用ssh来为公司搭建代理服务器,好方便的连接各地服务器。但是使用中发现经常会因为网络等原因导致连接断开,影响我们正常使用。
网上查资料,发现可以使用autossh来解决这个问题:autossh是一个程序,用于启动ssh的副本并监视它,如果ssh死掉或则停止传输流量,那么autossh会根据需要重新启动它。因为在centos7中默认没有安装,这里我们记录下centos7下怎么安装及简单使用autossh。
本次测试中系统为:CentOS 7.4 X64
1、安装autossh
1 2 3 4 5 6 7 |
[root@imzcy ~]# ll autossh* -rw-r--r--. 1 root root 24270 7月 20 2018 autossh-1.4b-4.1.mga1.x86_64.rpm [root@imzcy ~]# rpm -ivh autossh-1.4b-4.1.mga1.x86_64.rpm [root@imzcy ~]# autossh -V autossh 1.4b [root@localhost ~]# |
autossh安装包下载地址: 密码: 1jf7
2、autossh的使用
1 2 3 4 |
基本语法和ssh一样,只是命令改为autossh,然后加了一个-M选项指定监测端口即可。拿之前配置ssh代理的命令举例: ssh -CNfnqg -D 3333 -p 8848 zcy@8.8.8.8 修改为: autossh -M 68848 -CNnqg -D 3333 -p 8848 zcy@8.8.8.8 |
3、使用expect脚本为autossh重连时自动输入密码
autossh断开自动重连时有一个问题,,就有时候需要手动输入密码,不然连接就一直断掉了。下面就使用expect脚本为autossh自动输入密码
1 2 3 4 5 6 7 8 9 10 11 |
[root@imzcy script]# cat test.sh #!/usr/bin/expect set timeout 10000000 spawn autossh -M 66666 -CNfnqg -D 4444 -p 2222 root@127.0.0.1 expect { "root@127.0.0.1's password:*" { send "123456\r"; exp_continue } } [root@imzcy script]# |
expect脚本详细说明见下篇文章:点击跳转