From 7428178ab9f0d43529b44c0de1e8051880aa538d Mon Sep 17 00:00:00 2001 From: glondu Date: Sun, 26 Mar 2006 18:00:11 +0200 Subject: [PATCH] Dans affich_tools, tableau_ng remplace dornavant tableau. darcs-hash:20060326160011-68412-d87c57d6e2edf22dd78fd5c78e07793a19421ff5.gz --- admin/controle_tresorier.py | 27 +++++++----- gestion/affich_tools.py | 79 ++++++++---------------------------- gestion/whos.py | 46 ++++++++++++++------- surveillance/analyse.py | 14 +++---- surveillance/statistiques.py | 58 +++++++++++++------------- 5 files changed, 101 insertions(+), 123 deletions(-) diff --git a/admin/controle_tresorier.py b/admin/controle_tresorier.py index c9741ed4..d4752ca3 100755 --- a/admin/controle_tresorier.py +++ b/admin/controle_tresorier.py @@ -171,11 +171,12 @@ def controle_interactif(quoi): okc, nokc =_controle_interactif_clubs(todo_list['club']) print coul(u'\nRécapitulatif des nouveaux contrôles +%s :' % quoi, 'violet') - liste = [(u'Catégorie', u'OK', u'pas OK'), - (u'adhérents', str(oka), str(noka))] + liste = [[u'adhérents', str(oka), str(noka)]] if quoi == 'p': - liste.append((u'clubs', str(okc), str(nokc))) - print tableau([15, 10, 10], liste) + liste.append([u'clubs', str(okc), str(nokc)]) + print tableau(liste, + titre = [u'Catégorie', u'OK', u'pas OK'], + largeur = [15, 10, 10]) def formater_pour_cableur(liste): @@ -183,15 +184,18 @@ def formater_pour_cableur(liste): Formate la liste d'adhérents ou de clubs avec les dates correspondantes. liste est une liste de couples (date, objet). """ - lignes = [(u'id', u'Nom', u'Date Heure')] + lignes = [] total = 0 liste.sort(lambda x, y: cmp(x[1].nom(), y[1].nom())) for date, a in liste: - lignes.append((a.id(), a.Nom(), date)) + lignes.append([a.id(), a.Nom(), date]) total += 1 - return tableau([6, 40, 18], lignes) + u'\nTotal : %d' % total + return tableau(lignes, + titre = [u'id', u'Nom', u'Date Heure'], + largeur = [6, 40, 18], + alignement = ['d', 'c', 'c']) + u'\nTotal : %d' % total def formater_pour_bureau(dico): @@ -199,17 +203,20 @@ def formater_pour_bureau(dico): Formate la liste d'adhérents ou de clubs avec les câbleurs correspondantes pour le mail récapitulatif envoyé à bureau. """ - lignes = [(u'id', u'Nom', u'Câbleur', u'Date')] + lignes = [] total = 0 liste = dico.keys() liste.sort() for cableur in liste: for date, a in dico[cableur]: - lignes.append((a.id(), a.Nom(), cableur, date)) + lignes.append([a.id(), a.Nom(), cableur, date]) total += 1 - return tableau([6, 40, 18, 18], lignes) + u'\nTotal : %d' % total + return tableau(lignes, + titre = [u'id', u'Nom', u'Câbleur', u'Date'], + largeur = [6, 40, 18, 18], + alignement = ['d', 'c', 'c', 'c']) + u'\nTotal : %d' % total def qui(historique, quoi): diff --git a/gestion/affich_tools.py b/gestion/affich_tools.py index 83c14a7d..bf191994 100755 --- a/gestion/affich_tools.py +++ b/gestion/affich_tools.py @@ -86,62 +86,17 @@ ERREUR = coul('ERREUR','rouge') def cprint(txt,col): print coul(txt,col) -def tableau(largeurs,data) : - """ - retourne une chaine formatée repésentant un tableau - largeur est la liste des largeurs des colones - data est une liste de tuples : - [ ( données entète), (données ligne1), .... ] - """ - sep_col = u'|' - # Si l'une des largeurs est '*', alors on la met la plus grande possible - if '*' in largeurs: - rows, cols = get_screen_size() - nlargeurs = [] - for n in largeurs: - if n != '*': - nlargeurs.append(n) - else: - nlargeurs.append(max(cols - sum(filter(lambda x:x!='*',largeurs)) - len(largeurs) - 1, 3)) - largeurs = nlargeurs - - # Ligne de séparation entète corps - s=u'\n' - for l in largeurs : - s+= sep_col + u'-'*l - s += sep_col + u'\n' - - nb_cols = len(largeurs) - - # Remplissage tableau - f=u'' - for ligne in data : - for i in range(0, nb_cols) : - f+= sep_col - # Centrage - l = len(sre.sub('\x1b\[1;([0-9]|[0-9][0-9])m','',ligne[i])) # Longeur sans les chaines de formatage - if l >= largeurs[i] : - f += ligne[i] - else : - n = largeurs[i] - l - f += u' '*(n/2) + ligne[i] + u' '*(n/2 + n%2) - f+= sep_col + u'\n' - - # Final - f = f.replace(u'\n',s,1) # Insertion du séparateur entète - corps - return f[:-1] # Supression du \n final - -def tableau_ng(data,titre=None,largeur=None,alignement=None,format=None) : +def tableau(data, titre=None, largeur=None, alignement=None, format=None): """ - Retourne une chaine formatée repésentant un tableau + Retourne une chaine formatée repésentant un tableau. - data : liste de listes, chacune contenant les valeurs d'une ligne + data : liste de listes, chacune contenant les valeurs d'une ligne - titre : liste des titres + titre : liste des titres Si none, n'affiche pas de ligne de titre - largeur : liste des largeurs des colonnes, '*' met la plus grande + largeur : liste des largeurs des colonnes, '*' met la plus grande largeur possible. Si None, réduit aux max chaque colonne @@ -150,7 +105,7 @@ def tableau_ng(data,titre=None,largeur=None,alignement=None,format=None) : d = droit Si None, met c pour chaque colonne - format : liste des formats : s = string + format : liste des formats : s = string o = octet Si None, s pour chaque colonne """ @@ -167,20 +122,20 @@ def tableau_ng(data,titre=None,largeur=None,alignement=None,format=None) : if not format : format = ['s'] * nbcols - def reformate (data, format) : - if format == 's' : - return str(data) + def reformate(data, format): + if format == 's': + return unicode(data) elif format == 'o' : data = float(data) - if data > 1024**3 : - return str(round(data/1024**3,1))+'Go' - elif data > 1024**2 : - return str(round(data/1024**2,1))+'Mo' - elif data > 1024 : - return str(round(data/1024,1))+'ko' - else : - return str(round(data,1))+'o' + if data > 1024**3: + return str(round(data/1024**3, 1)) + 'Go' + elif data > 1024**2: + return str(round(data/1024**2, 1)) + 'Mo' + elif data > 1024: + return str(round(data/1024, 1)) + 'ko' + else: + return str(round(data, 1)) + 'o' data = [ [ reformate(ligne[i],format[i]) for i in range(nbcols) ] for ligne in data ] diff --git a/gestion/whos.py b/gestion/whos.py index a6ca6a22..0b2bb83b 100755 --- a/gestion/whos.py +++ b/gestion/whos.py @@ -107,7 +107,7 @@ def adhers_brief(adhers) : * chambre * machines """ - data = [ ( u'aid' , u'Prénom Nom' , u'Chbre', u'P', u'C', u'Machines' ) ] + data = [] for a in adhers : ## Etat administratif @@ -140,12 +140,15 @@ def adhers_brief(adhers) : else : machines = coul(nom,k) # Données - data.append((a.id() , a.Nom(), a.chbre(),paid,carte,machines )) + data.append([a.id(), a.Nom(), a.chbre(), paid, carte, machines]) return u"Machines en rouge = machines avec limitation de services\n" + \ u"P : paiement année en cours, le fond vert indique le précâblage\n" + \ u"C : carte d'étudiant année en cours\n" + \ - tableau([5, 30 , 5, 1, 1, '*'], data) + tableau(data, + titre = [u'aid', u'Prénom Nom', u'Chbre', u'P', u'C', u'Machines'], + largeur = [5, 30, 5, 1, 1, '*'], + alignement = ['d', 'c', 'g', 'c', 'c', 'c']) def machines_brief(machines) : """ @@ -157,7 +160,7 @@ def machines_brief(machines) : * adresse MAC * si blacklistée """ - data = [ ( u'mid' , u'Type', u'Nom de machine', u'Propriétaire', u'Chbre', u'Limitation' ) ] + data = [] for m in machines : t, bl = __bases_machines(m) @@ -171,10 +174,13 @@ def machines_brief(machines) : p = coul(p,'rouge') # Données - data.append((m.id() , t, m.nom().split('.')[0], p, a.chbre(), bl)) + data.append([m.id() , t, m.nom().split('.')[0], p, a.chbre(), bl]) return u"Le propriétaire en rouge signale un problème administratif\n" + \ - tableau([5, 4, 18, '*', 5, 10], data) + tableau(data, + titre = [u'mid', u'Type', u'Nom de machine', u'Propriétaire', u'Chbre', u'Limitation'], + largeur = [5, 4, 18, '*', 5, 10], + alignement = ['d', 'c', 'c', 'c', 'g', 'c']) def clubs_brief(clubs) : """ @@ -184,7 +190,7 @@ def clubs_brief(clubs) : * local * machines """ - data = [ ( u'cid' , u'Nom ', u'Local',u'P', u'Responsable', u'Machines' ) ] + data = [] for c in clubs : ## Etat administratif @@ -213,11 +219,14 @@ def clubs_brief(clubs) : resp = c.responsable().Nom() # Données - data.append((c.id() , c.Nom(), c.local(),paid, resp, machines )) + data.append([c.id() , c.Nom(), c.local(), paid, resp, machines]) return u"Machines en rouge = machines avec limitation de services\n" + \ u"P : signature charte année en cours, le fond vert indique le précâblage\n" + \ - tableau([5, '*' , 6, 1, 21, 15], data) + tableau(data, + titre = [u'cid', u'Nom ', u'Local', u'P', u'Responsable', u'Machines'], + largeur = [5, '*', 6, 1, 21, 15], + alignement = ['d', 'c', 'g', 'c', 'c', 'c']) def list_machines(machines) : @@ -230,15 +239,18 @@ def list_machines(machines) : * adresse MAC * si blacklistée """ - data = [ ( u'mid' , u'Type', u'Nom de machine', u'Adresse IP', u'Adresse MAC', u'Limitation' ) ] + data = [] for m in machines : t, bl = __bases_machines(m) # Données - data.append((m.id() , t, m.nom().split('.')[0], m.ip(), m.mac(), bl)) + data.append([m.id(), t, m.nom().split('.')[0], m.ip(), m.mac(), bl]) - return tableau([5, 4, '*', 17, 19, 10], data) + return tableau(data, + titre = [u'mid', u'Type', u'Nom de machine', u'Adresse IP', u'Adresse MAC', u'Limitation'], + largeur = [5, 4, '*', 17, 19, 10], + alignement = ['d', 'c', 'c', 'c', 'c', 'c']) def list_bornes(bornes) : """ @@ -252,7 +264,7 @@ def list_bornes(bornes) : * canal * lieu (la première remarque en fait) """ - data = [ ( u'mid' , u'Nom', u'Adresse IP', u'Adresse MAC', u'E', u'Can' , u'P', u'Pris', u'Lieu') ] + data = [] ok = u'\x1b[1;32mu\x1b[1;0m' nok = u'\x1b[1;31md\x1b[1;0m' @@ -278,9 +290,13 @@ def list_bornes(bornes) : else : puiss = b.puissance() - data.append((b.id() , b.nom().split('.')[0], b.ip(), b.mac(), etat, b.canal(), puiss, b.prise(),l )) + data.append([b.id(), b.nom().split('.')[0], b.ip(), b.mac(), etat, b.canal(), puiss, b.prise(), l]) - return u"Can=canaux, P=puissance, E=état\n" + tableau([4, 13, 15, 17, 1, 5, 3, 4, '*'], data) + return u"Can=canaux, P=puissance, E=état\n" + \ + tableau(data, + titre = [u'mid', u'Nom', u'Adresse IP', u'Adresse MAC', u'E', u'Can', u'P', u'Pris', u'Lieu'], + largeur = [5, 13, 15, 17, 1, 5, 3, 4, '*'], + alignement = ['d', 'c', 'c', 'c', 'c', 'c', 'c', 'g', 'c']) def adher_details(adher) : """ diff --git a/surveillance/analyse.py b/surveillance/analyse.py index dbb46324..4034dd31 100755 --- a/surveillance/analyse.py +++ b/surveillance/analyse.py @@ -5,9 +5,9 @@ import socket import sys, re from pyPgSQL import PgSQL sys.path.append('/usr/scripts/gestion/') -from affich_tools import tableau_ng +from affich_tools import tableau -def stats (ip_crans=[], ip_ext=[], show=['ip_crans','ip_ext','port_crans','port_ext'], upload_mini=0, show_limit=10, begin_time=24, end_time=0): +def stats(ip_crans=[], ip_ext=[], show=['ip_crans','ip_ext','port_crans','port_ext'], upload_mini=0, show_limit=10, begin_time=24, end_time=0): """ Retourne une chaine de caratères formatée avec le tableau de statistiques d'upload de l'ip fourni @@ -91,16 +91,16 @@ def stats (ip_crans=[], ip_ext=[], show=['ip_crans','ip_ext','port_crans','port_ # on modifie les ip en noms de machine et les ports en noms def nom_de_machine (ip) : - try : + try: return socket.gethostbyaddr(ip)[0] - except : + except: return ip port_to_service = {} for service,port in [ re.split('[ \t]+',x.strip().replace('/tcp','').replace('/udp',''))[:2] for x in open('/etc/services').readlines() if x[0] not in ['\n','#'] ] : port_to_service[port]=service - for champ in select : + for champ in select: if champ == 'ip_ext': col = select.index(champ) results = [ x[:col] + [nom_de_machine(x[col])] + x[col+1:] for x in results ] @@ -113,7 +113,7 @@ def stats (ip_crans=[], ip_ext=[], show=['ip_crans','ip_ext','port_crans','port_ col = select.index(champ) results = [ x[:col] + [port_to_service.get(x[col],x[col])] + x[col+1:] for x in results ] - return tableau_ng(results, titre=titre, largeur=largeur, alignement=alignement, format=format) + return tableau(results, titre=titre, largeur=largeur, alignement=alignement, format=format) if __name__ == '__main__' : @@ -261,5 +261,5 @@ Exemples : # affichage du résultat ####################### #print stats(ip_crans, group, upload_mini, limit, heures) - print stats (ip_crans, ip_ext, show, upload_mini, limit, begin_time, end_time) + print stats(ip_crans, ip_ext, show, upload_mini, limit, begin_time, end_time) diff --git a/surveillance/statistiques.py b/surveillance/statistiques.py index a96915b2..de1db039 100755 --- a/surveillance/statistiques.py +++ b/surveillance/statistiques.py @@ -22,7 +22,7 @@ import smtplib import socket import time, random, md5 from analyse import stats -from affich_tools import tableau_ng +from affich_tools import tableau from ldap_crans import AssociationCrans ############################### @@ -44,22 +44,22 @@ mail = smtplib.SMTP('localhost') ##################### requete = "SELECT ip_crans,sum(upload) as somme,sum(download) FROM upload WHERE ip_crans IN (SELECT ip_crans FROM avertis_upload where hard='1' or soft='1') and date > timestamp 'now' - interval '1 day' GROUP BY ip_crans ORDER BY somme DESC" curseur.execute(requete) -liste_upload = tableau_ng(data = [ [l[1], l[2], socket.gethostbyaddr(str(l[0]))[0]] for l in curseur.fetchall() ], - titre = ['upload', 'download', 'machine'], - largeur = [10, 10, 30], - format = ['o', 'o', 's'], - alignement = ['d', 'd', 'c']).encode('iso-8859-15') +liste_upload = tableau(data = [ [l[1], l[2], socket.gethostbyaddr(str(l[0]))[0]] for l in curseur.fetchall() ], + titre = ['upload', 'download', 'machine'], + largeur = [10, 10, 30], + format = ['o', 'o', 's'], + alignement = ['d', 'd', 'c']).encode('iso-8859-15') # Traffic exempté : ################### requete = "SELECT ip_crans,sum(upload) AS somme , sum(download) FROM upload WHERE ip_crans IN ( SELECT ip_crans from exemptes) and date > timestamp 'now' - interval '1 day' GROUP BY ip_crans ORDER BY somme DESC" curseur.execute(requete) -liste_exemptes = tableau_ng(data = [ [l[1], l[2], socket.gethostbyaddr(str(l[0]))[0] ] for l in curseur.fetchall() ], - titre = ['upload', 'download', 'machine'], - largeur = [10, 10, 30], - format = ['o', 'o', 's'], - alignement = ['d', 'd', 'c']).encode('iso-8859-15') +liste_exemptes = tableau(data = [ [l[1], l[2], socket.gethostbyaddr(str(l[0]))[0] ] for l in curseur.fetchall() ], + titre = ['upload', 'download', 'machine'], + largeur = [10, 10, 30], + format = ['o', 'o', 's'], + alignement = ['d', 'd', 'c']).encode('iso-8859-15') # Upload des serveurs : @@ -75,11 +75,11 @@ for i in (10,1,3,4,7,8,9,11): continue liste_serveurs.append([traffic[0],traffic[1],hostname]) -liste_serveurs = tableau_ng( data = liste_serveurs, - titre = ['upload','download','serveur'], - largeur = [10, 10, 30], - format = ['o','o','s'], - alignement = ['d','d','c']).encode('iso-8859-15') +liste_serveurs = tableau(data = liste_serveurs, + titre = ['upload','download','serveur'], + largeur = [10, 10, 30], + format = ['o','o','s'], + alignement = ['d','d','c']).encode('iso-8859-15') # statistiques des gros uploads depuis les serveurs @@ -103,7 +103,7 @@ for IP in infections: continue liste_virus.append(["%s" % (str(hostname))]) -liste_virus = tableau_ng(liste_virus, titre=['machine'], largeur=[30]).encode('iso-8859-15') +liste_virus = tableau(liste_virus, titre=['machine'], largeur=[30]).encode('iso-8859-15') # Machines ayant fait des attaques virus dans la journée : ########################################################## @@ -113,10 +113,10 @@ liste_virus2 = [] for IP, compteur in curseur.fetchall(): hostname = socket.gethostbyaddr(IP)[0] liste_virus2.append([hostname, compteur]) -liste_virus2 = tableau_ng(data = liste_virus2, - titre = ['machine', 'nombre'], - largeur = [30, 12], - alignement = ['c', 'd']).encode('iso-8859-15') +liste_virus2 = tableau(data = liste_virus2, + titre = ['machine', 'nombre'], + largeur = [30, 12], + alignement = ['c', 'd']).encode('iso-8859-15') # Machines ayant fait de attaques flood dans la journée : @@ -127,10 +127,10 @@ liste_virus3 = [] for IP, compteur in curseur.fetchall(): hostname = socket.gethostbyaddr(IP)[0] liste_virus3.append([hostname, compteur]) -liste_virus3 = tableau_ng(data = liste_virus3, - titre = ['machine', 'nombre'], - largeur = [30, 12], - alignement = ['c', 'd']).encode('iso-8859-15') +liste_virus3 = tableau(data = liste_virus3, + titre = ['machine', 'nombre'], + largeur = [30, 12], + alignement = ['c', 'd']).encode('iso-8859-15') # Machines ayant utilisé des protocoles P2P dans la journée : @@ -161,10 +161,10 @@ for IP, protocole, compteur, blackliste in curseur.fetchall(): '*%d*' % config.p2p.limite[protocole]]) else: liste_p2p.append([hostname, protocole, compteur, config.p2p.limite[protocole]]) -liste_p2p = tableau_ng(data = liste_p2p, - titre = ['machine', 'protocole', 'nombre', 'limite'], - largeur = [32, 14, 10, 8], - alignement = ['c', 'c', 'd', 'd']).encode('iso-8859-15') +liste_p2p = tableau(data = liste_p2p, + titre = ['machine', 'protocole', 'nombre', 'limite'], + largeur = [32, 14, 10, 8], + alignement = ['c', 'c', 'd', 'd']).encode('iso-8859-15')