我在Python中有一个脚本,我登录到思科设备并希望将命令输出打印到文件中。
我的输出都没问题,但不确定如何将其打印到文件中。
这是我登录的代码,打印出我需要的输出并注销。效果很好 - 我知道它不优雅:)
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()
答案 0 :(得分:2)
在函数内部print
但return
要保存的内容。然后通过将()
附加到函数名称来调用函数。
def cisco_output():
return policymap.before
filename = "policymap.txt"
target = open(filename, 'w')
target.write(cisco_output())
target.close()
答案 1 :(得分:1)
with open("policymap.txt", "w") as f:
print >>f, policymap.before