打印输出(函数?)一个文件?

2024-04-26 13:45:41 发布

您现在位置:Python中文网/ 问答频道 /正文

我有一个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()

Tags: 文件函数脚本hosttargetpasswordciscoexpect
2条回答
with open("policymap.txt", "w") as f:
    print >>f, policymap.before

不要print在函数内部,而是return要保存的内容。然后在函数名后面加上(),调用函数。你知道吗

def cisco_output():
    return policymap.before

filename = "policymap.txt"
target = open(filename, 'w')
target.write(cisco_output())
target.close()

相关问题 更多 >