掃二維碼與項目經理溝通
我們在微信上24小時期待你的聲音
解答本文疑問/技術咨詢/運營咨詢/技術建議/互聯網交流
expect是一個自動化交互套件,主要應用于執(zhí)行命令和程序時,系統以交互形式要求輸入指定字符串,實現交互通信,本篇文章為大家詳細講解一下Linux expect使用方法。

創(chuàng)新互聯堅持“要么做到,要么別承諾”的工作理念,服務領域包括:成都網站制作、做網站、企業(yè)官網、英文網站、手機端網站、網站推廣等服務,滿足客戶于互聯網時代的克井網站設計、移動媒體設計的需求,幫助企業(yè)找到有效的互聯網解決方案。努力成為您成熟可靠的網絡建設合作伙伴!
-c:執(zhí)行腳本前先執(zhí)行的命令,可多次使用。-d:debug模式,可以在運行時輸出一些診斷信息,與在腳本開始處使用exp_internal 1相似。-D:啟用交換調式器,可設一整數參數。-f:從文件讀取命令,僅用于使用#!時。如果文件名為”-“,則從stdin讀取(使用”./-“從文件名為-的文件讀取)。-i:交互式輸入命令,使用”exit”或”EOF”退出輸入狀態(tài)。--:標示選項結束(如果你需要傳遞與expect選項相似的參數給腳本時),可放到#!行:#!/usr/bin/expect --。-v:顯示expect版本信息。Expect中最關鍵的四個命令是send,expect,spawn,interact。
| 命令 | 說明 |
|---|---|
| send | 用于向進程發(fā)送字符串 |
| expect | 從進程接收字符串 |
| spawn | 啟動新的進程 |
| interact | 允許用戶交互 |
`# 命令行參數`
`# $argv,參數數組,使用[lindex $argv n]獲取,$argv 0為腳本名字`
`# $argc,參數個數`
`set` `username [lindex $argv 1]` `# 獲取第1個參數`
`set` `passwd` `[lindex $argv 2]` `# 獲取第2個參數`
`set` `timeout 30` `# 設置超時`
`# spawn是expect內部命令,開啟ssh連接`
`spawn` `ssh` `-l username 192.168.1.1`
`# 判斷上次輸出結果里是否包含“password:”的字符串,如果有則立即返回,否則就等待一段時間(timeout)后返回`
`expect` `"password:"`
`# 發(fā)送內容ispass(密碼、命令等)`
`send` `"ispass\r"`
`# 發(fā)送內容給用戶`
`send_user` `"$argv0 [lrange $argv 0 2]\n"`
`send_user` `"It's OK\r"`
`# 執(zhí)行完成后保持交互狀態(tài),控制權交給控制臺(手工操作)。否則會完成后會退出。`
`interact`
close:關閉當前進程的連接。
debug:控制調試器。
disconnect:斷開進程連接(進程仍在后臺運行)。
`send_user` `"password?\ "`
`expect_user -re` `"(.*)\n"`
`for` `{} 1 {} {`
`if` `{[fork]!=0} {``sleep` `3600;``continue``}`
`disconnect`
`spawn priv_prog`
`expect Password:`
`send` `"$expect_out(1,string)\r"`
`. . .`
`exit`
`}`
#!/usr/bin/expect ##注意路徑,使用 [whereis expect] 查看
set user "hadoop" ##設定參數,注意",'的區(qū)別
set pwd "yangkun"
set host "48.93.36.144"
set timeout -1 ##;號可有可無
spawn ssh -p 2020 $user@$host
expect { ##expect后有空格
"*yes/no" {send "yes\r";exp_continue}
"*password:" {send "$pwd\r"}
}
expect "]*" ## 通配符,使用 ]* 有效, 使用 *# 無效
send "touch /home/hadoop/aa.txt\r"
expect "]*"
send "echo hello world >> /home/hadoop/aa.txt\r"
expect "]*"
[interact] ##人為交互
send "exit\r" ##退出
#!/bin/bash
#!/usr/bin/expect
SERVERS="114.114.114.114" ##數組以空格分隔,可以為目標ip 或者hostName
PASSWORD="yangkun"
## 實現免密登錄配置的函數
auto_ssh_copy_id() {
expect -c "set timeout -1; spawn ssh-copy-id \"-p 2020 $1\"; ## 這里要注意,使用'或\'不可行 expect { *(yes/no)* {send -- yes\r;exp_continue;} *password:* {send -- $2\r;exp_continue;} eof {exit 0;} }";
}
## 循環(huán)執(zhí)行,配置主機到從節(jié)點所有免密
ssh_copy_id_to_all() {
for SERVER in $SERVERS ## 取值需要加$
do
auto_ssh_copy_id $SERVER $PASSWORD
done
}
## 調用循環(huán)配置函數
ssh_copy_id_to_all
## 批量部署
for SERVER in $SERVERS
do
scp install.sh root@$SERVER:/root
ssh root@$SERVER /root/install.sh
done
讓腳本自動讀取slaves文件中的機器名來批量安裝
cat slaves | while read host
do
echo $host
expect -c "set timeout -f spawn ssh-copy-id $host"
done
#!/bin/bash
BASE_SERVER=master
BASE_PATH=/home/hadoop/soft
TARGET_PATH=/usr/local
JAVA_PATH=$TARGET_PATH/java
## 1.判斷是否存在文件夾,不存在則創(chuàng)建soft文件夾
#if [ ! -d "$BASE_PATH" ]; then
# mkdir "$BASE_PATH"
#fi
## 2.從指定host拷貝jdk到目標機器上(已經拷貝文件夾)
scp -r $BASE_SERVER:$BASE_PATH $BASE_PATH
## 2.解壓jdk到指定目錄
if [ ! -d "$JAVA_PATH" ]; then
sudo -S mkdir -p "$JAVA_PATH"
fi
## 賦予權限
sudo -S chmod -R hadoop:hadoop $JAVA_PATH
tar -zxvf $BASE_PATH/jdk1.8.0_121.tar.gz -C $JAVA_PATH
#### 3.配置環(huán)境變量
sudo -S cat>>/etc/profileexport JAVA_HOME=$JAVA_PATH/jdk1.8.0_121
export PATH=\$PATH:\$JAVA_HOME/bin
EOF
#!/usr/bin/expect -f
set ip [lindex $argv 0 ] # 接收第1個參數,作為IP
set userid [lindex $argv 1 ] # 接收第2個參數,作為userid
set mypassword [lindex $argv 2 ] # 接收第3個參數,作為密碼
set mycommand [lindex $argv 3 ] # 接收第4個參數,作為命令
set timeout 10 # 設置超時時間
# 向遠程服務器請求打開一個telnet會話,并等待服務器詢問用戶名
spawn telnet $ip
expect "username:"
# 輸入用戶名,并等待服務器詢問密碼
send "$userid\r"
expect "password:"
# 輸入密碼,并等待鍵入需要運行的命令
send "$mypassword\r"
expect "%"
# 輸入預先定好的密碼,等待運行結果
send "$mycommand\r"
expect "%"
# 將運行結果存入到變量中,顯示出來或者寫到磁盤中
set results $expect_out(buffer)
# 退出telnet會話,等待服務器的退出提示EOF
send "exit\r"
expect eof
#!/usr/bin/expect -f
set ip [lindex $argv 0 ] # 接收第1個參數,作為IP
set userid [lindex $argv 1 ] # 接收第2個參數,作為Userid
set mypassword [lindex $argv 2 ] # 接收第3個參數,作為密碼
set timeout 10 # 設置超時時間
# 向遠程服務器請求打開一個FTP會話,并等待服務器詢問用戶名
spawn ftp $ip
expect "username:"
# 輸入用戶名,并等待服務器詢問密碼
send "$userid\r"
expect "password:"
# 輸入密碼,并等待FTP提示符的出現
send "$mypassword\r"
expect "ftp>"
# 切換到二進制模式,并等待FTP提示符的出現
send "bin\r"
expect "ftp>"
# 關閉ftp的提示符
send "prompt\r"
expect "ftp>"
# 下載所有文件
send "mget *\r"
expect "ftp>"
# 退出此次ftp會話,并等待服務器的退出提示EOF
send "bye\r"
expect eof
#!/usr/bin/expect
set IP [lindex $argv 0]
set USER [lindex $argv 1]
set PASSWD [lindex $argv 2]
set CMD [lindex $argv 3]
spawn ssh $USER@$IP $CMD
expect {
"(yes/no)?" {
send "yes\r"
expect "password:"
send "$PASSWD\r"
}
"password:" {send "$PASSWD\r"}
"* to host" {exit 1}
}
expect eof
#!/usr/bin/expect -f
set ip [lindex $argv 0 ] # 接收第1個參數,作為IP
set username [lindex $argv 1 ] # 接收第2個參數,作為username
set mypassword [lindex $argv 2 ] # 接收第3個參數,作為密碼
set timeout 10 # 設置超時時間
spawn ssh $username@$ip # 發(fā)送ssh請求
expect { # 返回信息匹配
"*yes/no" { send "yes\r"; exp_continue} # 第一次ssh連接會提示yes/no,繼續(xù)
"*password:" { send "$mypassword\r" } # 出現密碼提示,發(fā)送密碼
}
interact # 交互模式,用戶會停留在遠程服務器上面
#!/usr/bin/expect
for {set i 10} {$i set timeout 30
set ssh_user [lindex $argv 0]
spawn ssh -i .ssh/$ssh_user abc$i.com
expect_before "no)?" {
send "yes\r" }
sleep 1
expect "password*"
send "hello\r"
expect "*#"
send "echo hello expect! > /tmp/expect.txt\r"
expect "*#"
send "echo\r"
}
exit
#!/usr/bin/expect
if {$argc!=2} {
send_user "usage: ./expect ssh_user password\n"
exit
}
foreach i {11 12} {
set timeout 30
set ssh_user [lindex $argv 0]
set password [lindex $argv 1]
spawn ssh -i .ssh/$ssh_user [email protected]
expect_before "no)?" {
send "yes\r" }
sleep 1
expect "Enter passphrase for key*"
send "password\r"
expect "*#"
send "echo hello expect! > /tmp/expect.txt\r"
expect "*#"
send "echo\r"
}
exit
#!/usr/bin/expect
# 使用方法: script_name ip1 ip2 ip3 ...
set timeout 20
if {$argc "Usage: script IPs"
exit 1
}
# 替換你自己的用戶名
set user "username"
#替換你自己的登錄密碼
set password "yourpassword"
foreach IP $argv {
spawn ssh $user@$IP
expect \
"(yes/no)?" {
send "yes\r"
expect "password:?" {
send "$password\r"
}
} "password:?" {
send "$password\r"
}
expect "\$?"
# 替換你要執(zhí)行的命令
send "last\r"
expect "\$?"
sleep 10
send "exit\r"
expect eof
}
* tclsh - Simple shell containing Tcl interpreter
1
#!/bin/sh
# -*- tcl -*- \
exec tclsh $0 "$@"
package require Expect
set username [lindex $argv 0]
set password [lindex $argv 1]
set argv [lrange $argv 2 end]
set prompt "(%|#|\\$) $"
foreach ip $argv {
spawn ssh -t $username@$ip sh
lappend ids $spawn_id
}
expect_before -i ids eof {
set index [lsearch $ids $expect_out(spawn_id)]
set ids [lreplace $ids $index $index]
if [llength $ids] exp_continue
}
expect -i ids "(yes/no)\\?" {
send -i $expect_out(spawn_id) yes\r
exp_continue
} -i ids "Enter passphrase for key" {
send -i $expect_out(spawn_id) \r
exp_continue
} -i ids "assword:" {
send -i $expect_out(spawn_id) $password\r
exp_continue
} -i ids -re $prompt {
set spawn_id $expect_out(spawn_id)
send "echo hello; exit\r"
exp_continue
} timeout {
exit 1
}
The authenticity of host '192.168.17.35 (192.168.17.35)' can't be established. RSA key fingerprint is 25:e8:4c:89:a3:b2:06:ee:de:66:c7:7e:1b:fa:1c:c5. Are you sure you want to continue connecting (yes/no)? Warning: Permanently added '192.168.17.35' (RSA) to the list of known hosts. Enter passphrase for key '/data/key/my_dsa': Last login: Sun Jan 26 13:39:37 2014 from 192.168.11.143 [root@master003 ~]# [email protected]'s password:
Last login: Thu Jan 23 17:50:43 2014 from 192.168.11.102
[root@lvsmaster ~]#
#!/usr/bin/expect -f
# Auther:YuanXing
# Update:2014-02-08
if {$argc "Usage:\n $argv0 IPaddr User Passwd Port Passphrase\n"
puts stderr "argv error!\n"
sleep 1
exit 1
}
set ip [lindex $argv 0 ]
set user [lindex $argv 1 ]
set passwd [lindex $argv 2 ]
set port [lindex $argv 3 ]
set passphrase [lindex $argv 4 ]
set timeout 6
if {$port == ""} {
set port 22
}
#send_user "IP:$ip,User:$user,Passwd:$passwd,Port:$port,Passphrase:$passphrase"
spawn ssh -p $port $user@$ip
expect_before "(yes/no)\\?" {
send "yes\r"}
expect \
"Enter passphrase for key*" {
send "$passphrase\r"
exp_continue
} " password:?" {
send "$passwd\r"
exp_continue
} "*\[#\\\$]" {
interact
} "* to host" {
send_user "Connect faild!"
exit 2
} timeout {
send_user "Connect timeout!"
exit 2
} eof {
send_user "Lost connect!"
exit
}
#!/bin/bash
# TAG: mikrotik, ssh, expect, lftp
BACKUP_DIR="/var/backups"
HOSTNAME="192.168.88.1"
PORT="22"
USER="admin"
PASS="123456"
TMP=$(mktemp)
TODAY=$(date +%F)
FILENAME="$HOSTNAME-$TODAY"
PATH="/usr/local/sbin:/usr/sbin:/sbin:/usr/local/bin:/usr/bin:/bin"
# create expect script
cat > $TMP #exp_internal 1 # Uncomment for debug
set timeout -1
spawn ssh -p$PORT $USER@$HOSTNAME
match_max 100000
expect -exact "password:"
send -- "$PASS\r"
sleep 1
expect " > "
send -- "/export file=$FILENAME\r"
expect " > "
send -- "/system backup save name=$FILENAME\r"
expect " > "
send -- "quit\r"
expect eof
EOF
# run expect script
#cat $TMP # Uncomment for debug
expect -f $TMP
# remove expect script
rm $TMP
# download and remove backup files
# "xfer:clobber on" means overwrite existing files
cd ${BACKUP_DIR}
echo " set xfer:clobber on get ${FILENAME}.rsc rm ${FILENAME}.rsc get ${FILENAME}.backup rm ${FILENAME}.backup" |
lftp -u $USER,$PASS $HOSTNAME

我們在微信上24小時期待你的聲音
解答本文疑問/技術咨詢/運營咨詢/技術建議/互聯網交流