captain yossarian
captain yossarian

Reputation: 457

Printing a output (a function?) to a file?

I have a script in Python where I login into a Cisco device and want to print the output of a command to a file.

I've got the output all OK, but not sure how I go about printing it into a file.

Here's my code which logs in, prints the output I need, and logs out. Works well -- I know it isn't elegant :)

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

I tried adding a function and printing the output of the function to the file, but I think I may be on the wrong track here?

def cisco_output():
        print policymap.before

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

Upvotes: 0

Views: 63

Answers (2)

lalsam
lalsam

Reputation: 31

with open("policymap.txt", "w") as f:
    print >>f, policymap.before

Upvotes: 1

user1907906
user1907906

Reputation:

Don't print inside the function but return what you want to save. Then call the function by appending () to the function name.

def cisco_output():
    return policymap.before

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

Upvotes: 2

Related Questions