Using expect to get output from ssh
<p>I am trying to use <code>expect</code> to automate a task as part of a larger python program and am having a lot of trouble getting the stdout of the ssh command being run on a remote machine. I have not used <code>expect</code> before and haven't had success finding the solution on the man page.</p>

<p>I need to use expect to automate some interactions before actually being able to run this command, but I removed them here to simplify the question.</p>

<p>Here is a simplified example of the program:</p>

<pre><code>import subprocess

expect = """
/usr/bin/expect &lt;&lt;EOF

spawn ssh some_machine ls
expect eof
puts "$expect_out(buffer)"
"""

output = subprocess.check_output(expect, shell=True)
print(output)
</code></pre>

<p>Output:</p>

<pre><code>b'spawn ssh some_machine ls\r\n116029\r\nArchive\r\n\r\n(buffer)\n'
</code></pre>

<p>It appears to contain the spawn command as well as "(buffer)" at the end. I'm not sure why this is occurring. I am trying to only get the results of the <code>ls</code>.</p>

<p>If I turn on debug mode in expect, I see the <code>expect_out(buffer)</code> being set to what I would like to return, but the <code>puts</code> does not reflect this.</p>

<p>Output:</p>

<pre><code>expect version 5.45
argv[0] = /usr/bin/expect  argv[1] = -d
set argc 0
set argv0 "/usr/bin/expect"
set argv ""
executing commands from command file
parent: waiting for sync byte
parent: telling child to go ahead
parent: now unsynchronized from child
spawn: returns {1753}
expect: read eof
expect: set expect_out(spawn_id) "exp7"
expect: set expect_out(buffer) "116029\r\nArchive\r\n"
&lt;wrong output as above&gt;
</code></pre>