Expect安装
[root@web02 scripts]# yum install expect
SSH密钥生成
[root@web02 scripts]# ssh-keygen -t dsa <==生成密钥
Generating public/private dsa key pair.
Enter file in which to save the key (/root/.ssh/id_dsa):
Enter passphrase (empty for no passphrase):
Enter same passphrase again:
Your identification has been saved in /root/.ssh/id_dsa.
Your public key has been saved in /root/.ssh/id_dsa.pub.
The key fingerprint is:
d8:a6:e4:1f:8a:9a:25:f9:39:6c:74:1e:69:78:78:11 root@web02
The key's randomart image is:
+--[ DSA 1024]----+
| |
| E |
| . |
| .o |
| oooS |
| .+oBo |
| oo.*o.. |
| =+o.o . |
| oo+.. . |
+-----------------+
密钥分发
[root@web02 scripts]# vi ssh_handout.expect <==脚本编写
#!/usr/bin/expect -f
set ip [lindex $argv 0 ] <==接受第一个参数,赋值ip
set password 118530 <==被分发主机密码
set timeout 10
cd ~
spawn ssh-copy-id -i .ssh/id_dsa.pub root@$ip <==发送 .ssh/authorized_keys到目标主机
expect {
"*yes/no" { send "yes\r"; exp_continue} <==遇见“YES/NO” 发送命令“YES”
"*password:" { send "$password\r" } <==遇见“password” 发送命令“密码”
}
expect "#*"
#send "pwd\r"
#send "exit\r"
expect eof
~
~
~
~
~
~
~
~
~
"ssh_handout.expect" 15L, 305C written
[root@web02 scripts]# ./ssh_handout.expect 192.168.162.130 <==测试
spawn ssh-copy-id -i .ssh/id_dsa.pub root@192.168.162.130
root@192.168.162.130's password:
Now try logging into the machine, with "ssh 'root@192.168.162.130'", and check in:
.ssh/authorized_keys <==表示正确
to make sure we haven't added extra keys that you weren't expecting.
expect: spawn id exp4 not open
while executing
"expect eof "
(file "./ssh_handout.expect" line 14)
[root@web02 ~]# ssh root@192.168.162.130 <==免密码登陆
Last login: Thu Jul 21 19:59:12 2016 from 192.168.162.131
[root@web01 ~]# logout
Connection to 192.168.162.130 closed.
[root@web02 ~]# scp data/a.txt root@192.168.162.130:/tmp/ <==免密码传送文件
a.txt 100% 13 0.0KB/s 00:00
[root@web02 ~]# ssh root@192.168.162.130
Last login: Thu Jul 21 20:01:20 2016 from 192.168.162.131
[root@web01 ~]# ls /tmp/
a.txt yum.log
[root@web01 ~]# logout
Connection to 192.168.162.130 closed.
[root@web02 ~]#
[root@web02 scripts]# vi handout.sh <==分发到多个主机脚本
#aim:handout ssh to host
#!/bin/bash
#aim:handout ssh to host
#author:changyaoguo
#date:2016/07/21
. /etc/init.d/functions
for n in 128 129 130 132 133 <==每个主机的部分主机号
do
/server/scripts/ssh_handout.expect 192.168.162.$n >/dev/null 2>&1
action "ssh 192.168.162.$n" /bin/true
done
~
~
~
~
"handout.sh" [New] 10L, 245C written
[root@web02 scripts]# sh handout.sh <==测试
ssh 192.168.162.128 [ OK ]
ssh 192.168.162.129 [ OK ]
ssh 192.168.162.130 [ OK ]
ssh 192.168.162.132 [ OK ]
ssh 192.168.162.133 [ OK ]
希望点个赞!!!!