如何从* .txt文件读取IP地址并将ios show命令发送到CSV文件?

时间:2019-04-10 14:51:36

标签: python-2.7

我想创建一个从* .txt文件读取IP地址并执行一些cisco ios show命令的python脚本。 show命令的部分结果需要使用netmiko发送到CSV文件。 我没有任何编码背景,但是我设法用找到的片段创建了以下代码。 该脚本可以从* .txt文件读取IP地址,但无法连接到设备。

from getpass import getpass
import netmiko
import re
import time

def make_connection (ip, username, password):
        return netmiko.ConnectHandler(device_type='cisco_ios', ip=ip, username=username, password=password)

def get_ip (input):
     return(re.findall(r'(?:(?:25[0-5]|2[0-4][0-9]|[01]?[0-9][0-9]?).){3}(?:25[0-5]|2[0-4][0-9]|[01]?[0-9][0-9]?)', input))

def get_ips (file_name):
     for line in open(file_name, 'r').readlines():
        line = get_ip(line)
        for ip in line:
          ips.append(ip)

def to_doc_a(file_name, varable):
     f=open(file_name, 'a')
     f.write(varable)
     f.write('\r\n')
     f.close()

def to_doc_w(file_name, varable):
     f=open(file_name, 'w')
     f.write(varable)
     f.close()

#This will be a list of the devices we want to SSH to
ips = []
#Pull the IPs.txt is a list of the IPs we want to connect to
#This function pulls those IPs out of the txt file and puts them into a list
get_ips("vgw_ips.txt")

#Prompt user for account info
username = raw_input("Username: ")
print (username)
password = getpass()
file_name = "results.csv"
#Clearing all the old info out of the results.csv file
to_doc_w(file_name, "")



#Make a for loop to hit all the devices, for this we will be looking at the IOS it's running
for ip in ips:
    try:
    #Connect to a device
        net_connect = make_connection(ip, username, password)
    except Exception:
        pass
    print(ip)

#output version
output = net_connect.send_command("show ver | inc Cisco IOS Software")
output = output.split()
ver = (output[-4])
print(output[-4])

#output description
output = net_connect.send_command("show inv | inc DESCR")
output = output.split()
descr = (output[3]+ output[4])
print(output[3]+ output[4])

#output hostname
output = net_connect.send_command("show run | inc hostname")
output = output.split()
hostname = (output[1])
print(output[1])

results = ip+","+ver+","+descr+","+hostname
#Next we will append the output to the results file
to_doc_a(file_name, results)

0 个答案:

没有答案