互動式命令 expect

來源:互聯網
上載者:User

標籤:

shell儘管很強大。但是貌似無法完成互動式命令的操作,執行個體 ssh host 如果host而且該機沒有加入信任。手動輸入的時間需要password。

這樣的情況下可以使用expect支援。


下面舉個範例來說明expect的功能與使用:


功能:對叢集各機器運行同樣指令 如 叢集ip 為 :192.168.6.1~192.168.6.10。須要在這10台機器上 同一時候 以tt使用者登入 並運行 mkdir ttji_314命令。

首先 定義一個hostlist檔案 :

192.168.6.1192.168.6.2192.168.6.3192.168.6.4192.168.6.5192.168.6.6192.168.6.7192.168.6.8192.168.6.9192.168.6.10


然後定義一個 expect指令碼 完畢在單個機器運行命令:ssh_comm.sh

#!/usr/bin/expectset host [lindex $argv 0]set command [lindex $argv 1]set password 123456set username ttset timeout 1send_user "connect to $host ...\n"spawn ssh -l $username $hostexpect "password:"send "$password\r"expect "#$"send "$command\r"expect "#$"send "exit\r"#interactexpect eof


幾點說明 :

1 首行加上/usr/bin/expect

2 spawn: 後面加上須要啟動並執行shell 命令3 expect: 僅僅有spawn 啟動並執行命令結果才會被expect 捕捉到,由於spawn 會啟動一個進程,僅僅有這個進程的相關資訊才會被捕捉到。主要包含:標準輸入的提示資訊,eof 和timeout。

4 send 和send_user:send 會將expect 指令碼中須要的資訊發送給spawn 啟動的那個進程,而send_user 僅僅是回顯使用者發出的資訊,類似於shell 中的echo 而已。5.set timeout 1之後的指令將都等待1s。
最後完畢批量功能:command_all.sh

#!/bin/bashfunction use() {        echo "========================"        echo "./command_all.sh hostlist command"        echo "========================"}if [ $# != 2 ]        then                use        else                echo "welcome to use:\n"fifile=$1command=$2echo $fileecho $commandwhile read linedo    #echo $line    ./ssh_comm.sh $line "$command"done < $file

使用:./command_all.sh hostlist "mkdir ttji_314"

有個問題:當在expect指令碼中 使用root使用者登入的時候 似乎沒有timeout這樣的概念 ,運行完命令馬上返回;

而用普通使用者才會有這樣的體現。

若有瞭解的同學請留言不吝賜教,不勝感激~



著作權聲明:本文博主原創文章,部落格,未經同意不得轉載。

互動式命令 expect

聯繫我們

該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在5個工作日內處理。

如果您發現本社區中有涉嫌抄襲的內容,歡迎發送郵件至: info-contact@alibabacloud.com 進行舉報並提供相關證據,工作人員會在 5 個工作天內聯絡您,一經查實,本站將立刻刪除涉嫌侵權內容。

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.