實(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í)行截圖效果如下:
