2016-10-15 6 views
1

'ls/home'의 결과를 ssh.So를 통해 mylog1.txt에 넣으 려합니다. 컴퓨터에서 확인할 수 있습니다. 실행할 때 스크립트는 mylog1.txt에는 출력이없는, 오류가 없다.Python pexpect 스크립트는 오류없이 실행되지만 출력 파일에는 출력이 없습니다

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

단지 명령이 mylog1.txt file.Why에가 견인입니까?

+0

감사합니다. @ whjm.I 내 코드를 변경했습니다. 마지막 행에 child.expect (pexpect.EOF)를 추가하면 작동합니다! – garenwang

답변

0

당신은 ls 명령이 완료 될 때까지 기다릴 필요가 시도 할 조언합니다. 다음 예제를 참조하십시오 (암호 입력 프롬프트가 표시되지 않도록 ssh에 공개 키 인증을 사용하고 있습니다).

[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는 응용 프로그램과 상호 작용하는 것이 좋습니다.

그러나 단순히 SSH를 원하는 몇 가지 명령을 실행하면, 난 당신이 터미널과 상호 작용하는 경우처럼, Paramiko