Reputation: 241
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()
Upvotes: 1
Views: 2342
Reputation: 490
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
Upvotes: 1