2016-10-15 1 views
1

Ich möchte die Ergebnisse von 'ls/home' in mylog1.txt durch ssh.So, kann ich es auf meinem Computer überprüfen.Wenn ich laufe das Skript, ist kein Fehler, es gibt keinen Ausgang in mylog1.txt ist.Python Pexpect Skripte laufen ohne Fehler, aber es gibt keine Ausgaben in der Ausgabedatei

#!/usr/bin/env python 
import pexpect 
import sys 

child=pexpect.spawn('ssh [email protected]') 
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                      
[email protected]'s password: xxxxxxx 
ls /home 

Es gibt nur Befehle in der mylog1.txt file.Why schleppen?

+0

Vielen Dank! @ whjm.Ich habe meinen Code ändern.An der letzten Zeile, fügen Sie child.expect (pexpect.EOF) an, es funktioniert! – garenwang

Antwort

0

Sie müssen versuchen, bis die ls Befehl beendet warten, wie wenn Sie mit dem Terminal interagieren. Siehe folgendes Beispiel (Ich benutze öffentlichen Schlüssel auth für ssh, also keine Passwortabfrage):

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

pexpect ist gut, um mit einer Anwendung zu interagieren.

Aber wenn Sie einfach ssh wollen und einen Befehl ausführen, ich werde Sie beraten Paramiko

Verwandte Themen