liang10.0.0.129(秘钥服务端)
haproxy 10.0.0.130
nginx 10.0.0.131
mysql 10.0.0.132
4.2.2在服务端生成秘钥
[root@liang ~]# ssh-keygen(打完这条命令,一直按回车)
Generating public/private rsa key pair.
Enter file in which to save the key (/root/.ssh/id_rsa):
Enter passphrase (empty for no passphrase):
Enter same passphrase again:
Your identification has been saved in /root/.ssh/id_rsa.
Your publickey has been saved in /root/.ssh/id_rsa.pub.
The key fingerprint is:
ca:3d:85:7f:21:88:56:31:51:6c:1d:65:87:86:d4:e8 root@rsync-A
The key's randomart image is:
+--[ RSA 2048]----+
| ++.oo*o..|
| oo +.+. |
| .. . . |
| o o E |
| o S o . |
| o o o . . |
| o o . . |
| . . |
| |
+-----------------+
4.2.3编写shell嵌套expect脚本进行免秘钥操作
[root@liang 2018-07-30]# cat ssh.sh #!/bin/bash #shell脚本解释器
password=000000#设置变量,我这里所有虚拟机的密码都为000000
for ip in `seq 130132` #循环主机
do
expect -c " #调用expect命令
spawn ssh-copy-id -i /root/.ssh/id_rsa.pub 10.0.0.$ip #发送公钥的虚拟机
expect {
\"yes/no\" { send \"yes\r\";exp_continue }#这里的写法跟前面一样,\"\"(只是所有双引号的前面都需要加个\转义符号)
\"password\" { send \"${password}\r\"}
};#结尾需要加分号
expect eof #结束进程"
done
4.2.4执行脚本
[root@liang 2018-07-30]# bash ssh.sh
spawn ssh-copy-id -i /root/.ssh/id_rsa.pub 10.0.0.130
root@10.0.0.130's password:
Now try logging intothe machine, with"ssh '10.0.0.130'", and check in:
.ssh/authorized_keys
to make sure we haven't added extra keys that you weren't expecting.
spawn ssh-copy-id -i /root/.ssh/id_rsa.pub 10.0.0.131
root@10.0.0.131's password:
Now try logging intothe machine, with"ssh '10.0.0.131'", and check in:
.ssh/authorized_keys
to make sure we haven't added extra keys that you weren't expecting.
spawn ssh-copy-id -i /root/.ssh/id_rsa.pub 10.0.0.132
root@10.0.0.132's password:
Now try logging intothe machine, with"ssh '10.0.0.132'", and check in:
.ssh/authorized_keys
to make sure we haven't added extra keys that you weren't expecting.
4.2.5验证
[root@liang2018-07-30]# ssh 10.0.0.130Lastlogin:TueJul3101:08:522018 from 10.0.0.129
[root@haproxy ~]# exit
logout
Connection to 10.0.0.130 closed.
[root@liang2018-07-30]# ssh 10.0.0.131Lastlogin:TueJul3101:24:562018 from 10.0.0.129
[root@nginx ~]# exit
logout
Connection to 10.0.0.131 closed.
[root@liang2018-07-30]# ssh 10.0.0.132Lastlogin:MonJul3011:15:282018 from 10.0.0.1
[root@mysql ~]# exit
logout
Connection to 10.0.0.132 closed.
[root@liang 2018-07-30]# expect ssh_user.exp root@10.0.0.130 000000
spawn ssh-copy-id -i /root/.ssh/id_rsa.pub root@10.0.0.130
root@10.0.0.130's password:
Now try logging intothe machine, with"ssh 'root@10.0.0.130'", and check in:
.ssh/authorized_keys
to make sure we haven't added extra keys that you weren't expecting.
4.3.4测试
[root@liang2018-07-30]# ssh 10.0.0.130Lastlogin:TueJul3101:29:522018 from 10.0.0.129
[root@haproxy ~]# exit
logout
Connection to 10.0.0.130 closed.