pepoluan
pepoluan

Reputation: 6780

Expect: how to grab part of output

I'm a bit new to expect programming, so I need help.

Here's a sample session:

CMD> disable inactive
Accounts to be disabled are:
    albert_a  - UUID abcd-11-2222
    brian_b  - UUID bcde-22-3333
    charley_c  - UUID cdef-33-4444
Starting processing
    ...hundreds of lines of processing...
CMD> quit
Done.

I need to grab the username and UUIDs there (the UUIDs are not available through other means), then either save them into a file. How do I do that in expect?

Edit: the - UUID (space dash space "UUID") part of the list is static, and not found anywhere in the "hundreds of lines of processing", so I think I can match against that pattern... but how?

Upvotes: 0

Views: 214

Answers (1)

James
James

Reputation: 1236

Assuming the answer to my question in the comments is 'yes', here's my suggestion.

First, you need to spawn whatever program will connect you to the server (ssh, telnet, or whatever), and login (expect user prompt, send password, expect prompt). You'll find plenty samples of that, so I'll skip that part.

Once you have done that, and have a command prompt, here's how I would send the command and expect & match output:

set file [open /tmp/inactive-users w]     ;# open for writing and set file identifier

send "disable inactive\r"

expect {
      -re "(\[a-z0-9_\]+)  - UUID" {     ;# match username followed by "  - UUID"
            puts $file "$expect_out(1,string)"     ;# write username matched within parenthesis to file identifier
            exp_continue     ;# stay in the same expect loop in case another UUID line comes
      }
      -re "CMD>" {     ;# if we hit the prompt, command execution has finished -> close file
            close $file
      }
      timeout {     ;# reasonably elegant exit in case something goes bad
            puts $file "Error: expect block timed out"
            close $file
      }
}

Pls note that in the regexp I'm assuming that usernames can be composed of lowercase letters, numbers and underscores only.

If you need help with the login piece let me know, but you should be ok. There are plenty of samples of that out there.

Hope that helps!

Upvotes: 1

Related Questions