I'm attempting to write a script that pulls ip addresses from a file, connect to a network device at that ip address, run a "show run" against the device, export that config to a temp file, then parse the file for certain commands.
I'm trying to write a function so that I can pass the device ip address to the function, run the function, and exit. Then it moves on to the next device.
from netmiko import ConnectHandler
import getpass
import os.path
from ciscoconfparse import CiscoConfParse
import numpy as np
####Ask for username...will be displayed when typed
uname=input("Enter your username :")
###Ask for password...will not be displayed when typed
p = getpass.getpass(prompt="Enter your password: ")
###Ask for path to device list
filepath=("D:\Scripts\IOSDevices.csv")
hosts = open(filepath).read().splitlines()
#print (hosts) #verify host file is actually reading correctly
hostname = np.array(hosts)
print (hostname) #verify hosts are present in the array
def run_parseconfig():
pass
cf = open(".\tmp_file_conf.txt", "w+")
#Connect to IOS devices
device = ConnectHandler(device_type='cisco_ios', ip=hostname, username=uname, password=p)
output = device.send_command("show run")
device.disconnect()
print (output)
cf.write (output + "\n")
parse = CiscoConfParse(".\tmp_file_conf.txt")
cf.close()
output = " "
hostname_objs = parse.find_objects("^hostname")
service_objs = parse.find_objects("^service")
#f = open(hostname+"_config.txt", "a+")
f = open("D:\Scripts\IOS-DEVICES.txt", "a+")
f.write ("**** " + hostname + " ****" +"\n\n")
for h_obj in hostname_objs:
print (h_obj.text)
f.write (h_obj.text +"\n")
h_obj = " "
for s_obj in service_objs:
print (s_obj.text)
f.write (s_obj.text +"\n")
s_obj = " "
f.write ("\n" + "**** End of " + hostname +"'s Commands" + "\n")
f.write ("\n")
f.close()
parse = " "
#for hostname in hosts
run_parseconfig()
Before I built the function, it would successfully run against the first device, then on the second, it would send the running config to a temp file but not parse it out. That's where the function came in.
You closed the
cf
file after parsing withCiscoConfParse
and you kept resetting the variables to empty strings which is unecessary. Try to always use context managers instead ofopen()
.close()
.I did some modifications to your original code, and the code is commented: