Linux Shell腳本攻略讀書筆記 II —— 自動(dòng)化同步公鑰實(shí)現(xiàn)無密碼登錄

實(shí)現(xiàn)ssh免密需要兩步:

1.在本機(jī)創(chuàng)建SSH密鑰??ssh-keygen -t?rsa

2.將生成的公鑰加入到遠(yuǎn)程主機(jī)的~/.ssh/authorized_keys中

這里要使用sshpass工具 所以需要先安裝:

Ubuntu/Debian:?apt-get install sshpass

Fedora/CentOS:?yum install sshpass

Arch:?pacman -S sshpass

先不多說,直接上代碼

完成代碼git倉(cāng)庫(kù)?shell腳本學(xué)習(xí)隨筆? /auto_login.sh

#!/bin/bash

read -p "please input your username:" username

read -s -p "please input your password:" password

sync_key() {

while read ip;

do (

sshpass -p $password ssh -o StrictHostKeyChecking=no $username@$ip "cat >> /$username/.ssh/authorized_keys" < /$username/.ssh/id_rsa.pub ;

if [ $? -eq 0 ];

then

echo "the server $ip set successful ."

else

echo "the server $ip set failed ."

fi

)&

done < servers.list

wait;

}

if [ -e /$username/.ssh/id_rsa.pub -a -e /$username/.ssh/id_rsa ];

then

echo "the key is already"

sync_key

else

echo "the key is not exsits . "

exit

fi


要點(diǎn):

1. ssh采用了非對(duì)稱加密,密鑰包含兩個(gè)部分 公鑰和私鑰. ssh-keygen 可以生成公鑰以及私鑰。要實(shí)現(xiàn)免密登錄則需要將公鑰放置在目標(biāo)機(jī)器中(~/.ssh/authorized_keys)

2.read -s 指定不顯示用戶輸入 用于密碼的輸入

3.-e [path] 用以驗(yàn)證文件是否存在 -a = --and?

4.ssh-keygen -t rsa?指定rsa算法生成密鑰

5.while?read line; do () done < filename; 表示對(duì)filename文件中逐行進(jìn)行處理,filename文件作為stdin(標(biāo)準(zhǔn)輸入)

6.在while中使用()& done wait 語(yǔ)法表示并行使用子shell執(zhí)行小括號(hào)內(nèi)的命令 wait表示等待各個(gè)shell執(zhí)行完畢

7.這里使用sshpass工具向ssh指定主機(jī)密碼。 由于ssh沒有指定密碼輸入指令因此無法實(shí)現(xiàn)自動(dòng)填充密碼,因此借助sshpass工具實(shí)現(xiàn)。其中-o StrictHostKeyChecking=no表示在第一次登陸時(shí)不必進(jìn)行警告.

這里還可以使用expect工具來實(shí)現(xiàn)ssh密碼的輸入,由于expect是另一種解釋器因此沒有使用。

8. 這里使用了ssh user@host "command" 命令 表示在遠(yuǎn)程主機(jī)上執(zhí)行command命令。這里將本機(jī)的pub key作為標(biāo)準(zhǔn)輸入提供給指定的命令

9. $? 表示獲取上一步命令的執(zhí)行結(jié)果 0 表示成功 非0表示失敗

倉(cāng)庫(kù)中有auto_login.sh ,? auto_login.session 以及 auto_login.log

利用scriptreplay auto_login.log auto_login.session?

運(yùn)行錄制視頻運(yùn)行auto_login.sh即可

執(zhí)行截圖效果如下:


最后編輯于
?著作權(quán)歸作者所有,轉(zhuǎn)載或內(nèi)容合作請(qǐng)聯(lián)系作者
【社區(qū)內(nèi)容提示】社區(qū)部分內(nèi)容疑似由AI輔助生成,瀏覽時(shí)請(qǐng)結(jié)合常識(shí)與多方信息審慎甄別。
平臺(tái)聲明:文章內(nèi)容(如有圖片或視頻亦包括在內(nèi))由作者上傳并發(fā)布,文章內(nèi)容僅代表作者本人觀點(diǎn),簡(jiǎn)書系信息發(fā)布平臺(tái),僅提供信息存儲(chǔ)服務(wù)。
禁止轉(zhuǎn)載,如需轉(zhuǎn)載請(qǐng)通過簡(jiǎn)信或評(píng)論聯(lián)系作者。

相關(guān)閱讀更多精彩內(nèi)容

友情鏈接更多精彩內(nèi)容