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 [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
There are just tow commands in the mylog1.txt file.Why?
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] #
Collected from the Internet
Please contact [email protected] to delete if infringement.
Comments