【问题标题】:show ip interface brief in expect script在期望脚本中显示 ip 接口简介
【发布时间】:2023-03-05 13:48:01
【问题描述】:

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

你知道如何编写 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]
设置文件数据 [读取 $fp]
关闭 $fp
设置提示“>”
log_file -noappend switch_port_status.txt
foreach ip [split $file_data "\n"] {
提出“切换 $ip 接口状态”
生成远程登录 $ip
期望“用户名:”
发送“我的用户名\r”
期待“assword:”
发送“我的密码\r”
期待 $prompt
# 避免在大型配置中发送“Enter”键
发送“显示 ip int br\r”
期待 $prompt
期待{
-ex "--More--" { 发送--" "; exp_continue }
"*>" { 发送 "exit\r" }
}
设置超时 1; # 恢复默认超时
# 在全局提示下发送“退出”将关闭连接
期待 eof
}

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

switch-hostname>交换机接口状态
生成远程登录
用法:telnet [-l 用户] [-a] 主机名 [端口]
发送:生成 id exp9 未打开
执行时
"发送 "我的用户名\r""
(“foreach”身体线 5)
从内部调用
"foreach ip [拆分 $file_data "\n"] {
提出“切换 $ip 接口状态”
生成远程登录 $ip
期望“用户名:”
发送“我的用户名\r”
期待……”
(文件“./autotelnet.sh”第 8 行)

【问题讨论】:

    标签: telnet remote-access expect cisco


    【解决方案1】:

    您可以使用逐行输入交换机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"
    

    如果您想获得多个命令输出,请将它们保存在一个文件中并逐个发送。

    【讨论】:

    • 这是可行的。但是我收到了上述错误消息作为帖子,我该如何解决这个问题?谢谢
    • @Danny Luk :看起来 telnet 会话在没有任何 IP 地址的情况下产生。即ip 变量可能为空。该文件也可能包含空行。为了避免这种情况,我们可以在read 命令中使用nonewline 标志。我已经更新了我的答案。请检查。如果这篇文章回答了您的问题,您可以接受答案。
    • 我真的很感激。非常感谢! :D
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2011-10-20
    • 1970-01-01
    • 2016-02-28
    • 1970-01-01
    • 1970-01-01
    • 2014-10-20
    相关资源
    最近更新 更多