expect介紹
借助Expect處理交互的命令,可以將交互 過程如:ssh登錄,ftp登錄等寫在一個腳本上,使之自動化完成.尤其適用於需 要對多台服務器執行相同操作的環境中,可以大大提高系統管理人員的工作效率
expect安裝
[root@docker-01 ~]# yum -y install expect
expect 語法
expect [選項] [ -c cmds ] [ [ -[f|b] ] cmdfile ] [ args ] 選項 -c:從命令行執行expect腳本,默認expect是交互地執行的 示例:expect -c 'expect "\n" {send "pressed enter\n"} -d:可以輸出輸出調試信息 示例:expect -d ssh.exp expect中相關命令 spawn:啟動新的進程 send:用於向進程發送字符串 expect:從進程接收字符串 interact:允許用戶交互 exp_continue 匹配多個字符串在執行動作后加此命令 expect最常用的語法(tcl語言:模式-動作) 單一分支模式語法: expect “hi” {send “You said hi\n"} 匹配到hi后,會輸出“you said hi”,並換行 多分支模式語法: expect "hi" { send "You said hi\n" } \ "hehe" { send “Hehe yourself\n" } \ "bye" { send “Good bye\n" } 匹配hi,hello,bye任意字符串時,執行相應輸出.等同如下: expect { "hi" { send "You said hi\n"} "hehe" { send "Hehe yourself\n"} "bye" { send “Good bye\n"} }
自動拷貝文件到遠程主機
執行expect 不能以bash file 的方式來執行 (開啟一個子shell進程) 必須通過 chmod +x file ./file 這樣的方式 (不會開啟子shell進程,只在當前shell環境中執行) expect 如果只交互一次如拷貝文件 結尾就使用 expect eof 如果需要連續交互如登錄遠程主機執行各種命令結尾就需使用 interact
[root@docker-01 ~]# cat login #!/usr/bin/expect set timeout 30 spawn ssh root@192.168.1.221 expect "*password:" send "123456\n" expect "#" send "systemctl restart docker\n" expect eof
解釋: 1.#!/usr/bin/expect :需要先安裝軟件,然后來說明用expect來執行 2.spawn ssh root@192.168.1.221 :spawn是進入expect環境后才可以執行的expect內部命令,用來執行它后面的命令。 3.expect "*password:" :也是expect的內部命令,用來解惑關鍵的字符串,如果有,就會立即返回下面設置的內容,如果沒有就看是否設置了超時時間。 4.send "123456\n":這時執行交互式動作,與手工輸入密碼等效,在expect截獲關鍵字之后,它就會輸入send后面的內容。 5.interact :執行完畢后把持交互狀態,把控制台,這時候就可以進行你想要進行的操作了。如果沒有這一句,在登陸完成之后就會退出,而不是留在遠程終端上。