首页 > 解决方案 > 如何发送超过 100 条 cmd 行

问题描述

我期望(tcl)脚本用于自动任务正常工作 - 通过 telnet/ssh 配置网络设备。大多数情况下要执行 1,2 或 3 个命令行,但现在我有 100 多个命令行要通过期望发送。我怎样才能以智能和良好的脚本方式实现这一点:) 因为我可以将所有超过 100 的命令行与“\n”连接到一个变量“commandAll”并一个接一个地“发送”它们,但我认为它非常难看:)有没有办法不将它们堆叠在一起以便在代码或外部文件中读取?

#!/usr/bin/expect -f
set timeout 20
set ip_address "[lrange $argv 0 0]"
set hostname "[lrange $argv 1 1]"
set is_ok ""

# Commands
set command1 "configure snmp info 1"
set command2 "configure ntp info 2"
set command3 "configure cdp info 3"
#... more then 100 dif commands like this !
#... more then 100 dif commands like this !
#... more then 100 dif commands like this !

spawn telnet $ip_address

# login & Password & Get enable prompt
#-- snnipped--#

# Commands execution

# command1
expect "$enableprompt" { send "$command1\r# endCmd1\r" ; set is_ok "command1" }
    if {$is_ok != "command1"} {
        send_user "\n@@@ 9 Exit before executing command1\n" ; exit
    }

# command2
expect "#endCmd1" { send "$command2\r# endCmd2\r" ; set is_ok "command2" }
    if {$is_ok != "command2"} {
        send_user "\n@@@ 9 Exit before executing command2\n" ; exit
    }

# command3
expect "#endCmd2" { send "$command3\r\r\r# endCmd3\r" ; set is_ok "command3" }
    if {$is_ok != "command3"} {
        send_user "\n@@@ 9 Exit before executing command3\n" ; exit
    }

ps 我正在使用一种方法来获取成功,因为 cmd 行已成功执行,但我不确定这是完美的方法:D

标签: tclexpect

解决方案


不要使用编号变量,使用列表

set commands {
    "configure snmp info 1"
    "configure ntp info 2"
    "configure cdp info 3"
    ...
}

如果命令已经在文件中,您可以将它们读入列表:

set fh [open commands.file]
set commands [split [read $fh] \n]
close $fh

然后,遍历它们:

expect $prompt

set n 0
foreach cmd $commands {
    send "$cmd\r"
    expect {
        "some error string" {
            send_user "command failed: ($n) $cmd"
            exit 1
        }
        timeout {
            send_user "command timed out: ($n) $cmd"
            exit 1
        }
        $prompt 
    }
    incr n
}

推荐阅读