gpt4 book ai didi

regex - 在期望脚本中显示 cdp 邻居

转载 作者:行者123 更新时间:2023-12-02 05:04:20 27 4
gpt4 key购买 nike

总的来说,我对脚本编写还很陌生。我正在编写一个 expect 脚本,它通过 ssh 进入 Cisco 交换机,并运行“show cdp neighbors”命令来获取连接到交换机的所有设备的列表。然后我将输出保存到一个变量中并退出 ssh session 。我在包含的文件中设置了用户名和密码。

#!/usr/bin/expect -f
#exp_internal 1

source accountfile
set timeout 10
spawn $env(SHELL)
expect "#"
send "ssh $USERNAME@<hostname>\r"
expect {
"continue connecting" {
send_user "Adding host to ssh known hosts list...\n"
send "yes\n"
exp_continue
}
"Do you want to change the host key on disk" {
send_user "Changing host key on disk...\n"
send "yes\n"
exp_continue
}
"assword:" {
send "$PASSWORD\r"
}
}
expect "#"
send "term len 0\r"
expect "#"
send "show cdp neighbors\r"
expect "#"
set result $expect_out(buffer)
send "exit\r"
expect "#"

然后我想获取 $result 并查找包含 'R' 的行,并将这些行保存到文件中(R 两边都有空格表示路由器,这是我感兴趣的)

问题是,如果连接的设备名称很长,它会将设备名称放在一行,然后将有关该设备的其余数据放在下一行。因此,如果我匹配“R”字符串,我将无法获得设备名称,因为该名称位于前一行。

Device ID        Local Intrfce     Holdtme     Capability Platform  Port ID
...
<device_name_really_long>
Gig 2/0/52 171 R S I WS-C6509 Gig 3/14
<device_name2> Gig 2/0/1 131 H P M IP Phone Port 1
...

有什么想法吗?可能有一个正则表达式可以做到这一点,但我对正则表达式一无所知。

已解决:感谢 Glenn Jackman

我最终不得不添加一个期望条件来检查我是否有一个完整的缓冲区,所以我的最终代码如下所示:

#!/usr/bin/expect
#exp_internal 1
match_max 10000
set expect_out(buffer) {}
set timeout 30

source accountfile
spawn $env(SHELL)
expect "#"
send "ssh $USERNAME@ol2110-3750stack.sw.network.local\r"
expect {
"continue connecting" {
send_user "Adding host to ssh known hosts list...\n"
send "yes\n"
exp_continue
}
"Do you want to change the host key on disk" {
send_user "Changing host key on disk...\n"
send "yes\n"
exp_continue
}
"assword:" {
send "$PASSWORD\r"
}
}
expect "#"
send "term len 0\r"
expect "#"
send "show cdp neighbors\r"
set result ""
expect {
{full_buffer} {
puts "====== FULL BUFFER ======"
append result $expect_out(buffer)
exp_continue
}
"#" {
append result $expect_out(buffer)
}
}
send "exit\r"
expect "#"
set devices [list]
set current_device ""
set lines [split $result "\n"]
foreach line $lines {
set line [string trim $line]
if {[llength $line] == 1} {
set current_device $line
continue
}
set line "$current_device$line\n"
if {[string match {* R *} $line]} {
lappend devices $line
}
set current_device ""
}

puts $devices

最佳答案

set devices [list]
set current_device ""
foreach line [split $result \n] {
if {[llength [split [string trim $line]]] == 1} {
set current_device $line
continue
}
set line "$current_device$line"
if {[string match {* R *} $line]} {
lappend devices $line
}
set current_device ""
}

# devices list should now contain "joined" routers.

关于regex - 在期望脚本中显示 cdp 邻居,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/13383821/

27 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com