Python | Crear archivo .csv con datos obtenidos mediante libreria NAPALM

import napalm

# Create a hosts file to include all the target IPs/hostnames that will be SSH'd.

f = open ("/home/eve/hosts")

# Create a .csv file and define all of the columns matching with NAPALM's "get_facts" output.

csv_columns=("FQDN;HOSTNAME;MODEL;OS VERSION;SERIAL NUMBER;UPTIME;VENDOR\n")
file= open("napalm.csv","w")
file.write(csv_columns)

# Create a python loop where it perform the following actions:
#   1. Create the "host" variable where we will extract each line of code on every iteration using strip()
#   2. Define the NAPALM's driver + SSH Username and Password 
#   3. Connect to each target host (via SSH)  using device.open()
#   4. Perform NAPAM's "get_facts" on the target host in order to get general data from the Cisco device in an "structured" way. This data is stored as a "Dictionary".
#   5. Take each key data (fqdn, hostname, serial_number...) from "getfacts" variable and store it on a separated variable. Note that the variable "get_uptime" was
#   converted into a string as integer concatenation with strings wasn't allowed on the next step.
#   6. Define the variable "getfacts_data" where we will join all the previous key variables in a csv format-style. Each iteration will add a new line of code on "napalm.csv"
#   with "get_facts" data retrieved on the target host
#   7. Close the file and the SSH sesion

for line in f:
    host = line.strip()
    driver = napalm.get_network_driver('ios')
    device = driver(hostname=host, username='cisco', password='cisco')
    device.open()
    getfacts = device.get_facts()
    get_fqdn = getfacts["fqdn"]
    get_hostname = getfacts["hostname"]
    get_model = getfacts["model"]
    get_osversion = getfacts["os_version"]
    get_serialnumber = getfacts["serial_number"]
    get_uptime = getfacts["uptime"]
    get_uptime_str = str(get_uptime)
    get_vendor = getfacts["vendor"]
    getfacts_data=(get_fqdn + ";" + get_hostname + ";" + get_model + ";" + get_osversion + ";" + get_serialnumber + ";" + get_uptime_str + ";" + get_vendor + "\n")
    file = open("napalm.csv", "a")
    file.write(getfacts_data)
    file.close
    device.close()

    # Open "napalm.csv" on Excel and you will see all the different key data on different columns

 

Comentarios

Entradas populares de este blog

EVE-NG: Instalación de EVE-NG

Fortigate: Capturar paquetes (Packet capture/sniffer)

Cisco ISE | Certificados SSL públicos para Guest Portal