garenwang garenwang - 1 month ago 22
Linux Question

Python pexpect scripts run without error,but there are no outputs in output file

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。


#!/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')



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


There are just tow commands in the mylog1.txt file.Why?

Answer

You have to wait until the ls 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):

[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] #