Inventory exporter bash script for Cisco 9200, 9300, 9500 devices

Cisco DNA center currently lacks a feature to export all inventory. You can’t export serial numbers for power supplies and network modules. This bash script is very simple and primitive, it connects to Cisco device via SSH and collects inventory data. If you have a lot of devices, this will take a lot of time. You need to modify this script for parallel ssh connections if you have more than 100 devices. For more info, read the script comments.

#!/bin/bash

# SSH credentials for Cisco devices
# For security reasons, make sure the user is read only capable
user=CiscoUsername
password=CiscoPassword

# Path to file where IPs of devices are stored (one IP per line)
file=devices.txt

# Mail settings
mailrelay="smtp=some.mail.server:25"
sender=no-reply@somedomain.com
mailto=some.user@somedomain.com
mailsubject="inventory bash exporter - C9K2,C9K3,C9K5 devices"

# Path to output file (exported inventory file)
results=results.txt

# Cleanup from before

rm -f "$results"

# Check if necessary files exist
if [ ! -f "$file" ]; then
    echo
    echo "ERROR: Missing file with IP addresses. Exiting ..."
    echo
    exit 1
fi

lines=$(cat $file)

for line in $lines
do
        # Connect to device, read hostname and append output to file. I filter hostname by "-SDA-", because each device
        # contains "-SDA-" in hostname, in my case. You need to modify this to your own needs.
        sshpass -p "$password" ssh -t -q -o ConnectTimeout=5 -o StrictHostKeyChecking=no -o UserKnownHostsFile=/dev/null\
        "$user"@"$line" 'show run | i hostname' | grep "\-SDA\-" | sed 's/=//g' | sed 's/\//g' | sed 's/ //g' >> "$results"

        # Connect to device, read inventory, filter output to get desired results (you can modify this to your own needs)
        # and append output to file. I filter out SFP modules, FAN trays, Stack modules.
        sshpass -p "$password" ssh -t -q -o ConnectTimeout=5 -o StrictHostKeyChecking=no -o UserKnownHostsFile=/dev/null\
        "$user"@"$line" 'show inventory' | grep PID | awk '{print $2,$7,$8}' | sed 's/ //g' | grep -v "," | sort | uniq | sed 's/SN:/,Serial:/g' |\
        grep -v "SFP\|FANTRAY\|FTRJ\|GLC\|FTLF\|STACK" >> "$results"

        printf "\n" >> "$results"
done
    # Send results to an email 
    echo "Export generated: $(date). See attachment." | mailx -r "$sender" -S "$mailrelay" -s "$mailsubject" -a "$results" -v "$mailto"
    echo
    # Send done message to console
    echo "Done, check "$results"! or email"
    echo

Leave a Reply

Your email address will not be published. Required fields are marked *