如何使用 expect 获取 ssh 命令的响应

如何使用 expect 获取 ssh 命令的响应

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

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

现在我想读取硬件地址,因为我正在使用 expect 进行自动化,有什么方法可以做到这一点吗?谢谢

答案1

尝试这个:

send "show interf\r"
expect -re {HW address:\s+(\S+)}
set hw_addr $expect_out(1,string)
puts "the HW address is $hw_addr"

send "exit\r"  ;# or quit, or whatever
expect eof

相关内容