我正在尝试编写一个脚本,从文件中提取 IP 地址,连接到该 IP 地址的网络设备,对设备运行“显示运行”,将该配置导出到临时文件,然后解析该文件以确保命令。
我正在尝试编写一个函数,以便可以将设备 IP 地址传递给该函数,运行该函数并退出。然后它移动到下一个设备。
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()
在我构建这个函数之前,它会在第一个设备上成功运行,然后在第二个设备上,它将运行配置发送到一个临时文件,但不会将其解析出来。这就是函数的用武之地。