开发者

How do you save and parse a command output in Expect?

开发者 https://www.devze.com 2022-12-16 09:44 出处:网络
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 succe开发者_JAVA技巧ssfully m

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 succe开发者_JAVA技巧ssfully 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


Two tips for expect development:

  • autoexpect to lay out a framework for your automation
  • exp_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.


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].

  1. "How to access the result of a remote command in Expect" http://wiki.tcl.tk/2958
  2. "regexp" http://wiki.tcl.tk/986
  3. "string match" http://wiki.tcl.tk/4385


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:

set var "";
expect $prompt { send "echo PSTART; $command; echo PEND;\r"; }
expect {
    -re PSTART\r\n(.*)PEND\r\n$prompt { set var [ string trim $expect_out(1,string) ]; send "\r"; }
    -re $prompt { set var "" ; send "\r"; }
    timeout { send_user "TIMEOUT\n"; exit }
}

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'.

0

精彩评论

暂无评论...
验证码 换一张
取 消