expect介紹
expect 是由 Don Libes 基于 Tcl(Tool Command Language)語言開發(fā)的,主要應(yīng)用于自動(dòng)化交互式操作的場景嫌褪,借助 Expect 處理交互的命令笼痛,可以將交互過程如:ssh登錄,ftp登錄等寫在一個(gè)腳本上摘刑,使之自動(dòng)化完成刻坊。尤其適用于需要對多臺(tái)服務(wù)器執(zhí)行相同操作的環(huán)境中谭胚,可以大大提高系統(tǒng)管理人員的工作效率。
expect 語法:
expect [option] [-c cmds] [[-[f|b]] cmdfile] [args]
選項(xiàng):
?-c:從命令行執(zhí)行 expect 腳本漏益,默認(rèn) expect 是交互地執(zhí)行的
??expect -c expect "\n" {send "pressed enter\n"}
?-d:可以輸出調(diào)試信息
??expect -d ssh.exp
expect 中相關(guān)命令:
?spawn
:啟動(dòng)新的進(jìn)程
?send
:用于向進(jìn)程發(fā)送字符串
?expect
:從進(jìn)程接收字符串
?interact
:允許用戶交互
?exp_continue
:匹配多個(gè)字符串在執(zhí)行動(dòng)作后加此命令expect 最常用的語法(tcl 語言:模式 - 動(dòng)作)
-
單一分支模式語法:
匹配到 hi 后蛹锰,會(huì)輸出 "You said hi",并換行[root@node2 ~]# expect expect1.1> expect "hi" {send "You said hi\n"} hi You said hi
-
多分支模式語法:
匹配 hi绰疤,hehe铜犬,bye 任意字符串時(shí),執(zhí)行相應(yīng)輸出[root@node2 ~]# expect expect1.1> expect "hi" { send "You said hi\n" } \ +> "hehe" { send "Hehe yourself\n" } \ +> "bye" { send "Good bye\n" } hi You said hi
[root@node2 ~]# expect expect1.1> expect { +> "hi" { send "You said hi\n" } +> "hehe" { send "Hehe yourself\n" } +> "bye" { send "Good bye\n" } +> } hi You said hi
示例:
- 自動(dòng)化遠(yuǎn)程復(fù)制文件
#!/usr/bin/expect spawn scp /etc/fstab 192.168.8.100:/app expect { "yes/no" { send "yes\n";exp_continue } "password" { send "RyoATeu6\n" } } expect eof
- 自動(dòng)化登錄
#!/usr/bin/expect spawn ssh 192.168.8.100 expect { "yes/no" { send "yes\n";exp_continue } "password" { send "RyoATeu6\n" } } interact
- 變量
#!/usr/bin/expect set ip 192.168.8.100 set user root set password 88888888 set timeout 10 spawn ssh $user@$ip expect { "yes/no" { send "yes\n";exp_continue } "password" { send "$password\n" } } interact
- 位置參數(shù)
#!/usr/bin/expect set ip [lindex $argv 0] set user [lindex $argv 1] set password [lindex $argv 2] spawn ssh $user@$ip expect { "yes/no" { send "yes\n";exp_continue } "password" { send "$password\n" } } interact
- shell腳本調(diào)用expect
#!/bin/bash ip=$1 user=$2 password=$3 expect <<EOF set timeout 10 spawn ssh $user@$ip expect { "yes/no" { send "yes\n";exp_continue } "password" { send "$password\n" } } expect "]#" { send "useradd hehe\n" } expect "]#" { send "echo 88888888 | passwd --stdin hehe\n" } expect "]#" { send "exit\n" } expect eof EOF