您好,登錄后才能下訂單哦!
平時(shí)運(yùn)維中有時(shí)會(huì)遇到需要更改服務(wù)器的管理員密碼,如果服務(wù)器比較多的時(shí)候,我們可以編寫一個(gè)腳本來實(shí)現(xiàn),省時(shí)省力。
linux使用SSH登陸時(shí)需 要手動(dòng)輸入yes 來確認(rèn)連接,所以首先要解決這個(gè)問題,讓腳本實(shí)現(xiàn)遠(yuǎn)程執(zhí)行命令無須人工干預(yù)。
第一步 使用ssh-keygen創(chuàng)建本機(jī)的公鑰和私鑰
創(chuàng)建成功后會(huì)在/root/.ssh下生成私鑰和公鑰
第二步 使用ssh-copy-id復(fù)制公鑰到遠(yuǎn)程主機(jī)及expect內(nèi)部命令編寫ssh自動(dòng)登陸腳本
auto_ssh_copy_id () {
expect -c "set timeout -1;
spawn /usr/bin/ssh-copy-id -i /root/.ssh/id_rsa.pub root@$2;
expect {
*(yes/no)* {send -- yes\r;exp_continue;}
*password:* {send -- $1\r;exp_continue;}
eof{exit 0;}
}";
}
調(diào)用方法:auto_ssh_copy_id $pass1 $ipnet.$i
假設(shè)需要更改密碼的服務(wù)器IP 在172.18.0.1-172.18.0.100之間,腳本如下。
#!/bin/bash
#Program
#
#relase
#tryrus 20161029
ipnet=172.18.0 #改成實(shí)際的IP 段
declare i=1 #改成實(shí)際開始的IP
pass1=password1 #ssh遠(yuǎn)程登陸root的密碼
pass2=password2 #要設(shè)定的新密碼
auto_ssh_copy_id () {
expect -c "set timeout -1;
spawn /usr/bin/ssh-copy-id -i /root/.ssh/id_rsa.pub root@$2;
expect {
*(yes/no)* {send -- yes\r;exp_continue;}
*password:* {send -- $1\r;exp_continue;}
eof{exit 0;}
}";
}
auto_ssh_change_psw() {
expect -c "set timeout -1;
spawn ssh root@$2 "passwd";
expect {
*New* {send -- $1\r;exp_continue;}
*Retype* {send -- $1\r;exp_continue;}
eof{exit 0;}
}";
}
while [[ "$i" -le "100" ]] #控制循環(huán),數(shù)值改成實(shí)際要使用的IP
do
ping "$ipnet.$i" -c 3 > /dev/null
if [ $? -eq 0 ];then
auto_ssh_copy_id $pass1 $ipnet.$i #運(yùn)行一次后,這行就不需要了
auto_ssh_change_psw $pass2 $ipnet.$i
fi
let "i+=1"
done
第二次測(cè)試結(jié)果
謝謝你打開這篇博文,并一直堅(jiān)持看到了這里,如果覺得對(duì)你有幫助,請(qǐng)不要吝嗇點(diǎn)一下右下角的贊。
免責(zé)聲明:本站發(fā)布的內(nèi)容(圖片、視頻和文字)以原創(chuàng)、轉(zhuǎn)載和分享為主,文章觀點(diǎn)不代表本網(wǎng)站立場(chǎng),如果涉及侵權(quán)請(qǐng)聯(lián)系站長郵箱:is@yisu.com進(jìn)行舉報(bào),并提供相關(guān)證據(jù),一經(jīng)查實(shí),將立刻刪除涉嫌侵權(quán)內(nèi)容。