Возврат нескольких серийных номеров с устройств Cisco - PullRequest
1 голос
/ 10 апреля 2019

Я анализирую команду show version для получения ряда информации. Может быть, есть какой-то более простой способ, но я пытаюсь вернуть все серийные номера для устройств в стеке. В настоящее время я получаю только серийный номер активных коммутаторов. Также мне нужно искать в нескольких областях серийный номер. И ID платы процессора, и системный серийный номер.

Я проверял следующие строки Regex на https://regex101.com, . *? ^ System \ sSerial \ sNumber \ s ^ Серийный номер системы \ s ([^,] +)

Но в моем коде они, похоже, не работают. Когда я печатаю свою переменную, она отображается пустой для всех итераций цикла For.

#!/usr/bin/python

from getpass import getpass
import netmiko
import re

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):
    #with does all the cleanup and prework of file open for you
    with open(file_name, 'r') as in_file:
        for line in in_file:
            #this is probably supposed to be lineips = get_ip(line)
            #line = get_ip(line)
            lineips = get_ip(line)
        for ip in lineips:
            ips.append(ip)

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

def to_doc_w(file_name, varable):
    f=open(file_name, 'w', newline="\n")
    f.write(str(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('IPs.txt')

#list where informations will be stored
#devices = []
#Results string storage
strresults = ""

#Prompt user for account info
username = input("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:
    #Connect to a device
    net_connect = make_connection(ip, username, password)
    #Run a command and set that to output
    output = net_connect.send_command('show version')

    #finding hostname in output using regular expressions
    regex_hostname = re.compile(r'(\S+)\suptime')
    hostname = regex_hostname.findall(output)

    #finding uptime in output using regular expressions
    regex_uptime = re.compile(r'\S+\suptime\sis\s(.+)')
    uptime = regex_uptime.findall(output)

    #finding version in output using regular expressions
    regex_version = re.compile(r'Cisco\sIOS\sSoftware.+Version\s([^,]+)')
    version = regex_version.findall(output)

    #finding serial in output using regular expressions
    regex_serial = re.compile(r'Processor\sboard\sID\s(\S+)')
    serial = regex_serial.findall(output)

    #finding serial in output using regular expressions
    regex_serial2 = re.compile(r'^System Serial Number\s([^,]+)')
    serial2 = regex_serial2.findall(output)
    print(serial2)

    #finding ios image in output using regular expressions
    #regex_ios = re.compile(r'System\s\image\s\file\sis\s"([^ "]+)')
    #ios = regex_ios.findall(output)

    #finding model in output using regular expressions
    regex_model = re.compile(r'[Cc]isco\s(\S+).*memory.')
    model = regex_model.findall(output)

    #append results to table [hostname,uptime,version,serial,ios,model]
    #devices.append([hostname[0], uptime[0], version[0], serial[0], 
    #model[0]])

    results = (ip, hostname, version, serial, serial2, model)
    #Store results for later, reduce calls to append file, greatly i 
    #ncrease performance
    strresults = strresults + str(results) + "\n"
    #Next we will append the output to the results file
    #to_doc_a(file_name, results)
to_doc_w(file_name, strresults)

Независимо от того, какое устройство Cisco я хотел бы, чтобы он вытягивал серийный номер, и если в стеке есть несколько устройств, возвращаются все серийные номера для устройств в стеке. Также он должен вернуть IP, имя хоста, версию кода и модель.

1 Ответ

0 голосов
/ 11 апреля 2019

Для системного серийного номера ваш шаблон ^System Serial Number\s([^,]+) использует якорь для подтверждения начала строки, начинается с верхнего регистра Serial Number и пропускает двоеточие : после номера.

Вы можетеобновите свой шаблон, где (\S+) захватывает в группе, совпадающей 1+ раз, с непропущенным символом.В вашем паттерне вы используете [^,]+, чтобы соответствовать не запятой, но это также соответствует пробелу или символу новой строки.

System serial number:\s(\S+)

Regex demo | Демо Python

Добро пожаловать на сайт PullRequest, где вы можете задавать вопросы и получать ответы от других членов сообщества.
...