在 expect 脚本中显示 ip 接口简介

show ip interface brief in expect script

我希望能够设置一个可以远程连接到多个交换机的期望脚本文件。

你知道如何编写 telnet 到 200 台交换机的专家脚本和 运行 命令示例:show ip interface brief 然后列出 Linux 上的所有交换机状态吗??

#!/usr/bin/expect -f
spawn telnet 192.168.0.1
expect "Username:"
send "MyUsername\r"
expect "assword:"
send "MyPassword\r"
send "show ip int br\r"
interact timeout 5
expect {
    "MORE --, next page" {send -- " "; exp_continue}
    "*?2626#*" {send -- "exit \r"}
}

感谢 Dinesh,在我期望的脚本如下后:

!/usr/bin/expect -f

吞噬输入文件

设置 fp [打开 "input.txt" r]
设置 file_data [读取 $fp]
关闭 $fp
设置提示符“>”
log_file -noappend switch_port_status.txt
foreach ip [拆分 $file_data "\n"] {
放“切换 $ip 接口状态”
spawn telnet $ip
期望“用户名:”
发送“MyUsername\r”
期待“密码:”
发送“MyPassword\r”
期待$提示
# 为了避免在巨大的配置
上发送 'Enter' 密钥 发送“show ip int br\r”
期待$提示
期待{
-ex "--More--" { 发送 -- " "; exp_continue}
“*>”{ 发送“exit\r”}
}
设置超时 1; # 恢复默认超时
# 在全局级别提示发送 'exit' 将关闭连接
期待eof
}

可行。但以下是我收到的错误消息,我该如何解决?谢谢

switch-hostname>交换机接口状态
生成 telnet
用法:telnet [-l 用户] [-a] 主机名 [端口]
发送:spawn id exp9 未打开
执行时
“发送“MyUsername\r”
(“foreach”正文第 5 行)
从内部调用
"foreach ip [split $file_data "\n"] {
放“切换 $ip 接口状态”
spawn telnet $ip
期望“用户名:”
发送“MyUsername\r”
期望..."
(文件“./autotelnet.sh”第 8 行)

您可以使用逐行输入交换机IP信息的文件。使用 terminal length 0 将保存我们的工作,最后 log_file 派上用场来保存输出。

#!/usr/bin/expect -f
#Slurp up the input file
set fp [open "input.txt" r]
# To avoid empty lines, 'nonewline' flag is used
set file_data [read -nonewline $fp]
close $fp 
set prompt "#"
log_file -noappend switch_port_status.txt
foreach ip [split $file_data "\n"] {
    puts "Switch $ip Interface Status"
    spawn telnet $ip
    expect "Username:"
    send "MyUsername\r"
    expect "assword:"
    send "MyPassword\r"
    expect $prompt
    # To avoid sending 'Enter' key on huge configurations
    send "terminal length 0\r"
    expect $prompt
    set timeout 120;# Increasing timeout to 2mins, as it may take more time to get the prompt
    send "show ip int br\r"
    expect $prompt
    set timeout 10; # Reverting to default timeout
    # Sending 'exit' at global level prompt will close the connection
    send "exit\r"
    expect eof
}

注意:关闭连接只在发送exit命令的基础上处理。因此,请确保 exit 命令始终在全局级别的提示符下发送。除了依赖 exit,我们还可以使用关闭 telnet 连接的典型方式,即 'Ctrl+]' 组合键。

#This will send 'Ctrl+]' to close the telnet connection gracefully
send "\x1d"
expect "telnet>"
send "quit\r"
expect "Connection"

如果假设你想获得多个命令输出,那么将它们保存在一个文件中并一个一个地发送。