如何使用expect从ssh命令获得响应

时间:2013-12-12 11:00:22

标签: ssh terminal

目前我正在使用以下代码,

#!/usr/bin/expect --

set timeout 60

set username [lindex $argv 0]
set password [lindex $argv 1]
set ip [lindex $argv 2]


spawn ssh $username@$ip

expect {
        "*yes/no*" { send "yes\r" }
        "?assword:" { send "$password\r" }
}
expect ">"
send "en\r"

expect "#"
send "con t\r"

expect "(config) #"
send "show interf\r"
interact

我在终端中有以下结果,

Interface abcdefgh status:
   Comment:            
   Admin up:           XXX
   Link up:            XXX
   DHCP running:       XX
   IP address:         00.00.00.000 /00
   Netmask:            255.255.255.0
   IPv6 enabled:       no
   Speed:              1000Mb/s (auto)
   Duplex:             full (auto)
   Interface type:     abcdefgh
   MTU:                0000
   HW address:         XX:XX:XX:XX:XX:XX

现在我想读取硬件地址,因为我正在使用期望自动化,有没有任何方法。感谢

1 个答案:

答案 0 :(得分:0)

我刚刚找到了解决方案,并为像我一样受苦的每个人分享。
send "show interf\r"
expect -re {HW address:\s+(\S+)}
set hw_addr $expect_out(1,string)
puts "the HW address is $hw_addr"