expect 使用
安裝:yum -y install expect
1,首行宣告
2,控制台輸出
3,設定日期變數$date
4,設定ip變數$local_ip 127.0.0.1
#!/usr/bin/expect -f
set date [exec date "+%y%m%d"]
set ip1 123.57.219.236
set timeout 3000
6,簡單互動
spawn
send:用於向程序傳送字串
expect:從程序接收字串
spawn:啟動新的程序
interact:允許使用者互動
等待輸入"hi\n"
?輸出"hello word\n"
?expect "hi\n"
send "you typed <$expect_out(buffer)>"
send "but i only expected <$expect_out(0,string)>"
當在標準輸入中輸入
test
hi是,執行結果如下
you typed: test
hii only expect: hi
匹配到hi後,會輸出"you said hi"
expect "hi"
匹配到hi,hello,bye任意乙個字串時,執行相應的輸出
expect
"hello"
"bye"
}set timeout -1
spawn ftp ftp.test.com //開啟新的程序,該程序使用者連線遠端ftp伺服器.最後將控制權交給使用者.
expect "name" //程序返回name時
send "user\r" //向程序輸入anonymous\r
expect "password:" //程序返回password:時
send "123456\r" //向程序輸入[email protected]\r
expect "ftp> " //程序返回ftp>時
send "binary\r" //向程序輸入binary\r
expect "ftp> " //程序返回ftp>時
send "get test.tar.gz\r" //向程序輸入get test.tar.gz\r
interact
ssh免密碼登入:123.57.219.236,密碼:123456:
spawn ssh -p10022 [email protected]
expect
"password:"
}interact
執行236上指定目錄的指令碼,可以適配第一次連線:
spawn ssh -p 10022 rsync@$ip1 "expect /data/software/bak/rsync_2_48.sh"
expect
"$ip1's password:"
}expect eof
2,獲取執行引數
執行的第乙個引數
set nb1 [lindex $argv 0]
# 執行第二個引數
set nb2 [lindex $argv 1]
# 引數數量
puts "$argc"
# 程式名字
puts "$argv0"
3,邏輯判斷
switch 分支結構
set color [lindex $argv 0]
switch $color
banana
}if 分支
#!/usr/bin/expect
set test [lindex $argv 0]
puts "$test"
} else
for 迴圈結構
第一種foreach number
第二種for
while 迴圈結構
set i 1
while
4 函式定義
proc test {}
test
5. 結尾加 interact
執行完成後保持互動狀態,把控制權交給控制台,這個時候就可以手工操作了。如果沒有這一句登入完成後會退出,而不是留在遠端終端上。如果你只是登入過去執行
然後在shell指令碼中呼叫即可:
#!/bin/bash
expect /root/shell/login.exp agrv1 agrv2
linux 下expect的使用
usr bin expect set timeout 60 spawn ssh l guest 210.45.114.190 expect password expect guest node43 send cd sa11011033 r expect guest node43 send touch...
Linux下expect的安裝和使用
要使用expect需要預先安裝tcl這個東西,然後再安裝expect包.我這裡使用的是tcl8.4.11 src.tar.gz和expect 5.43.0.tar.gz的安裝包.安裝tcl和expect tar zxvf tcl8.4.11 src.tar.gz cd tcl8.4.11 unix ...
在Linux下靈活使用expect指令碼的小竅門
對於喜愛自動化的linux系統管理員而言,一定是用過expect這個命令列工具。expect 是由 don libes 基於 tcl 語言開發的,並被廣泛應用於互動式操作和自動化測試的場景之中,它尤其適用於需要對多台伺服器執行相同操作的環境中,可以大幅度提高系統管理人員的工作效率。本文是thegee...