CentOS / RHEL /Ubuntu 幾乎Linux環境都適用
工作上須對多台服務器來做設定檔修改等等,ssh對多台連線避免出現人工key密碼情形,當然此方法也可以拿來使用ssh-copy-id交換多台主機ssh public key環境使用以Centos8.2來做示範首先來安裝epel-release 與sshpass 套件
[student@localhost 桌面]$ sudo dnf -y install epel-release && sudo dnf -y install sshpass
Extra Packages for Enterprise Linux Modular 8 - 39 kB/s | 82 kB 00:02
Extra Packages for Enterprise Linux 8 - x86_64 611 kB/s | 7.5 MB 00:12
依賴關係解析完畢。
================================================================================
Package Architecture Version Repository Size
================================================================================
安裝:
sshpass x86_64 1.06-9.el8 epel 27 k
首次登入ssh連線的話會show出一個 "Are you sure you want to continue connecting (yes/no/[fingerprint])?" 會造成sshpass使用困難
解決辦法:ssh -o StrictHostKeyChecking=no
[student@localhost 桌面]$ ssh 192.168.0.11
The authenticity of host '192.168.0.11 (192.168.0.11)' can't be established.
ECDSA key fingerprint is SHA256:s1MZg2bsOHYuwR6WfTdE1Z2sDyLBX7LJmDSIL/+kiqk.
Are you sure you want to continue connecting (yes/no/[fingerprint])?
1. 使用明碼的方式來登入遠端主機
sshpass -p password ssh -o StrictHostKeyChecking=no user@ip
-p : 後面接的是使用者密碼 "student"
[student@localhost 桌面]$ sshpass -p student ssh -o StrictHostKeyChecking=no student@192.168.0.11
Warning: Permanently added '192.168.0.11' (ECDSA) to the list of known hosts.
Activate the web console with: systemctl enable --now cockpit.socket
Last login: Wed Aug 5 04:55:54 2020
2. 宣告變數SSHPASS來登入遠端主機
-e : 帶入$SSHPASS環境變數 "student"
[student@localhost ~]$ export SSHPASS=student
[student@localhost ~]$ echo $SSHPASS
student
[student@localhost ~]$ sshpass -e ssh student@servera
Activate the web console with: systemctl enable --now cockpit.socketLast login: Wed Aug 5 06:51:14 2020 from 192.168.0.100
[student@servera ~]$
3. 從file 載入使用者密碼登入
-f : 從檔案載入使用者密碼 "student"
[student@servera ~]$ echo "student" >> passwd.txt
[student@servera ~]$ cat passwd.txt
student
[student@localhost ~]$ sshpass -f passwd.txt ssh student@servera
Activate the web console with: systemctl enable --now cockpit.socket
Last login: Wed Aug 5 06:57:32 2020 from 192.168.0.100
4. For Loop迴圈搭配使用sshpass
如果第一次登入記得加上 "ssh -o StrictHostKeyChecking=no"
[student@localhost ~]$ for i in {a..c} ; do sshpass -f passwd.txt ssh -o StrictHostKeyChecking=no student@server$i 'hostname' ;done
servera.example.comserverb.example.comserverc.example.com
5. 編寫簡單腳本來對遠端主機做控制
[student@localhost ~]$ cat server_list.cfg
servera
serverb
serverc
[student@localhost ~]$ cat passwd.sh
#!/bin/bash
export SSHPASS=redhat
ips=`cat server_list.cfg`
for ip in $ips
do
echo ==========$ip===========
sshpass -e ssh root@$ip "hostname"
[ $? -eq 0 ] && echo -e "\033[32m ==$ip==password is ok... \033[0m" || echo -e "\033[31m ==$ip==Password is error!!! \033[0m"
done