【发布时间】:2021-03-16 12:00:16
【问题描述】:
您好,我正在尝试制作以下脚本。
- 我们通过 ssh 访问设备 - 它可以工作
- 我们执行命令并从该命令中获取必要的数据 通过正则表达式
- 我们将接收到的数据写入一个变量
- 使用变量执行命令
#!/usr/bin/expect -f
set host [lindex $argv 0]
set user test
set pass 123456
set timeout 5
spawn ssh -o StrictHostKeyChecking=no $user@$host
expect "*assword:" {send "$pass\r"}
expect "*#" {send "sh ip int br | i Vlan9\n"}
regexp {(\d+\.\d+\.\d+\.\d+)} $expect_out(buffer) matched ip
puts "ADDRESS: $ip"
expect eof
但它不起作用..
expect -d ssh 192.168.18.200
expect -d ssh 192.168.18.200
expect version 5.45.4
argv[0] = expect argv[1] = -d argv[2] = ssh argv[3] = 192.168.18.200
set argc 1
set argv0 "ssh"
set argv "192.168.18.200"
executing commands from command file ssh
spawn ssh -o StrictHostKeyChecking=no test@192.168.18.200
parent: waiting for sync byte
parent: telling child to go ahead
parent: now unsynchronized from child
spawn: returns {22907}
expect: does "" (spawn_id exp5) match glob pattern "*assword:"? no
Password:
expect: does "\rPassword: " (spawn_id exp5) match glob pattern "*assword:"? yes
expect: set expect_out(0,string) "\rPassword:"
expect: set expect_out(spawn_id) "exp5"
expect: set expect_out(buffer) "\rPassword:"
send: sending "123456\r" to { exp5 }
expect: does " " (spawn_id exp5) match glob pattern "*#"? no
expect: does " \r\n" (spawn_id exp5) match glob pattern "*#"? no
test-gw#
expect: does " \r\ntest-gw#" (spawn_id exp5) match glob pattern "*#"? yes
expect: set expect_out(0,string) " \r\ntest-gw#"
expect: set expect_out(spawn_id) "exp5"
expect: set expect_out(buffer) " \r\ntest-gw#"
send: sending "sh ip int br | i Vlan9\n" to { exp5 }
can't read "ip": no such variable
while executing
"puts "ADDRESS: $ip""
(file "ssh" line 17)
在路由器上是这样的
sh ip int br | i Vlan9
Vlan9 192.168.18.200 YES NVRAM up up
通过send我们执行这个命令,通过正则表达式我们需要把地址192.168.18.200拉出来写入一个变量中以备使用
【问题讨论】:
-
你能给出合法行和非法行的输入示例吗?这个期望看起来像 TCL,所以你在你的正则表达式中缺少捕获分配
-
用
expect -d myprog.exp arg ...运行你的程序——非常详细的调试输出会告诉你为什么你的模式不匹配。 -
不,你读错了我的回答。把我的正则表达式放在你期望的 -re 正则表达式的地方。 IP 将出现在 expect_out(1,string) 变量中。
-
是的,我不明白:它工作 - 期望 -exact "#" 发送 -- "sh run | i hostname\r" set name $expect_out(buffer) regexp {([_A-Za-z0-9]+)} $name match hostname puts "$hostname"
-
它不起作用 - 期望 -exact "#" 发送 -- "sh ip int br | i Vlan9\r" set src $expect_out(buffer) regexp { (\d+\.\d+\.\d+\.\d+)} $src match ipsrc puts "ADDRESS: $ipsrc"