Python pexpect scripts run without error,but there are no outputs in output file
<p>I want to put the results of 'ls /home' into mylog1.txt through ssh.So,I can check it on my computer.When I run the script,there is no error,there is no output in mylog1.txtã</p>

<blockquote>
<pre><code>#!/usr/bin/env python
import pexpect
import sys

child=pexpect.spawn('ssh shiyanlou@192.168.42.2')
fout=file('mylog1.txt','w')
child.logfile=fout

child.expect("password:")
child.sendline("xxxxx")
child.expect('$')
child.sendline('ls /home')
</code></pre>
</blockquote>

<pre><code>shiyanlou:pythontest/ $ cat mylog1.txt                                                                                    
shiyanlou@192.168.42.2's password: xxxxxxx 
ls /home
</code></pre>

<p>There are just tow commands in the mylog1.txt file.Why?</p>

<p>You have to wait until the <code>ls</code> command finishes, just like when you are interacting with the terminal. See following example (I'm using public key auth for ssh so no password prompt):</p>

<pre class="lang-none prettyprint-override"><code>[STEP 106] # cat foo.py
import pexpect

shell_prompt = 'bash-[.0-9]+[$#] '

ssh = pexpect.spawn('ssh -t 127.0.0.1 bash --noprofile --norc')
ofile = file('file.out', 'w')
ssh.logfile_read = ofile

ssh.expect(shell_prompt)

ssh.sendline('echo hello world')
ssh.expect(shell_prompt)

ssh.sendline('exit')
ssh.expect(pexpect.EOF)
[STEP 107] # python foo.py
[STEP 108] # cat file.out
bash-4.3# echo hello world
hello world
bash-4.3# exit
exit
Connection to 127.0.0.1 closed.
[STEP 109] #
</code></pre>

python linux devops pexpect