#!/bin/bash /usr/scripts/python.sh # -*- coding: utf-8 -*- # # locate_mac.py - permet de tracer une mac sur le réseau. # Ignore les switches spéciaux et cachés, ainsi que les ports # d'uplink. # # Pierre-Elliott Bécue # # 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. import sys from lc_ldap import shortcuts, printing from gestion.config.encoding import out_encoding from gestion.hptools2 import tools from gestion import annuaires_pg def get_chambres(mac): """Récupère la liste des chambres dans lesquelles mac se trouve""" # hptools2 retourne un tuple avec en premier élément la mac # et en second élément la liste des ports sur lesquels la mac # est vue. trace_mac appelle annuaires_pg.all_switchs(), qui # ignore les switches spéciaux et cachés. De plus, on ignore # les prises uplink mac_ports_tuple = tools.trace_mac(mac, in_all_switches=True) if mac_ports_tuple is None: return None ports = mac_ports_tuple[1] chambres = [] for port in ports: bat = port.name()[0] prise_num = port.name()[1:] # Ne retourne que la chambre, pas le bâtiment. try: chbre_locale = annuaires_pg.reverse(bat, prise_num)[0] # Si pas de correspondance, il s'agit d'une machine crans avec attribu prise ou d'une mac inconnue except IndexError: chbre_locale = prise_num pass # Donc on ajoute le bâtiment chambres.append("%s%s" % (bat.upper(), chbre_locale)) return chambres def fetch_db(chambres): """Récupère dans la base LDAP les infos sur les proprios des chambres""" if chambres is None: return [] ldap_conn = shortcuts.lc_ldap_readonly() # On évite de multiplier les requêtes à LDAP ldap_filter = u"" for chambre in chambres: ldap_filter += u"(chbre=%s)" % (chambre,) ldap_filter += u"(prise=%s)" % (chambre,) ldap_filter = u"(|%s)" % (ldap_filter,) results = ldap_conn.search(ldap_filter) return results if __name__ == '__main__': MAC = tools.format_mac(sys.argv[1]) # On trace la MAC et récupère les chambres CHAMBRES = get_chambres(MAC) # Via LDAP, on trouve les propriétaires PROPRIOS = fetch_db(CHAMBRES) # On se fiche des détails, on veut juste savoir chez qui on tombe # sprint affiche entre autres la chambre du priorio print printing.sprint_list(PROPRIOS).encode(out_encoding)