實(shí)現(xiàn)免密登陸腳本, expect登陸遠(yuǎn)程主機(jī),將生成的密鑰寫入到目標(biāo)主機(jī), expect測(cè)試遠(yuǎn)程登陸。
1)通過shift讀取腳本參數(shù)
2)通過select來選擇功能.例如功能有
- 安裝mysql
- 安裝apache
- 免密鑰登陸主機(jī)
當(dāng)前我們只實(shí)現(xiàn)免密鑰登陸主機(jī)
3)通過函數(shù)封裝每個(gè)功能
4)將免密鑰登陸的過程可以重復(fù)進(jìn)行, while 循環(huán)實(shí)現(xiàn)重復(fù),需要有退出過程。當(dāng)用戶輸入exit時(shí),退出免密鑰功能。
5)支持輸入一批主機(jī)免密鑰,使用數(shù)組 實(shí)現(xiàn)
#!/bin/bash
# **********************************************************
#
# * Author : zxk
# * Email : zxknico@foxmail.com
# * Create time : 2022-09-02 22:31
# * Filename : main_test.sh
# * Description :
#
# **********************************************************
declare -A host
ssh_except () {
echo "免密登錄功能現(xiàn)在運(yùn)行"
while [ -n "$1" ];do #shift兩兩讀取腳本參數(shù),依次為主機(jī)IP和密碼,然后向其發(fā)送生成的公鑰文件
hostip=$1
shift
secret=$1
shift
host[$hostip]=$secret
echo "shift傳參完成"
done
while true;do #while循環(huán)實(shí)現(xiàn)多次的免密登錄和增加免密登錄的主機(jī)
cat <<EOF
請(qǐng)選擇1-3
1)再次確認(rèn)免密登錄主機(jī)IP和登錄密碼
2)輸入測(cè)試主機(jī)IP
3)退出免密登錄
EOF
read -p "您的選擇:" i
case $i in
1)
read -p"IP和密碼:" hostip secret
host[$hostip]=$secret
#創(chuàng)建公鑰 -P:密碼為空 -f:指定公鑰位置(實(shí)現(xiàn)無交互創(chuàng)建公鑰)
[ ! -f /root/.ssh/id_rsa.pub ] && ssh-keygen -t rsa -P '' &>/dev/null
expect <<EOF
spawn ssh-copy-id -i /root/.ssh/id_rsa.pub root@$hostip
expect {
"yes/no" { send "yes\n";exp_continue }
"password" { send "$secret\n" }
}
expect eof
EOF
;;
2)
read -p"測(cè)試ip:" testip
ssh root@$testip
;;
3)
break
;;
esac
done
}
main="--安裝myspl --安裝apache --免密鑰登錄主機(jī) --退出"
select i in $main;do
case $REPLY in
1)
echo "安裝mysql成功"
;;
2)
echo "安裝apache成功"
;;
3)
ssh_except $*
;;
4) break
;;
esac
done
運(yùn)行展示

image.png