简体   繁体   中英

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.

Your problem is two-fold:

  1. You're not expect ing the response after send ing 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, eg, 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…

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.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM