shell_expect實現(xiàn)自動

一、expect內(nèi)部命令

語法結(jié)構(gòu)

spawn  shell 命令程序
expect  "捕獲到shell命令程序執(zhí)行之后輸出的字符串"
send "發(fā)送給 shell 命令程序的字符串"

在命令行直接輸入 expect 可以進入 expect 程序的解釋器終端

[root@localhost ~]# expect
expect1.1> spawn echo "hello"  #發(fā)送一條shell命令
spawn echo hello
57431
expect1.2> expect "hello"     #捕獲這個字符串
hello
expect1.3> send "yes\n"      #發(fā)送一個字符串
expect1.4> expect off       # 結(jié)束這次捕獲
yes

在腳本中使用

# 開始 expect  解釋器程序
/usr/bin/expect<<EOF
# 設(shè)置捕獲字符串后,期待回復的超時時間
set timeout 30
spawn   ssh-keygen

# 開始進連續(xù)捕獲
expect     {
        ".ssh/id_rsa)"       { send    "\n";  exp_continue }
        "Overwrite (y/n)?"   { send    "y\n"; exp_continue }
        "no passphrase):"    { send    "\n";  exp_continue }
        "again:"             { send    "\n";  exp_continue }
}
# 結(jié)束 expect 解釋器程序
EOF

實戰(zhàn)案例

# 寫個用于自動生成密鑰對的函數(shù)
auto_keygen (){
    /usr/bin/expect<<EOF
    set timeout 30        #設(shè)置超時時間
    spawn   ssh-keygen   #發(fā)送命令

    expect     {

        ".ssh/id_rsa)"       { send    "\n";  exp_continue }
        "Overwrite (y/n)?"   { send    "y\n"; exp_continue }
        "no passphrase):"    { send    "\n";  exp_continue }
        "again:"             { send    "\n";  exp_continue }
    }
EOF
}
# 寫個自動免密登錄的函數(shù)
send_key () {
pwd=upsa
/usr/bin/expect <<EOF
set timeout 30

# 發(fā)送公鑰給對方服務(wù)器
spawn ssh-copy-id root@$1
expect {
"yes/no" { send "yes\n"; exp_continue }
"password:" { send "${pwd}\n"} }
expect eof
EOF
}

# 定義一個變量,其值是當前用戶的公鑰文件
pub_key_file=$HOME/.ssh/id_rsa.pub
# 假如公鑰文件不存在,說明需要創(chuàng)建密鑰對
if [ ! -f ${pub_key_file} ];then
    auto_keygen
fi

# 循環(huán)一個存放 ip 地址的文件,并且把每個 IP地址傳遞給 函數(shù)
for ip in $(cat ./ips.txt)
do
   send_key $ip
done

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

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

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