我在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()
不要print
在函数内部,而是return
要保存的内容。然后通过附加到函数名称来调用该函数()
。
def cisco_output():
return policymap.before
filename = "policymap.txt"
target = open(filename, 'w')
target.write(cisco_output())
target.close()
本文收集自互联网,转载请注明来源。
如有侵权,请联系[email protected] 删除。
我来说两句