简体   繁体   English

打印并预期日志记录并读取文件

[英]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. 文件已创建,但为了读取文件,它会以valueerror I / O操作的形式给出错误。 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): 编辑(OP要系统调用打印到文件):

Save the standard output to some temp var, so just add: 将标准输出保存到一些临时变量中,因此只需添加:

prev_std = sys.stdout

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

After you are done and closed sys.stdout , restore the original one: 完成并关闭sys.stdout ,还原原始的一个:

sys.stdout = prev_std

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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