scripts/gestion/hptools2/mac.py
2015-08-22 05:18:22 +02:00

93 lines
2.8 KiB
Python

#!/bin/bash /usr/scripts/python.sh
# -*- coding: utf-8 -*-
#
# This file is free software; you can redistribute it and/or modify
# it under the terms of the GNU General Public License as published by
# the Free Software Foundation; either version 2 of the License, or
# (at your option) any later version.
#
# This file is distributed in the hope that it will be useful,
# but WITHOUT ANY WARRANTY; without even the implied warranty of
# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
# GNU General Public License for more details.
#
# You should have received a copy of the GNU General Public License
# along with this program; if not, write to the Free Software
# Foundation, Inc., 59 Temple Street #330, Boston, MA 02111-1307, USA.
"""Contient les outils pour manipuler des adresses MAC
dans le module hptools"""
import binascii
import netaddr
def bin_to_mac(raw):
"""Convertit une OctetString en une MAC"""
return format_mac(binascii.hexlify(raw))
def format_mac(raw):
"""Formatte la mac en aa:bb:cc:dd:ee:ff"""
return str(netaddr.EUI(raw)).replace('-', ':').lower()
class MACFactory(object):
"""Factory stockant les macs"""
__macs = {}
@classmethod
def register_mac(cls, mac, parent=None):
"""Enregistre une mac dans la factory et
retourne une instance de MACAddress si besoin."""
if cls.__macs.get(mac, None) is None:
cls.__macs[mac] = MACAddress(mac, parent)
else:
cls.__macs[mac].append_parent(parent)
return cls.__macs[mac]
@classmethod
def get_mac(cls, mac):
"""Récupère une mac dans la factory"""
return cls.__macs.get(mac, None)
@classmethod
def get_macs(cls):
"""Récupère l'ensemble des MACS de la factory"""
return cls.__macs
class MACAddress(object):
"""Classe représentant une adresse MAC"""
def __init__(self, value, parent=None):
"""Stocke l'adresse mac quelque part et le parent"""
self.__value = value
if parent is not None:
self.__parents = {parent.name() : parent}
@property
def value(self):
"""Property pour lire la valeur d'une MAC"""
return self.__value
@property
def parents(self):
"""Retourne les parents"""
return self.__parents
def append_parent(self, parent):
"""Ajoute un parent à la MAC si parent n'est pas None"""
if parent is not None:
if self.__parents.get(parent.name(), None) is None:
self.__parents[parent.name()] = parent
def remove_parent(self, parent):
"""Retire le parent référencé à la MAC"""
if parent is not None:
if self.__parents.get(parent.name(), None) is not None:
_ = self.__parents.pop(parent.name())