实验说明:
在自动化部署时,会经常SSH别的机器去操作,然而每次的密码认证却很令人烦躁,尤其是很长的密码,因此SSH免密登陆就显得必不可少;
在机器数目很多的时候,使用更过的往往是Ansible分发并执行SSH免密登陆脚本,使得每台机器之间都能免密登陆。
实验环境:
宿主机系统 :Fedora 28 WorkStation
虚拟机管理器 :Virt-Manager 1.5.1
虚拟机配置 :ha1 CentOS 7.2 1511 (minimal) virbr0: 192.168.122.57
ha2 CentOS 7.2 1511 (minimal) virbr0: 192.168.122.58
ha3 CentOS 7.2 1511 (minimal) virbr0: 192.168.122.59
实验步骤:
1.安装系统并配置网络(所有虚拟机都需联网)
2.先操作第一台虚拟机(ha1)
3.编写主机名与IP的映射关系
[root@ha1 ~]# vi /etc/hosts
127.0.0.1 localhost localhost.localdomain localhost4 localhost4.localdomain4
::1 localhost localhost.localdomain localhost6 localhost6.localdomain6
192.168.122.57 ha1
192.168.122.58 ha2
192.168.122.59 ha3
4.创建公有密钥
[root@ha1 ~]# ssh-keygen -t rsa
Generating public/private rsa key pair.
Enter file in which to save the key (/root/.ssh/id_rsa):
/root/.ssh/id_rsa already exists.
Overwrite (y/n)? y
Enter passphrase (empty for no passphrase):
Enter same passphrase again:
Your identification has been saved in /root/.ssh/id_rsa.
Your public key has been saved in /root/.ssh/id_rsa.pub.
The key fingerprint is:
40:c3:81:eb:60:49:2e:f7:fe:59:bb:ef:7d:ad:bb:06 root@ha2
The key’s randomart image is:
+–[ RSA 2048]—-+
| o+. |
| . …. |
| o . .. |
|. * . . |
| + + S |
| o E |
| . . . . |
| . o . . o .|
| .o o+o .o++ |
+—————–+
5.发送公有密钥至远程机器
[root@ha1 ~]# ssh-copy-id root@192.168.122.58
[root@ha1 ~]# ssh-copy-id root@192.168.122.59
6.以上是单台虚拟机的逐条执行命令的方式,将以上操作写成脚本(脚本在本文末尾PS处)
7.下面操作其他虚拟机(ha2、ha3)
# 虚拟机ha2
[root@ha2 ~]# chmod 777 build-ssh-credit.sh
[root@ha2 ~]# ./build-ssh-credit.sh
# 虚拟机ha3
[root@ha3 ~]# chmod 777 build-ssh-credit.sh
[root@ha3 ~]# ./build-ssh-credit.sh
8.至此,三台虚拟机之间相互访问都无需输入密码,实现了SSH的免密登陆
9.Complete!!!
PS:公钥初始化和实现SSH免密登陆的脚本(build-ssh-credit.sh),直接拷贝就可使用。
#!/usr/bin/bash
# 安装expect,minimal没有此rpm包,需联网或有本地yum源
yum install expect -y
expect << EOF
set timeout 10
# 创建公有密钥
spawn ssh-keygen -t rsa
expect {
“*to save the key” {send “\n”;exp_continue}
“*(y/n)” {send “y\r”;exp_continue}
“Enter passphrase” {send “\n”;exp_continue}
“Enter same passphrase” {send “\n”;exp_continue}
}
EOF
# 获取/etc/hosts文件中除localhost的映射关系
ip_list=`grep -v ‘localhost’ /etc/hosts | awk -F ‘ ‘ ‘{print $1,$2}’`
for ip in $ip_list
do
expect << EOF
set timeout 2
# 发送公有密钥
spawn ssh-copy-id root@$ip
expect {
“yes/no” {send “yes\r”;exp_continue}
“password” {send “000000\r”;exp_continue}
}
# 拷贝/etc/hosts文件到远程机器
spawn scp /etc/hosts $ip:/etc
expect {
“yes/no” {send “yes\r”;exp_continue}
“password” {send “root\r”;exp_continue}
}
EOF
done
Linux公社的RSS地址:https://www.linuxidc.com/rssFeed.aspx
本文永久更新链接地址:https://www.linuxidc.com/Linux/2018-08/153761.htm