我正在 Linux 服务器上编写 Expect 脚本,该脚本应该远程登录到路由器以收集一些系统信息。到目前为止,我的脚本可以成功建立连接、运行路由器命令、断开连接并终止。
该命令显示了我需要解析的几行,我不确定如何在 Expect 中执行此操作。如何保存输出,grep 一行,然后从该行中查找一列,最后将结果保存在文件中?如果可能的话,我想完全使用 Expect 而不是解决方法(例如 Bash 中嵌入的 Expect)。
感谢您抽出时间。
jk04
I am half-way through writing an Expect script on a Linux server which is supposed to telnet to a router in order to collect some system information. So far my script can successfully make the connection, run a router command, disconnect and terminate.
The command displays a few lines which I need to parse, something I am not sure how to do in Expect. How can I save the output, grep a line, then a column from the line, and finally save the result in a file? If possible, I would like to use Expect entirely rather than a work-around (for example Expect embdded in Bash).
Thanks for your time.
jk04
发布评论
评论(3)
Expect 开发的两个技巧:
autoexpect
为您的自动化构建一个框架exp_internal 1
详细地显示 Expect 内部正在做什么。当您无法弄清楚为什么正则表达式没有捕获您期望的内容时,这一点是必不可少的。Two tips for expect development:
autoexpect
to lay out a framework for your automationexp_internal 1
to show verbosely what expect is doing internally. This one is indispensable when you can't figure out why your regular expression isn't capturing what you expect.基本上,$expect_out(buffer) [1]。保存最后一个期望匹配到当前匹配的输出。你可以在那里找到你的命令输出。
对于字符串操作,您可以简单地使用 tcl 的内置 [2][3]。
basically, $expect_out(buffer) [1]. holds the output from last expect match to the current one. you can find your command output there.
and for the string manipulation, you can simply employ the tcl's built-in [2][3].
我在与 bash 交互时遇到并解决了类似的问题。我相信该方法可以推广到任何其他提供无操作、固定字符串输出的交互式环境。
基本上,我用两个固定字符串包装命令,然后搜索在开头和结尾包含这些字符串的模式,并将内容保存在它们之间。例如:
我怀疑这种方法也适用于 shell 的注释字符,或者返回已知输出的简单状态命令。
然后你可以用“var”的内容做任何你需要的事情。
I've faced and solved a similar problem for interacting with bash. I believe the approach generalizes to any other interactive environment that provides no-op, fixed-string output.
Basically, I wrap the command with two fixed strings and then search for the pattern that includes these strings at the beginning and end, and save the content in between them. For example:
I suspect that this approach would work with a shell's comment characters as well, or a simple status command that returns a known output.
Then you can do whatever you need with the content of 'var'.