简体   繁体   中英

How to read the send command output in expect script

I have an expect script that will login to the remote server and execute a python script. In python script I have set sys.exit(1) for a certain condition so that it would stop execution when that condition is met. Is there way to know if python script stopped execution or ran fine?
(or) is there a way to read the output that python script produces (that is I would like to read output of send "python pythonscript.py arg1\\r" ). Any approach is fine. Please suggest ideas

expectscript.exp

#!/usr/bin/expect

eval spawn ssh -oStrictHostKeyChecking=no -oCheckHostIP=no user@******
expect "Password:"
send "password\r"
expect "$username$"
set prompt ":|#|\\\$"
set timeout -1
send "cd /Users/username/Documents/folder/\r"
send "python pythonscript.py arg1\r"
expect $prompt

Run as command

spawn ssh -c "python pythonscript.py arg1"
expect $prompt

Try to use spawn -c for executable commands as this will fetch the result back, sending them terminates after execution.

This is where you need to expect -re to capture the output before the prompt:

send "cd /Users/username/Documents/folder/\r"
expect $prompt
send "python pythonscript.py arg1\r"
expect -re "(.+)$prompt"
set pythonOutput $expect_out(1,string)

expect buffers output in the expect_out array, and the array key 1,string (note, no space there ) contains the contents of the first capturing parentheses of the regex pattern.

Also note, the output will include the python command, and lines are ended with \\r\\n : so you can do something like:

set outputLines [lrange [lmap line [split $pythonOutput \n] {regsub {\r$} $line ""] 1 end]

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