關於expect的實戰總結


如何從機器A上ssh到機器B上,然后執行機器B上的命令?如何使之自動化完成?看完下面的文章你就明白了 

一、安裝

expect 是基於tcl 演變而來的,所以很多語法和tcl 類似

sudo apt-get install tcl tk expect

或者

yum install -y tcl tclx tcl-devel

二、如何使用

expect是linux中的一個用來處理交互的命令。借助Expect,我們可以將交互過程寫在一個腳本上,使之自動化完成。形象的說,ssh登錄,ftp登錄等都符合交互的定義。下文我們首先提出一個問題,然后介紹基礎知四個命令

四個命令

Expect中最關鍵的四個命令是send,expect,spawn,interact。

send:用於向進程發送字符串
expect:從進程接收字符串
spawn:啟動新的進程
interact:允許用戶交互

1、send

send命令接收一個字符串參數,並將該參數發送到進程。

expect1.1> send "hello world\n"
hello world

2. expect命令

啟用選項

  • -c:執行腳本前先執行的命令,可多次使用。

  • -d:debug模式,可以在運行時輸出一些診斷信息,與在腳本開始處使用exp_internal 1相似。

  • -D:啟用交換調式器,可設一整數參數。

  • -f:從文件讀取命令,僅用於使用#!時。如果文件名為"-",則從stdin讀取(使用"./-"從文件名為-的文件讀取)。

  • -i:交互式輸入命令,使用"exit"或"EOF"退出輸入狀態。

  • --:標示選項結束(如果你需要傳遞與expect選項相似的參數給腳本時),可放到#!行:#!/usr/bin/expect --

  • -v:顯示expect版本信息。

expect命令和send命令正好相反,expect通常是用來等待一個進程的反饋。expect可以接收一個字符串參數,也可以接收正則表達式

expect "hi\n"
send "hello there!\n"

這兩行代碼的意思是:從標准輸入中等到hi和換行鍵后,向標准輸出輸出hello there。

看一段代碼:

#!/usr/bin/expect -f
expect "hi\n"
send "you typed <$expect_out(buffer)>"
send "but I only expected <$expect_out(0,string)>"

執行結果

1
2
3
4
5
hi
you typed <1
2
3
4
5
hi
>but I only expected <hi

多分支模式

expect "hi" { send "You said hi\n" } \
"hello" { send "Hello yourself\n" } \
"bye" { send "That was unexpected\n

或者下面的寫法

expect {
"hi" { send "You said hi\n"}
"hello" { send "Hello yourself\n"}
"bye" { send "That was unexpected\n"}
}

3、spawn

spawn命令就是用來啟動新的進程的,比如登錄ftp

spawn ftp ftp.test.com

4、interact

interact ##是Expect用來打開用戶與產生進程之間通信的命令,簡單說就是登陸以后將遠程服務器的終端保持在當前終端,而不是將遠程終端關掉

#!/usr/bin/expect -f
set timeout -1  
spawn ssh $user@$host
expect -exact  "password" 
send "$password\n"
send --  "pwd\n"
interacter

三、總結

1、常用命令

# 命令行參數 
# $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:"
 
# 發送內容ispass(密碼、命令等)
send "ispass\r"
 
# 發送內容給用戶
send_user "$argv0 [lrange $argv 0 2]\n"
send_user "It's OK\r"
# 執行完成后保持交互狀態,控制權交給控制台(手工操作)。否則會完成后會退出。
interact

2、命令介紹

  • close:關閉當前進程的連接。
  • debug:控制調試器。
  • disconnect:斷開進程連接(進程仍在后台運行)。
  • 執行priv_prog:定時讀取密碼
  • exit:退出expect。
  • exp_continue [-continue_timer]:繼續執行下面的匹配。
  • exp_internal [-f file] value:
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
}

3、范例

A、自動telnet會話

#!/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

B、自動建立FTP會話

#!/usr/bin/expect -f
setip [lindex $argv 0 ]         # 接收第1個參數,作為IP
setuserid [lindex $argv 1 ]     # 接收第2個參數,作為Userid
setmypassword [lindex $argv 2 ] # 接收第3個參數,作為密碼
settimeout 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

C、自動登錄ssh執行命令

#!/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

D、批量登錄ssh服務器執行操作范例,設定增量的for循環

#!/usr/bin/expect
for {set i 10} {$i <= 12} {incr 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

E、批量登錄ssh並執行命令,foreach語法

#!/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 root@xxx.yy.com
    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 

F、從命令行獲取服務器IP,foreach語法,expect嵌套

#!/usr/bin/expect
# 使用方法: script_name ip1 ip2 ip3 ...
 
set timeout 20
if {$argc < 1} {
  puts "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 "\$?"
# 替換你要執行的命令
send "last\r"
expect "\$?"
sleep 10
send "exit\r"
expect eof
}

G、ssh自動登錄expect腳本

#!/usr/bin/expect -f
# Auther:YuanXing
# Update:2014-02-08
if {$argc < 4} {
    send_user "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
}

H、通過shell腳本調用

#!/bin/bash

TMP=$(mktemp)
username=(test)
# create expect script

for ip in `cat ip.txt`; do

cat > $TMP << EOF
set timeout 5
spawn  ssh  -i  $username/id_rsa   -p888   $username@$ip

expect -exact "$username"  
send --  "su - \r\n"

expect -exact "Password"  
send --  "213f214##!ds(*&a@\r\n"

expect -exact "root"  
send --  "userdel -r zhangshan\r\n"
send --  "userdel -r lisi\r\n"


send --  "history -c \r\n exit\r\n"
send --  "history -c \r\n exit\r\n"
expect eof

EOF

expect -f $TMP
rm $TMP
done

  

參考:

https://www.cnblogs.com/iloveyoucc/archive/2012/05/11/2496433.html

http://www.xuetimes.com/archives/781


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM