2021-05-12 14:32:11
RHEL/CentOS 7 多節點SSH免密登陸[附可行性指令碼]
實驗說明:
在自動化部署時,會經常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 "yr";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 "yesr";exp_continue}
"password" {send "000000r";exp_continue}
}
# 拷貝/etc/hosts檔案到遠端機器
spawn scp /etc/hosts $ip:/etc
expect {
"yes/no" {send "yesr";exp_continue}
"password" {send "rootr";exp_continue}
}
EOF
done
Linux公社的RSS地址:https://www.linuxidc.com/rssFeed.aspx
本文永久更新連結地址:https://www.linuxidc.com/Linux/2018-08/153761.htm
相關文章