简体   繁体   中英

print and pexpect logging and reading the file

I am actually trying to write the commands and its output to a file and then read the file . The file is created , but for reading the file, it gives error as valueerror i/o operation. What am I missing here. ?

import pexpect
import time,sys
from StringIO import StringIO

telconn=pexpect.spawn('telnet 10.24.12.109')
telconn.logfile = sys.stdout
telconn.expect(":")
telconn.send("user" + "\r")
telconn.expect(":")
telconn.send("pass" + "\r\r\r\r\n\n\n")
telconn.expect("key to proceed.")
telconn.send ("\003")
telconn.expect("root>")
sys.stdout=open("test1.txt","w")

print "Telnet connection is done"

telconn.sendline('ls -al');
telconn.expect (['root>',pexpect.EOF])
ls = telconn.before

telconn.sendline('pwd');
telconn.expect (['root>',pexpect.EOF])
pwd = telconn.before

telconn.sendline('cli');
telconn.expect (['#',pexpect.EOF])
cli = telconn.before

telconn.sendline('\n\n');

telconn .sendline('exit');
telconn.close()

print ls
print pwd
print cli
print "Ended session"

sys.stdout.close()

sys.stdout = open("test1.txt", "r+")
str = sys.stdout.read();
print "Read String is : ", str
# Close opend file

print "Read String is : ", str
sys.stdout.close()

edit (OP wants system call prints to file):

Save the standard output to some temp var, so just add:

prev_std = sys.stdout

before you do sys.stdout=open("test1.txt","w") .

After you are done and closed sys.stdout , restore the original one:

sys.stdout = prev_std

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM