How to store output in a variable while using expect 'send' command

时间秒杀一切 提交于 2020-01-14 07:43:08

问题


Thanks.

But the account and password are needed. So I must send them and then send ovs-vsctl command.

the scripts are something like this:

spawn telnet@ip 

expect -re "*login*" {
       send "root"
}

expect -re "password*" {
       send "****"
}

send "ovs-vsctl *******"

I want to store the output of this command send "ovs-vsctl ****", but many times I got some output of the command "send "password"", how can I get the output of send "ovs-vsctl****". The output of the command send "ovs-vsctl *** are two string and each string occupies one line.

Thanks.


回答1:


Maybe:

log_user 0                   ;# turn off the usual output
spawn telnet@ip 
expect -re "*login*"
send "root\r"
expect -re "password*"
send "****\r"
send "ovs-vsctl *******"
expect eof
puts $expect_out(buffer)     ;# print the results of the command



回答2:


Expect works with an input buffer, which contains everything that is returned from the interactive application, meaning both process output and your input (as long is it is echoed from the remote device, which is usually the case).

The expect command is used to recover text from the input buffer. Each time a match is found, the buffer up to the end of that match is cleared, and saved to $expect_out(buffer). The actual match is saved to $expect_out(0,string). The buffer then resets.

What you need to do in your case is match the output with an expect statement, to get what you want.

What I would do in your case is match the remote device prompt after sending the password, then match it again after command was sent. That way the buffer after the last match will hold the needed output.

Something along the lines of:

[...]
expect -re "password*" {
       send "****"
}

expect -re ">"

send "ovs-vsctl *******\r"

expect -re ">"  # Better if you can use a regexp based on your knowledge of device output here - see below

puts $expect_out(buffer)

By matching using a regexp based on your knowledge of the output, you should be able to extract only the command output and not the echoed command itself. Or you can always do that after-the-fact, by using the regexp command.

Hope that helps!



来源:https://stackoverflow.com/questions/20884435/how-to-store-output-in-a-variable-while-using-expect-send-command

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!