1. 程式人生 > >linux中expect命令詳解

linux中expect命令詳解

linux運維

expect

expect 是由Don Libes基於Tcl(Tool Command Language )語言開發的,主要應用於自動化交互式操作的場景,借助Expect處理交互的命令,可以將交互過程如:ssh登錄,ftp登錄等寫在一個腳本上,使之自動化完成。尤其適用於需要對多臺服務器執行相同操作的環境中,可以大大提高系統管理人員的工作效率

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匹配多個字符串在執行動作後加此命令

except最常用的語法(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"}

}

示例

cat ssh1.exp

#!/usr/bin/expect

spawn ssh 192.168.8.100

expect {

"yes/no" { send"yes\n";exp_continue }

"password" { send“magedu\n" }

}

interact

#expect eof

示例:變量

cat ssh2.exp

#!/usr/bin/expect

set ip 192.168.8.100

set user root

set password magedu

set timeout 10

spawn ssh [email protected]$ip

expect {

"yes/no" { send"yes\n";exp_continue }

"password" { send"$password\n" }

}

interact

示例:位置參數

vim ssh3.exp

#!/usr/bin/expect

set ip [lindex $argv 0]

set user [lindex $argv 1]

set password [lindex $argv 2]

spawn ssh [email protected]$ip

expect {

"yes/no" { send"yes\n";exp_continue }

"password" { send"$password\n" }

}

interact

#./ssh3.exp 192.168.8.100 rootmagedu

示例:執行多個命令

cat ssh4.exp

#!/usr/bin/expect

set ip [lindex $argv 0]

set user [lindex $argv 1]

set password [lindex $argv 2]

set timeout 10

spawn ssh [email protected]$ip

expect {

"yes/no" { send"yes\n";exp_continue }

"password" { send"$password\n" }

}

expect "]#" { send"useradd haha\n" }

expect "]#" { send"echo magedu |passwd --stdin haha\n" }

send "exit\n"

expect eof

#./ssh4.exp 192.168.8.100 rootmagedu

示例:shell腳本調用expect

vim ssh5.sh

#!/bin/bash

ip=$1

user=$2

password=$3

expect <<EOF

set timeout 10

spawn [email protected]$ip

expect {

"yes/no" { send"yes\n";exp_continue}

"password" { send"$password\n" }

}

expect "]#" { send"useraddhehe\n" }

expect "]#" { send "echomagedu|passwd--stdinhehe\n" }

expect "]#" { send"exit\n" }

expect eof

EOF

#./ssh5.sh 192.168.8.100 rootmagedus


本文出自 “13145479” 博客,請務必保留此出處http://13155479.blog.51cto.com/13145479/1970741

linux中expect命令詳解