1

I made a script and it looks like this:

#!/usr/bin/expect -f
set ip [lindex $argv 0];
spawn ssh name@server
expect "assword"
set timeout 0.5
send "password\r"
expect "xxxxx"
set timeout 1
send "telnet $ip\r"
expect "assword"
send "password\r"
expect "xxxxxx"
send "xxxxxxx\r"
.
.
.
.

The script continues to a point where my output shows like this:

Last update from 1.1.1.1 1d06h ago
  Routing Descriptor Blocks:
  * 1.1.1.1 from 2.2.2.2

I need to figure out how to extract this IP that will always be unique (1.1.1.1) and put it forward automatically into my script so I can continue.

0

There's two instances of 1.1.1.1; on the assumption that the first instance is okay to match on, one will first need to write a simple script that generates the required output and also includes fake prompts as more or less done by the remote device:

#!/usr/bin/env expect
proc prompt {} { puts "prompt"; gets stdin; }
prompt
puts "Last update from 1.1.1.1 1d06h ago"
puts "  Routing Descriptor Blocks:"
puts "  * 1.1.1.1 from 2.2.2.2"
prompt

I've called this script generator; one then also needs another script that calls and interacts with this script. But first a diversion into how to iterate quickly on changes to these scripts; in another terminal I had running:

$ (echo consume; echo generate) | entr ./consume
...

which runs the consume script anytime either of the consume or generate scripts changes. Then I can fiddle around with the scripts to interact with the prompts, find the required output, and apply a regular expression (read the regexp(n) manual) to it:

#!/usr/bin/env expect
spawn -noecho ./generate

expect -ex prompt
send -- "before\r"

expect -ex prompt
# this is what I used to confirm that the required prompt block
# had been matched
#puts ">>>$expect_out(buffer)<<<"

regexp {Last update from ([^ ]+) } $expect_out(buffer) unused theip
puts ">>>$theip<<<"

send -- "after\r"
expect eof

this method assumes the desired output is braced by prompts; another option would be to expect the Last update ... line with a regular expression but that may be more complicated. Also this IP address match could really match anything; use a more exact regular expression if you need to validate that the text there really is an IP address.

misc concerns:

  • Your timeouts are very low; what happens if any of the systems or networks involved are slow, and the output takes longer than the given timeout to arrive?
  • There's not much error checking, what happens if the ssh system instead throws up a host key error or prompt, or ...

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.