【发布时间】:2014-08-06 11:28:02
【问题描述】:
我有一个 Python 脚本,我在其中登录 Cisco 设备并希望将命令的输出打印到文件中。
我的输出一切正常,但不确定如何将其打印到文件中。
这是我的登录代码,打印我需要的输出,然后注销。效果很好——我知道它不优雅:)
import pexpect
HOST = "172.17.1.1"
user = "username"
password = "password"
policymap = pexpect.spawn ('telnet '+HOST)
policymap.expect ('Username: ')
policymap.sendline (user)
policymap.expect ('Password: ')
policymap.sendline (password)
routerHostname = "switch1"
policymap.expect (routerHostname+'#')
policymap.sendline ('sh policy-map interface gi0/1\r')
print(policymap.readline())
policymap.expect (routerHostname+'#')
policymap.sendline ('exit\r')
print policymap.before
我尝试添加一个函数并将函数的输出打印到文件中,但我想我可能走错了路?
def cisco_output():
print policymap.before
filename = "policymap.txt"
target = open(filename, 'w')
target.write(cisco_output)
target.close()
【问题讨论】:
-
您使用的是哪个 Python 版本?您同时使用了
print和print(),这很不寻常。 -
您应该使用
with打开您的文件。