jk04
jk04

Reputation: 41

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

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

Upvotes: 4

Views: 30363

Answers (3)

stephen.z
stephen.z

Reputation: 345

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

Upvotes: 4

glenn jackman
glenn jackman

Reputation: 246764

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.

Upvotes: 7

Dyno Fu
Dyno Fu

Reputation: 9044

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

Upvotes: 6

Related Questions