J. Tam
J. Tam

Reputation: 145

How to filter output from a command in an Expect Script

I'm writing an automation script that logs into servers and finds an application id. I'm using an expect script in order to login to each of he servers after expecting a prompt. When I login, there is a wall of default text (SECURITY NOTICE etc) I'm trying to store the output from a command AFTER I login to the server but haven't found any luck doing so. Any advice is appreciated

This is for a Linux server. I've tried using $expect_out(buffer) but had no luck muting the login message at the beginning.

ssh -l <userid> <servername>
expect "$prompt" {send "ps -ef|grep java| grep -i 'jboss' |cut -f1 -d' '\r"}
set id $expect_out(buffer)
exec ./output.sh $id

The output I receive is a substring of the login message.

Upvotes: 0

Views: 1712

Answers (2)

J. Tam
J. Tam

Reputation: 145

I found the solution. To get the response from my command, I used the following code:

expect "$prompt"
set cmd "ps -ef|grep java|grep -i 'tomcat' | cut -f1 -d' '\r"
send -- $cmd
expect eof

expect -re "$ ps -ef | grep java | grep -i 'tomcat' | cut -f1 -d' '\r\n(.*)\r" {set output $expect_out(1,string)}

I set the expect value to contain the command (with the prompt) and made it continue onto the next line where my desired output would be. Then I set my variable $output to be $expect_out(1,string) which takes everything but the expected value therefore giving me my command output.

Upvotes: 0

Donal Fellows
Donal Fellows

Reputation: 137567

Your problem is two-fold:

  1. You're not expecting the response after sending the command. Without that, the response probably won't actually be processed at the point when you try to extract the ID from the response.
  2. The expect_out(buffer) variable can very easily contain text other than that which you want. You need to be selective about matching, e.g., with a regular expression and the -re option to `expect.

I'm guessing that the fix is to change that third line to:

expect -re {(\d+)\n} {
    set id $expect_out(1,string)
}

Remember to turn on debugging mode whenever you can't figure out why your expect script is going wrong. It usually says exactly what the (immediate) problem is, which helps hugely…

Upvotes: 1

Related Questions