Commit e14e382d authored by Benjamin Graillot's avatar Benjamin Graillot

Ajout d'un script pour afficher les MACs sur un switch

parent 8f9caaad
#!/usr/bin/python3
import argparse
import sys
from pysnmp.hlapi import *
hpSwitchPortFdbAddress = '1.3.6.1.4.1.11.2.14.11.5.1.9.4.2.1.2'
class HPSwitch:
def __init__(self, host):
self.host = host
self.session = None
def walk(self, attribute):
iterator = nextCmd(
SnmpEngine(),
CommunityData('public'),
UdpTransportTarget((self.host, 161)),
ContextData(),
ObjectType(ObjectIdentity(*attribute)),
lexicographicMode=False
)
values = []
try:
while True:
errorIndication, errorStatus, errorIndex, varBinds = next(iterator)
if errorIndication:
print(errorIndication)
elif errorStatus:
print('%s at %s' % (errorStatus.prettyPrint(), errorIndex and varBinds[int(errorIndex) - 1][0] or '?'))
for varBind in varBinds:
values.append(varBinds)
except StopIteration:
pass
return values
def get_macs(self):
macs = {}
for mac in self.walk((hpSwitchPortFdbAddress,)):
oib = mac[0][0].getOid().asTuple()
value = mac[0][1].asNumbers()
value = ':'.join(['{:02x}'.format(n) for n in value])
port = oib[17]
if port in macs:
macs[port].append(value)
else:
macs[port] = [value]
return macs
def get_macs_on_port(self, port):
macs = []
for mac in self.walk((hpSwitchPortFdbAddress+'.'+str(port),)):
value = mac[0][1].asNumbers()
value = ':'.join(['{:02x}'.format(n) for n in value])
macs.append(value)
return macs
if __name__ == '__main__':
parser = argparse.ArgumentParser(description="Afficher les MACs sur les ports d'un switch")
parser.add_argument('-p', '--port', help='Traiter uniquement le port PORT.', type=int, default=None)
parser.add_argument('switch', help='Nom du switch à contacter.', type=str)
args = parser.parse_args()
s = HPSwitch(args.switch)
if args.port:
macs = s.get_macs_on_port(args.port)
print('Port', args.port, ':', macs)
else:
macs = s.get_macs()
for port in sorted(macs.keys()):
print('Port', port, ':', macs[port])
Markdown is supported
0% or
You are about to add 0 people to the discussion. Proceed with caution.
Finish editing this message first!
Please register or to comment