A common task for a system administrator is to program scripts to streamline routine tasks, one of which is often to inventory servers, OS versions, interfaces, IPs, software versions. In this article, we will focus on how to obtain the interfaces, MAC, and each of the IPs.
The script itself is quite self-explanatory, using certain libraries we can obtain all the necessary info:
#! /usr/bin/python
import os
import sys
import socket
from netifaces import interfaces, ifaddresses, AF_INET, AF_LINK
from IPy import IP
hostname = socket.gethostname()
print "-------------------------------"
print "Analyzing Host: " + hostname
print "-------------------------------"
print " "
print "--- Interface List: ---"
for ifaceName in interfaces():
# Check Vlan Config
if ifaceName.count("."):
(iface, vlan) = ifaceName.split(".")
else:
iface = ifaceName
vlan = "None"
# Check MAC in device
if AF_LINK in ifaddresses(ifaceName):
mac = ifaddresses(ifaceName)[AF_LINK][0]['addr']
else:
mac = "None"
# Check IP Address and print them!!
if AF_INET in ifaddresses(ifaceName):
for address in ifaddresses(ifaceName)[AF_INET]:
type = IP(address['addr']).iptype()
netmask = address['netmask']
print "-- Interface: " + str(iface)
print " ++ MAC: " + mac
print " ++ VLAN: " + vlan
print " ++ IP: " + address['addr']
print " ++ Netmask: " + netmask
print " ++ Type " + type
else:
print "-- Interface: " + str(iface)
print " ++ MAC: " + mac
print " ++ VLAN: " + vlan
print " "