Search code examples
pythonbashexpectsys

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

Solution

  • 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]