From d0ba7705d9f3f45e2886d36be26388a3e89fcca8 Mon Sep 17 00:00:00 2001 From: pauget Date: Sun, 12 Sep 2004 01:24:57 +0200 Subject: [PATCH] Nouveau systme de destruction d'objets. darcs-hash:20040911232457-41617-acc80a0d56d11a346497d0aef68fd4b5c0b13a00.gz --- gestion/config.py | 5 +-- gestion/gen_confs/generate.py | 73 +++++++++++++++++++++++++++++----- gestion/ldap_crans.py | 75 ++++++++++++++++++++--------------- gestion/whos.py | 11 +++-- 4 files changed, 114 insertions(+), 50 deletions(-) diff --git a/gestion/config.py b/gestion/config.py index ec5386f8..8cefeed3 100644 --- a/gestion/config.py +++ b/gestion/config.py @@ -25,9 +25,8 @@ dat = localtime() if dat[1]<9 : ann_scol = dat[0]-1 else : ann_scol = dat[0] -## Quelques fichiers -# Log des destructions de machines ou d'adhérents -delete_log = '/tmp/delete.log' +## Répertoire de stoquage des objets détruits +cimetiere = '/home/cimetiere' ############################# ## Paramètres des machines ## diff --git a/gestion/gen_confs/generate.py b/gestion/gen_confs/generate.py index 91faab0b..dc2df1ca 100755 --- a/gestion/gen_confs/generate.py +++ b/gestion/gen_confs/generate.py @@ -1,14 +1,14 @@ #! /usr/bin/env python # -*- coding: iso-8859-15 -*- -import sys, signal, os, commands, getopt, smtplib +import sys, signal, os, commands, getopt, smtplib, shutil sys.path.append('/usr/scripts/gestion') from ldap_crans import crans_ldap, crans, ann_scol, smtpserv from lock import * from affich_tools import anim, cprint, OK, ERREUR, WARNING -from time import localtime +from time import localtime, strftime import config # On vérifie que l'on es root @@ -24,7 +24,7 @@ make_lock('auto_generate') ##### Options fournies ? try : if len(sys.argv) > 1 : - options, arg = getopt.getopt(sys.argv[1:], '', ['quiet', 'home=', 'mail_bienvenue=', 'ML-ENS=', 'droits', 'switch=' , 'dhcp', 'dns', 'firewall', 'conf_wifi', 'bornes_wifi=' ]) + options, arg = getopt.getopt(sys.argv[1:], '', ['quiet', 'home=', 'mail_bienvenue=', 'ML-ENS=', 'droits', 'switch=' , 'dhcp', 'dns', 'firewall', 'conf_wifi', 'bornes_wifi=' , 'del_user=']) else : options, arg = ( [],'') except getopt.error, msg : @@ -51,8 +51,46 @@ else : from socket import gethostname +inst = [] + if gethostname().split(".")[0] == 'zamok': - inst = [] + if 'del_user' in to_do.keys() : + if auto : db.services_to_restart('-del_user') + cprint('Archivage fichiers utilisateur','gras') + for args in to_do['del_user'] : + anim('\t' + args) + try : + login, home = args.split(',') + if not login or not home : + raise ValueError('Argument invalide') + warn = '' + f = config.cimetiere + '/files/' + strftime('%Y-%m-%d-%H:%M_') + login + '.tar.bz2' + status, output = commands.getstatusoutput("tar cjf '%s' '%s' /var/spool/mail/%s" % ( f,home,login) ) + if ( status != 512 and status!=0 ) or not os.path.isfile(f) : + # La 512 est si un des paths n'exite pas. + raise OSError(output) + if os.path.isdir(home) and os.stat(home)[4] >= 500 : + shutil.rmtree(home) + else : + warn += '%s incorrect\n' % home + if os.path.isfile('/var/spool/mail/' + login ) : + os.unlink('/var/spool/mail/' + login) + else : + warn += '/var/spool/mail/%s incorrect\n' % login + + if warn : + print WARNING + if debug : + sys.stderr.write(warn) + + except : + print ERREUR + # On devra le refaire la prochaine fois + if auto : db.services_to_restart('del_user',[args]) + if debug : + import traceback + traceback.print_exc() + if 'home' in to_do.keys() : if auto : db.services_to_restart('-home') cprint('Création home','gras') @@ -60,17 +98,29 @@ if gethostname().split(".")[0] == 'zamok': anim('\t' + args) try : home, uid, login = args.split(',') - try : + ### Home + if not os.path.exists(home) : + # Le home n'existe pas os.mkdir(home, 0755) - except : - pass - os.chown(home, int(uid) ,config.gid) - try : + os.chown(home, int(uid) ,config.gid) + elif os.path.isdir(home) : + # Il y un répertoire existant + # Bon UID ? + stat = os.stat(home) + if stat[4] != int(uid) or stat[5] != config.gid : + # Le home n'est pas à la bonne personne + raise OSError('home existant') + + ### Mail + try : os.mkdir(home + '/Mail', 0700) + os.chown(home + '/Mail', int(uid) ,config.gid) except : + # Pas grave pass - os.chown(home + '/Mail', int(uid) ,config.gid) - status, output = commands.getstatusoutput('/usr/sbin/edquota -p pauget %s' % login ) + + ### Quota + status, output = commands.getstatusoutput('/usr/sbin/edquota -p pauget %s' % login ) if status : print WARNING if debug : @@ -84,6 +134,7 @@ if gethostname().split(".")[0] == 'zamok': if debug : import traceback traceback.print_exc() + if 'mail_bienvenue' in to_do.keys() : if auto : db.services_to_restart('-mail_bienvenue') cprint('Envoi mail de bienvenue','gras') diff --git a/gestion/ldap_crans.py b/gestion/ldap_crans.py index 446d0b19..c7ef82d9 100755 --- a/gestion/ldap_crans.py +++ b/gestion/ldap_crans.py @@ -25,7 +25,7 @@ smtpserv = "localhost" import smtplib, sre, os, random, string, time, sys import ldap, ldap.modlist -import config, annuaires, iptools, chgpass, user_tests +import config, annuaires, iptools, chgpass, user_tests, cPickle from chgpass import chgpass from affich_tools import coul, prompt from time import sleep,localtime @@ -41,8 +41,8 @@ random.seed() # On initialise le g ################################################################################## ### Items de la blackliste blacklist_items = { u'bloq' : u'Bloquage total de tout services' , - u'bl_virus' : u'Bloquage sur squid', - u'bl_upload' : u'Bloquage total accès extérieur' } + u'virus' : u'Bloquage sur squid', + u'upload' : u'Bloquage total accès extérieur' } ################################################################################## ### Droits possibles @@ -749,7 +749,6 @@ class base_classes_crans(crans_ldap) : except ldap.TYPE_OR_VALUE_EXISTS , c : champ = c.args[0]['info'].split(':')[0] raise RuntimeError(u'Entrée en double dans le champ %s' % champ) - ### Génération de la liste de services à redémarrer @@ -762,21 +761,16 @@ class base_classes_crans(crans_ldap) : 'ipsec' : [ 'conf_wifi' ], 'hostAlias' : [ 'dns' ] , 'droits' : [ 'droits' ] , - 'ports' : [ 'firewall-komaz' ] + 'ports' : [ 'firewall-komaz' ] , + 'blacklist' : [ 'blacklistes' ] , } + serv = [] for m in self.modifs : for s in annuaire_modif_service.get(m,[]) : if s not in serv : serv.append(s) - # Regénération blackliste nécessaire ? - bl = self.blacklist_actif() - if bl and ( 'host' in self.modifs or 'blacklist' in self.modifs ): - for s in bl : - if s not in serv : - serv.append(s) - # Reinitialisation self._init_data = self._data.copy() @@ -785,24 +779,33 @@ class base_classes_crans(crans_ldap) : def _delete(self,dn,comment='') : """ Sauvegarde puis destruction du dn (et des sous-dn) fourni """ - if not self.conn : self.connect() + # Commentaires + self.modifs.append('destruction (%s)' % comment) + self._save() + + # Sauvegarde + t = str(self.__class__).split('.')[-1] + fd = open('%s/%s/%s_%s' % (config.cimetiere, t, time.strftime('%Y-%m-%d-%H:%M'), self.nom()),'wb') + self.conn = None # Fermeture de la connexion à la base sinon cPickle ne marchera pas + cPickle.dump(self,fd,2) + fd.close() + index = "%s, %s : %s %s # %s\n" % (time.strftime(date_format), script_utilisateur, t, self.Nom() , comment) + + # Destruction + self.connect() data = self.conn.search_s(dn,2) - txt = "%s # Destruction le %s par %s" % (data, time.strftime(date_format), script_utilisateur) - if comment : - txt += ' (%s)' % comment - txt += '\n' data.reverse() # Necessaire pour détruire d'abord les sous-dn for r in data : self.conn.delete_s(r[0]) - + try : - log = open(config.delete_log,'a') - log.write(txt) + log = open(config.cimetiere + '/index','a') + log.write(index) log.close() except : pass - + def _set(self,champ,val) : """ Met à jour les données de data et modifie modifs si besoin """ if not self._data.has_key(champ) \ @@ -895,18 +898,16 @@ class base_proprietaire(base_classes_crans) : """Destruction du proprietaire""" done = 0 for m in self.machines() : - if m.ipsec() : - self.services_to_restart('conf_wifi') - elif not done : - done = 1 - self.services_to_restart('switch',[self.chbre()]) - if self.machines() : - self.services_to_restart('dhcp') - self.services_to_restart('dns') - self.services_to_restart('firewall',[ self.nom() ]) - + # Destruction machines + m.delete(comment) + self._delete(self.dn,comment) + if self.compte() : + args = self._data['uid'][0] + ',' + args+= self._data['homeDirectory'][0] + self.services_to_restart('del_user',[ args ] ) + def save(self) : """ Enregistre l'adhérent ou le club courant dans la base LDAP @@ -1524,7 +1525,7 @@ class club(base_proprietaire) : class machine(base_classes_crans) : """ Classe de définition d'une machine """ idn = 'mid' - + def __init__(self,parent_or_tuple,typ='fixe',conn=None) : """ parent_or_tuple est : @@ -1876,7 +1877,13 @@ class machine(base_classes_crans) : if self.__typ == 'wifi' and ( 'ipHostNumber' in self.modifs or 'host' in self.modifs ) : # Reconfiguration clients wifi necessaire self.services_to_restart('conf_wifi') - + + # Regénération blackliste nécessaire ? + bl = self.blacklist_actif() + if bl and ( 'ipHostNumber' in self.modifs or 'host' in self.modifs ): + for s in bl : + self.services_to_restart(s,[ self.ip() ] ) + # Remise à zéro self.modifs=[] @@ -1895,6 +1902,8 @@ class machine(base_classes_crans) : elif self.__typ == 'fixe' : self.services_to_restart('switch',[ self.proprietaire().chbre() ]) + self.proprio = self.__proprietaire.Nom() # On met dans un coin le nom du proprio + self.__proprietaire = None # On oublie le propriétaire self._delete(self.dn,comment) self.services_to_restart('dhcp') diff --git a/gestion/whos.py b/gestion/whos.py index 4d5c5245..3f8ec48e 100755 --- a/gestion/whos.py +++ b/gestion/whos.py @@ -384,11 +384,16 @@ def machine_details(machine) : f+= coul(u'MAC : ','gras') + "%s\n" %machine.mac() # Propriétaire - a = machine.proprietaire() f+= coul(u'Propriétaire : ','gras') - f += "%s" % a.Nom() - if a.chbre() : f += " (%s)" % a.chbre() + try : + f += machine.proprio + coul(' (adhérent détruit)', 'jaune') + a = crans() + except : + a = machine.proprietaire() + f += "%s" % a.Nom() + if a.chbre() : f += " (%s)" % a.chbre() f+= '\n' + # Adhérent blacklisté ? bl = a.blacklist_actif()