一般来说,我对脚本很陌生。我正在编写一个将 ssh 连接到 Cisco 交换机的期望脚本,并运行“show cdp neighbors”命令以获取连接到交换机的所有设备的列表。然后我将输出保存到一个变量中并退出 ssh 会话。我在包含的文件中设置了用户名和密码。
#!/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
...
有任何想法吗?可能有一个正则表达式可以做到这一点,但我不知道正则表达式。
解决:感谢格伦杰克曼
我最终不得不添加一个期望条件来检查我是否有一个完整的缓冲区,所以我的最终代码如下所示:
#!/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