您的位置:首页 > 其它

自动化配置ssh连接

2016-06-14 21:46 162 查看

自动化配置ssh连接

在从主机使用ssh连接其他的主机时往往要求一些不同的响应信息。

例如第一次访问时:

#ssh root@localhost
The authenticity of host 'localhost (::1)' can't be established.
ECDSA key fingerprint is 03:cc:13:fe:6c:85:0a:af:df:67:de:18:19:ae:d8:1f.
Are you sure you want to continue connecting (yes/no)?


在你输入
yes
下一步你将发现下如下的输出:

root@localhost's password:


此时要求你输入root的密码。在你输入正确的密码后,你就可以看到如下输出:

Last login: Tue Jun 14 20:45:07 2016 from 192.168.12.1
[root@LINUXTEST ~]#


我们如果希望实现ssh的自动化操作,并且在远程主机上执行某一个操作,例如:

root@LINUXTEST .ssh]# ssh root@localhost hostname
The authenticity of host 'localhost (::1)' can't be established.
ECDSA key fingerprint is 03:cc:13:fe:6c:85:0a:af:df:67:de:18:19:ae:d8:1f.
Are you sure you want to continue connecting (yes/no)? yes
Warning: Permanently added 'localhost' (ECDSA) to the list of known hosts.
root@localhost's password:LINUXTEST


在这个过程中,你需要输入
yes
,
password
这两个值。

在这里只靠
shell
自身是无法完成,需要一个
expect
的工具来帮助我们。

安装
expect


#yum install expect -y

Installed:
expect.x86_64 0:5.45-14.el7_1

Dependency Installed:
tcl.x86_64 1:8.5.13-8.el7

Complete!


创建如下脚本
autossh.sh


# vi autossh.sh
#!/usr/bin/expect
set ipaddr "localhost"
set password "root1234"

spawn ssh root@$ipaddr
expect {
"yes/no" { send "yes\r";exp_continue }
"password:" { send "\r" }
}
expect "]#"
send "pwd;hostname \r"
expect eof
exit
# chmod u+x autossh.sh


执行这个脚本,得到如下输出

# ./autossh.sh
spawn ssh root@localhost
The authenticity of host 'localhost (::1)' can't be established.
ECDSA key fingerprint is 03:cc:13:fe:6c:85:0a:af:df:67:de:18:19:ae:d8:1f.
Are you sure you want to continue connecting (yes/no)? yes
Warning: Permanently added 'localhost' (ECDSA) to the list of known hosts.
root@localhost's password:Last login: Tue Jun 14 20:56:38 2016 from 192.168.12.1
[root@LINUXTEST ~]# pwd;hostname
/root
LINUXTEST


接下来我们只需要创建一个包含所有主机的用户名与密码的文件
h-u-p.txt
,里面包含如下的内容

#vi h-u-p.txt
hostname1:username1:password1
hostname2:username2:password2
hostname4:username3:password3
hostname4:username4:password4
.......


编写另外一个脚本
batchssh.sh
来处理这些参数并且调用
autossh.sh


#vi batchssh.sh
#!/usr/bin/bash

for line in $(cat h-u-p.txt)
do
arr=(${line//:/ })
./autossh.sh ${arr[0]} ${arr[1]} ${arr[2]}
done


修改
autossh.sh


#>autossh.sh
#vi autossh.sh
#!/usr/bin/expect
set ipaddr [lindex $argv 0]
set username [lindex $argv 1]
set password [lindex $argv 2]

spawn ssh $username@$ipaddr
expect {
"yes/no" { send "yes\r";exp_continue }
"password:" { send "$password\r" }
}
expect "]#"
send "pwd;hostname;exit \r"
expect eof
exit


那么现在就可以编辑文件
h-u-p.txt
来批量执行ssh连接了。文件列表如下:

autossh.sh  batchssh.sh  h-u-p.txt
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签:  自动化 ssh