Detabification massive.
darcs-hash:20051018083823-d1718-09c2df38cfb707d3c3679188b9b9a812009f4f7c.gz
This commit is contained in:
parent
3c54fb2904
commit
37b21339a6
40 changed files with 1473 additions and 1473 deletions
|
@ -18,9 +18,9 @@ def dialog(backtitle,arg) :
|
|||
""" Affiche la boite de dialogue défine avec les arguments fournis
|
||||
(cf man dialog)
|
||||
si tout se déroule bien retourne :
|
||||
[ 0, [ reponse(s) ] ]
|
||||
[ 0, [ reponse(s) ] ]
|
||||
si annulatin retourne :
|
||||
[ 1, [] ]
|
||||
[ 1, [] ]
|
||||
si appui sur ESC demande confirmation de l'abandon et exécute sys.exit(0)
|
||||
si erreur dans les arguments raise RuntimeError
|
||||
"""
|
||||
|
@ -29,30 +29,30 @@ def dialog(backtitle,arg) :
|
|||
res = os.system(cmd.encode('iso-8859-15','ignore'))
|
||||
|
||||
if res == 256 :
|
||||
# Annuler
|
||||
f.close()
|
||||
return [ 1, [] ]
|
||||
|
||||
# Annuler
|
||||
f.close()
|
||||
return [ 1, [] ]
|
||||
|
||||
# Lecture du fichier de résultat et effacement
|
||||
try:
|
||||
result=f.readlines()
|
||||
f.close()
|
||||
result=f.readlines()
|
||||
f.close()
|
||||
except :
|
||||
result = [ "n'importe quoi", '']
|
||||
res = 65280
|
||||
result = [ "n'importe quoi", '']
|
||||
res = 65280
|
||||
|
||||
# Traitement
|
||||
if res==65280 and result:
|
||||
# Erreur dans les arguments
|
||||
raise RuntimeError( arg, result[1].strip() )
|
||||
# Erreur dans les arguments
|
||||
raise RuntimeError( arg, result[1].strip() )
|
||||
elif res==65280 :
|
||||
# Appui sur ESC
|
||||
arg1 = u'--title "Annulation" --yesno "Quitter ?\nLes dernières modifications seront perdues." 6 48'
|
||||
print backtitle
|
||||
cmd = u'/usr/bin/dialog --backtitle "%s" %s' % (backtitle,arg1)
|
||||
res = os.system(cmd.encode('iso-8859-15','ignore') )
|
||||
if res==0 : sys.exit(0)
|
||||
else : return dialog(backtitle,arg)
|
||||
# Appui sur ESC
|
||||
arg1 = u'--title "Annulation" --yesno "Quitter ?\nLes dernières modifications seront perdues." 6 48'
|
||||
print backtitle
|
||||
cmd = u'/usr/bin/dialog --backtitle "%s" %s' % (backtitle,arg1)
|
||||
res = os.system(cmd.encode('iso-8859-15','ignore') )
|
||||
if res==0 : sys.exit(0)
|
||||
else : return dialog(backtitle,arg)
|
||||
elif not result : result=['']
|
||||
|
||||
return [ 0, result ]
|
||||
|
@ -66,11 +66,11 @@ def coul(txt,col):
|
|||
"""
|
||||
codecol={'rouge' : 31 , 'vert' : 32 , 'jaune' : 33 , 'bleu': 34 , 'violet' : 35 , 'cyan' : 36 , 'gras' : 50}
|
||||
try :
|
||||
if col[:2]=='f_' : add=10; col=col[2:]
|
||||
else : add=0
|
||||
txt = "\033[1;%sm%s\033[1;0m" % (codecol[col]+add,txt)
|
||||
if col[:2]=='f_' : add=10; col=col[2:]
|
||||
else : add=0
|
||||
txt = "\033[1;%sm%s\033[1;0m" % (codecol[col]+add,txt)
|
||||
finally :
|
||||
return txt
|
||||
return txt
|
||||
|
||||
OK = coul('OK','vert')
|
||||
WARNING = coul('WARNING','jaune')
|
||||
|
@ -84,7 +84,7 @@ 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), .... ]
|
||||
[ ( données entète), (données ligne1), .... ]
|
||||
"""
|
||||
sep_col = u'|'
|
||||
|
||||
|
@ -102,25 +102,25 @@ def tableau(largeurs,data) :
|
|||
# Ligne de séparation entète corps
|
||||
s=u'\n'
|
||||
for l in largeurs :
|
||||
s+= sep_col + u'-'*l
|
||||
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'
|
||||
|
||||
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
|
||||
|
@ -151,44 +151,44 @@ def prompt(prompt, defaut=''):
|
|||
|
||||
class anim :
|
||||
""" Permet de créer une animation :
|
||||
truc................./
|
||||
truc.................-
|
||||
truc.................\
|
||||
truc.................|
|
||||
ou une barre de progression si le nombre total d'itérations est founi.
|
||||
"""
|
||||
truc................./
|
||||
truc.................-
|
||||
truc.................\
|
||||
truc.................|
|
||||
ou une barre de progression si le nombre total d'itérations est founi.
|
||||
"""
|
||||
def __init__(self,truc,iter=0) :
|
||||
""" Affichage de :
|
||||
truc................."""
|
||||
self.txt = truc + '.'*(45-len(truc))
|
||||
self.c = 1
|
||||
self.iter = iter
|
||||
sys.stdout.write(self.txt)
|
||||
sys.stdout.flush()
|
||||
|
||||
""" Affichage de :
|
||||
truc................."""
|
||||
self.txt = truc + '.'*(45-len(truc))
|
||||
self.c = 1
|
||||
self.iter = iter
|
||||
sys.stdout.write(self.txt)
|
||||
sys.stdout.flush()
|
||||
|
||||
def reinit(self) :
|
||||
""" Efface la ligne courrante et
|
||||
affiche : truc................. """
|
||||
sys.stdout.write(el + self.txt)
|
||||
if self.iter :
|
||||
sys.stdout.write(' '*28)
|
||||
sys.stdout.write(el + self.txt)
|
||||
sys.stdout.flush()
|
||||
""" Efface la ligne courrante et
|
||||
affiche : truc................. """
|
||||
sys.stdout.write(el + self.txt)
|
||||
if self.iter :
|
||||
sys.stdout.write(' '*28)
|
||||
sys.stdout.write(el + self.txt)
|
||||
sys.stdout.flush()
|
||||
|
||||
def cycle(self) :
|
||||
""" Efface la ligne courrante et
|
||||
affiche : truc..................?
|
||||
? caratère variant à chaque appel """
|
||||
sys.stdout.write(el + self.txt)
|
||||
if self.iter!=0 :
|
||||
sys.stdout.write('[')
|
||||
av = float(self.c) / float(self.iter)
|
||||
n = int(20 * av)
|
||||
sys.stdout.write('='*n)
|
||||
sys.stdout.write('>')
|
||||
sys.stdout.write(' '*(20 - n))
|
||||
sys.stdout.write('] %3i%%' % int(100 * av) )
|
||||
else :
|
||||
sys.stdout.write('/-\|'[self.c%4])
|
||||
sys.stdout.flush()
|
||||
self.c += 1
|
||||
""" Efface la ligne courrante et
|
||||
affiche : truc..................?
|
||||
? caratère variant à chaque appel """
|
||||
sys.stdout.write(el + self.txt)
|
||||
if self.iter!=0 :
|
||||
sys.stdout.write('[')
|
||||
av = float(self.c) / float(self.iter)
|
||||
n = int(20 * av)
|
||||
sys.stdout.write('='*n)
|
||||
sys.stdout.write('>')
|
||||
sys.stdout.write(' '*(20 - n))
|
||||
sys.stdout.write('] %3i%%' % int(100 * av) )
|
||||
else :
|
||||
sys.stdout.write('/-\|'[self.c%4])
|
||||
sys.stdout.flush()
|
||||
self.c += 1
|
||||
|
|
|
@ -490,10 +490,10 @@ def reverse(bat) :
|
|||
""" Retourne un dictionnaire : { prise : [ chambre(s) ] } """
|
||||
reverse={}
|
||||
for chbre, prise in chbre_prises[bat].items() :
|
||||
if reverse.has_key(prise) :
|
||||
reverse[prise] += [ chbre ]
|
||||
else :
|
||||
reverse[prise] = [ chbre ]
|
||||
if reverse.has_key(prise) :
|
||||
reverse[prise] += [ chbre ]
|
||||
else :
|
||||
reverse[prise] = [ chbre ]
|
||||
return reverse
|
||||
|
||||
def all_switchs(bat=None):
|
||||
|
@ -517,7 +517,7 @@ def all_switchs(bat=None):
|
|||
dup = map(lambda x: x[0], reverse(b).keys())
|
||||
# dup contient des elements en double
|
||||
for n in list(dict(zip(dup,[None]*len(dup)))):
|
||||
switchs.append("bat%s-%s.adm.crans.org" % (b, n))
|
||||
switchs.append("bat%s-%s.adm.crans.org" % (b, n))
|
||||
switchs.sort(cmp)
|
||||
return switchs
|
||||
|
||||
|
@ -528,18 +528,18 @@ def locaux_clubs() :
|
|||
# Corespondance chbre -> nom du local club
|
||||
locaux_clubs = { 'Bcl0' : 'Kfet' ,
|
||||
'Bcl1' : 'Krobot',
|
||||
'Gcl0' : 'Med' ,
|
||||
'Pcl0' : 'Bds' ,
|
||||
'Hcl0' : 'Eileo',
|
||||
'EXT' : 'EXT' }
|
||||
'Gcl0' : 'Med' ,
|
||||
'Pcl0' : 'Bds' ,
|
||||
'Hcl0' : 'Eileo',
|
||||
'EXT' : 'EXT' }
|
||||
# Ajout des locaux d'étage A, B et C
|
||||
for b in 'ABC' :
|
||||
for i in range(2,7) :
|
||||
locaux_clubs['%scl%i' % ( b, i)] = '%i@%s' % (i, b)
|
||||
for i in range(2,7) :
|
||||
locaux_clubs['%scl%i' % ( b, i)] = '%i@%s' % (i, b)
|
||||
# Ajout de ceux des H, I et J
|
||||
for b in 'HIJ' :
|
||||
for i in range(1,5) :
|
||||
locaux_clubs['%scl%i' % ( b, i)] = '%i@%s' % (i, b)
|
||||
for i in range(1,5) :
|
||||
locaux_clubs['%scl%i' % ( b, i)] = '%i@%s' % (i, b)
|
||||
# Supression du 2@B et 4@J
|
||||
locaux_clubs.pop('Bcl2')
|
||||
locaux_clubs.pop('Jcl4')
|
||||
|
|
|
@ -80,12 +80,12 @@ class home:
|
|||
sys.stderr.write(output+'\n')
|
||||
else :
|
||||
print OK
|
||||
|
||||
### Mail
|
||||
os.mkdir(home + '/Mail', 0700)
|
||||
os.chown(home + '/Mail', int(uid) ,config.gid)
|
||||
os.mkdir('/var/mail/' + login,0770)
|
||||
os.chown('/var/mail/' + login, int(uid) ,8)
|
||||
|
||||
### Mail
|
||||
os.mkdir(home + '/Mail', 0700)
|
||||
os.chown(home + '/Mail', int(uid) ,config.gid)
|
||||
os.mkdir('/var/mail/' + login,0770)
|
||||
os.chown('/var/mail/' + login, int(uid) ,8)
|
||||
|
||||
except :
|
||||
print ERREUR
|
||||
|
|
|
@ -19,11 +19,11 @@ except:
|
|||
|
||||
class droits(gen_config) :
|
||||
def restart(s) :
|
||||
# Rien à faire
|
||||
pass
|
||||
# Rien à faire
|
||||
pass
|
||||
|
||||
def __str__(s):
|
||||
return "droits"
|
||||
return "droits"
|
||||
|
||||
class droits_ldap(crans_ldap,droits) :
|
||||
####### Les groupes
|
||||
|
@ -32,9 +32,9 @@ class droits_ldap(crans_ldap,droits) :
|
|||
# Quels droits donnent l'appartenacne à quel groupe ?
|
||||
groupes = { 'adm' : [ u'Nounou' ] ,
|
||||
'respbats' : [ u'Câbleur' , u'Déconnecteur', u'Nounou' ] ,
|
||||
'moderateurs' : [ u'Modérateur' ] ,
|
||||
'disconnect' : [ u'Déconnecteur' ] ,
|
||||
'webcvs' : [ u'CVSWeb'] }
|
||||
'moderateurs' : [ u'Modérateur' ] ,
|
||||
'disconnect' : [ u'Déconnecteur' ] ,
|
||||
'webcvs' : [ u'CVSWeb'] }
|
||||
|
||||
####### Les ML
|
||||
# Le + devant un nom de ML indique une synchronisqtion
|
||||
|
@ -42,96 +42,96 @@ class droits_ldap(crans_ldap,droits) :
|
|||
# des abonnés si le droit est retiré
|
||||
mailing_listes = { 'roots' : [ u'Nounou', u'Apprenti' ],
|
||||
'+nounou' : [ u'Nounou', u'Apprenti' ],
|
||||
'respbats' : [ u'Câbleur', u'Nounou' ],
|
||||
'+moderateurs' : [ u'Modérateur' ],
|
||||
'+disconnect' : [ u'Déconnecteur' ] }
|
||||
|
||||
'respbats' : [ u'Câbleur', u'Nounou' ],
|
||||
'+moderateurs' : [ u'Modérateur' ],
|
||||
'+disconnect' : [ u'Déconnecteur' ] }
|
||||
|
||||
def build_group(self) :
|
||||
""" Reconstruit les groupes dans la base LDAP """
|
||||
self.anim.iter = len( self.groupes.keys() )
|
||||
for group, fonctions in self.groupes.items() :
|
||||
self.anim.cycle()
|
||||
# Qui doit être dans ce groupe ?
|
||||
res = []
|
||||
for f in fonctions :
|
||||
res += self.search('droits=%s' % f)['adherent']
|
||||
""" Reconstruit les groupes dans la base LDAP """
|
||||
self.anim.iter = len( self.groupes.keys() )
|
||||
for group, fonctions in self.groupes.items() :
|
||||
self.anim.cycle()
|
||||
# Qui doit être dans ce groupe ?
|
||||
res = []
|
||||
for f in fonctions :
|
||||
res += self.search('droits=%s' % f)['adherent']
|
||||
|
||||
# Récupération de la constitution du groupe actuel
|
||||
dn = 'cn=%s,%s' % (group, self.base_group_dn)
|
||||
data = self.conn.search_s(dn ,0,'objectClass=posixGroup')[0][1]
|
||||
init_data = data.copy()
|
||||
|
||||
# Supression de tout les membres
|
||||
data['memberUid'] = []
|
||||
|
||||
# Ajout des bonnes personnes
|
||||
for adher in res :
|
||||
uid = preattr(adher.compte())[1]
|
||||
if uid and uid not in data['memberUid'] :
|
||||
data['memberUid'].append(uid)
|
||||
|
||||
# Sauvegarde
|
||||
# Récupération de la constitution du groupe actuel
|
||||
dn = 'cn=%s,%s' % (group, self.base_group_dn)
|
||||
data = self.conn.search_s(dn ,0,'objectClass=posixGroup')[0][1]
|
||||
init_data = data.copy()
|
||||
|
||||
# Supression de tout les membres
|
||||
data['memberUid'] = []
|
||||
|
||||
# Ajout des bonnes personnes
|
||||
for adher in res :
|
||||
uid = preattr(adher.compte())[1]
|
||||
if uid and uid not in data['memberUid'] :
|
||||
data['memberUid'].append(uid)
|
||||
|
||||
# Sauvegarde
|
||||
modlist = ldap.modlist.modifyModlist(init_data,data)
|
||||
self.conn.modify_s(dn,modlist)
|
||||
self.conn.modify_s(dn,modlist)
|
||||
|
||||
def print_liste(self,poste) :
|
||||
""" Donne la liste des membres actifs """
|
||||
for adh in self.search('droits=%s&chbre!=EXT' % poste)['adherent'] :
|
||||
print "%s %s" % (adh.nom(), adh.prenom())
|
||||
|
||||
""" Donne la liste des membres actifs """
|
||||
for adh in self.search('droits=%s&chbre!=EXT' % poste)['adherent'] :
|
||||
print "%s %s" % (adh.nom(), adh.prenom())
|
||||
|
||||
def sync_ML(self) :
|
||||
self.anim.iter = len( self.mailing_listes.keys() )
|
||||
for ML, fonctions in self.mailing_listes.items() :
|
||||
self.anim.cycle()
|
||||
if ML[0] == '+' :
|
||||
ML = ML[1:]
|
||||
only_add = 1
|
||||
else :
|
||||
only_add = 0
|
||||
|
||||
# Instance correspondant à la ML
|
||||
mlist = MailList.MailList(ML)
|
||||
self.mlist_to_unlock = mlist
|
||||
|
||||
# Qui doit être dans cette ML ?
|
||||
res = []
|
||||
for f in fonctions :
|
||||
res += self.search('droits=%s' % f)['adherent']
|
||||
|
||||
# Liste des personnes déja inscrites
|
||||
deja_inscrits = {} # { email en miniscules : email avec case n'importe comment }
|
||||
for addr in mlist.getMemberCPAddresses(mlist.getMembers()):
|
||||
deja_inscrits[addr.lower()] = addr
|
||||
|
||||
# Mails à ajouter
|
||||
to_add = []
|
||||
mail_traite = []
|
||||
for adher in res :
|
||||
mail = adher.mail().lower()
|
||||
if mail in mail_traite : continue
|
||||
mail_traite.append(mail)
|
||||
if mail.find('@') == -1 : mail += '@crans.org'
|
||||
if mail not in deja_inscrits.keys() :
|
||||
# Visiblement pas inscrit
|
||||
to_add.append([ mail, adher.Nom() ])
|
||||
else :
|
||||
# L'adhérent est déja inscrit
|
||||
deja_inscrits.pop(mail)
|
||||
|
||||
# Ajout
|
||||
for mail, nom in to_add :
|
||||
pw = Utils.MakeRandomPassword()
|
||||
userdesc = UserDesc( mail, nom, pw)
|
||||
mlist.ApprovedAddMember(userdesc)
|
||||
if not only_add :
|
||||
# Supression des personnes inscritees en trop
|
||||
for mail in deja_inscrits.values() :
|
||||
mlist.ApprovedDeleteMember(mail)
|
||||
|
||||
mlist.Save()
|
||||
mlist.Unlock()
|
||||
self.mlist_to_unlock = None
|
||||
|
||||
self.anim.iter = len( self.mailing_listes.keys() )
|
||||
for ML, fonctions in self.mailing_listes.items() :
|
||||
self.anim.cycle()
|
||||
if ML[0] == '+' :
|
||||
ML = ML[1:]
|
||||
only_add = 1
|
||||
else :
|
||||
only_add = 0
|
||||
|
||||
# Instance correspondant à la ML
|
||||
mlist = MailList.MailList(ML)
|
||||
self.mlist_to_unlock = mlist
|
||||
|
||||
# Qui doit être dans cette ML ?
|
||||
res = []
|
||||
for f in fonctions :
|
||||
res += self.search('droits=%s' % f)['adherent']
|
||||
|
||||
# Liste des personnes déja inscrites
|
||||
deja_inscrits = {} # { email en miniscules : email avec case n'importe comment }
|
||||
for addr in mlist.getMemberCPAddresses(mlist.getMembers()):
|
||||
deja_inscrits[addr.lower()] = addr
|
||||
|
||||
# Mails à ajouter
|
||||
to_add = []
|
||||
mail_traite = []
|
||||
for adher in res :
|
||||
mail = adher.mail().lower()
|
||||
if mail in mail_traite : continue
|
||||
mail_traite.append(mail)
|
||||
if mail.find('@') == -1 : mail += '@crans.org'
|
||||
if mail not in deja_inscrits.keys() :
|
||||
# Visiblement pas inscrit
|
||||
to_add.append([ mail, adher.Nom() ])
|
||||
else :
|
||||
# L'adhérent est déja inscrit
|
||||
deja_inscrits.pop(mail)
|
||||
|
||||
# Ajout
|
||||
for mail, nom in to_add :
|
||||
pw = Utils.MakeRandomPassword()
|
||||
userdesc = UserDesc( mail, nom, pw)
|
||||
mlist.ApprovedAddMember(userdesc)
|
||||
if not only_add :
|
||||
# Supression des personnes inscritees en trop
|
||||
for mail in deja_inscrits.values() :
|
||||
mlist.ApprovedDeleteMember(mail)
|
||||
|
||||
mlist.Save()
|
||||
mlist.Unlock()
|
||||
self.mlist_to_unlock = None
|
||||
|
||||
def gen_conf(self) :
|
||||
self.anim = anim('\tconfiguration groupes')
|
||||
try:
|
||||
|
@ -170,10 +170,10 @@ class droits_openbsd(droits) :
|
|||
"""
|
||||
master = ""
|
||||
group = "wheel:*:0:root"
|
||||
self.anim.iter = 2
|
||||
self.anim.iter = 2
|
||||
for fonction in ("Nounou", "Apprenti"):
|
||||
self.anim.cycle()
|
||||
# Qui doit être dans ce groupe ?
|
||||
self.anim.cycle()
|
||||
# Qui doit être dans ce groupe ?
|
||||
res = crans_ldap().search('droits=%s' % fonction)['adherent']
|
||||
for a in res:
|
||||
if fonction == "Nounou":
|
||||
|
@ -234,13 +234,13 @@ class droits_openbsd(droits) :
|
|||
|
||||
if __name__ == '__main__' :
|
||||
if '-h' in sys.argv or '--help' in sys.argv or len(sys.argv) == 1 :
|
||||
print "%s <switch>" % sys.argv[0].split('/')[-1].split('.')[0]
|
||||
print "Génération de la liste des personnes avec le(s) droit(s) donné(s)."
|
||||
sys.exit(255)
|
||||
|
||||
print "%s <switch>" % sys.argv[0].split('/')[-1].split('.')[0]
|
||||
print "Génération de la liste des personnes avec le(s) droit(s) donné(s)."
|
||||
sys.exit(255)
|
||||
|
||||
cl = droits()
|
||||
for arg in sys.argv[1:] :
|
||||
titre = "%s : " % arg
|
||||
print titre
|
||||
print "-" * len (titre)
|
||||
cl.print_liste(unicode(arg,'iso-8859-1'))
|
||||
for arg in sys.argv[1:] :
|
||||
titre = "%s : " % arg
|
||||
print titre
|
||||
print "-" * len (titre)
|
||||
cl.print_liste(unicode(arg,'iso-8859-1'))
|
||||
|
|
|
@ -25,25 +25,25 @@ class exemptions(gen_config) :
|
|||
restart_cmd = ""
|
||||
|
||||
def __str__ (self) :
|
||||
return "exemptions"
|
||||
return "exemptions"
|
||||
|
||||
def _gen (self) :
|
||||
|
||||
machines = crans_ldap().search('exempt=*')['machine']
|
||||
|
||||
pgsql = PgSQL.connect(host='/var/run/postgresql', database='filtrage', user='crans')
|
||||
curseur = pgsql.cursor()
|
||||
|
||||
requete="DELETE FROM exemptes"
|
||||
curseur.execute(requete)
|
||||
|
||||
for couple in self.base :
|
||||
requete="INSERT INTO exemptes (ip_crans,ip_dest) VALUES ('%s','%s')" % (couple[0],couple[1])
|
||||
curseur.execute(requete)
|
||||
|
||||
for machine in machines :
|
||||
for destination in machine.exempt() :
|
||||
requete="INSERT INTO exemptes (ip_crans,ip_dest) VALUES ('%s','%s')" % (machine.ip(),destination)
|
||||
curseur.execute(requete)
|
||||
|
||||
pgsql.commit()
|
||||
|
||||
machines = crans_ldap().search('exempt=*')['machine']
|
||||
|
||||
pgsql = PgSQL.connect(host='/var/run/postgresql', database='filtrage', user='crans')
|
||||
curseur = pgsql.cursor()
|
||||
|
||||
requete="DELETE FROM exemptes"
|
||||
curseur.execute(requete)
|
||||
|
||||
for couple in self.base :
|
||||
requete="INSERT INTO exemptes (ip_crans,ip_dest) VALUES ('%s','%s')" % (couple[0],couple[1])
|
||||
curseur.execute(requete)
|
||||
|
||||
for machine in machines :
|
||||
for destination in machine.exempt() :
|
||||
requete="INSERT INTO exemptes (ip_crans,ip_dest) VALUES ('%s','%s')" % (machine.ip(),destination)
|
||||
curseur.execute(requete)
|
||||
|
||||
pgsql.commit()
|
||||
|
|
|
@ -44,23 +44,23 @@ class base_reconfigure :
|
|||
if not to_do :
|
||||
if debug : print 'Lecture services à redémarrer dans la base LDAP'
|
||||
auto = 1
|
||||
to_do = {}
|
||||
to_do = {}
|
||||
# Création de la liste de ce qu'il y a à faire
|
||||
for serv in db.services_to_restart() :
|
||||
# Services spéciaux portant sur plusieurs machines
|
||||
to_add = self.__service_develop.get(serv.nom,[])
|
||||
if to_add :
|
||||
for nom in to_add :
|
||||
for t in serv.start :
|
||||
db.services_to_restart(nom,serv.args,t)
|
||||
if time() > t :
|
||||
to_do[nom] = serv.args
|
||||
for t in serv.start :
|
||||
db.services_to_restart(nom,serv.args,t)
|
||||
if time() > t :
|
||||
to_do[nom] = serv.args
|
||||
db.services_to_restart('-' + serv.nom)
|
||||
else :
|
||||
for t in serv.start :
|
||||
if time() > t :
|
||||
to_do[serv.nom] = serv.args
|
||||
break
|
||||
else :
|
||||
for t in serv.start :
|
||||
if time() > t :
|
||||
to_do[serv.nom] = serv.args
|
||||
break
|
||||
else :
|
||||
auto = 0
|
||||
if debug : print 'Services à redémarrer imposés (non lecture de la base LDAP)'
|
||||
|
@ -87,8 +87,8 @@ class base_reconfigure :
|
|||
reste = db.services_to_restart()
|
||||
if reste :
|
||||
print "Reste à faire :"
|
||||
for s in reste :
|
||||
print '\t%s' % s
|
||||
for s in reste :
|
||||
print '\t%s' % s
|
||||
else :
|
||||
print "Plus rien à faire"
|
||||
|
||||
|
@ -116,7 +116,7 @@ class rouge(base_reconfigure) :
|
|||
def dns(self) :
|
||||
from gen_confs.bind import dns
|
||||
self._do(dns(),self._machines())
|
||||
|
||||
|
||||
def dhcp(self) :
|
||||
from gen_confs.dhcpd import dhcp
|
||||
self._do(dhcp(),self._machines())
|
||||
|
@ -134,14 +134,14 @@ class rouge(base_reconfigure) :
|
|||
l'affichage des résultats formera le corps du mail """
|
||||
from supervison import mail
|
||||
self._do(mail(trucs))
|
||||
|
||||
|
||||
def switch(self,chambres) :
|
||||
from gen_confs.switchs import switch
|
||||
self._do(switch(chambres))
|
||||
|
||||
def exemptions(self) :
|
||||
from exemptions import exemptions
|
||||
self._do(exemptions())
|
||||
self._do(exemptions())
|
||||
|
||||
class zamok(base_reconfigure) :
|
||||
# Tout est dans le parent
|
||||
|
@ -243,7 +243,7 @@ class vert(base_reconfigure) :
|
|||
def del_user(self,args) :
|
||||
from adherents import del_user
|
||||
self._do(del_user(args))
|
||||
|
||||
|
||||
def mail_bienvenue(self,mails) :
|
||||
from adherents import mail_bienvenue
|
||||
self._do(mail_bienvenue(mails))
|
||||
|
@ -290,7 +290,7 @@ if __name__ == '__main__' :
|
|||
elif opt == '--list' :
|
||||
print 'Services à redémarrer :'
|
||||
for s in db.services_to_restart() :
|
||||
print '\t%s' % s
|
||||
print '\t%s' % s
|
||||
sys.exit(0)
|
||||
|
||||
elif opt == '--reconnect' :
|
||||
|
|
|
@ -15,32 +15,32 @@ class squid(gen_config) :
|
|||
restart_cmd = '/etc/init.d/squid reload'
|
||||
|
||||
def __str__(self) :
|
||||
return str(self.__class__).replace('_','-').split('.')[2]
|
||||
return str(self.__class__).replace('_','-').split('.')[2]
|
||||
|
||||
def _gen(self) :
|
||||
self._mklist()
|
||||
self._mklist()
|
||||
|
||||
def _mklist(self) :
|
||||
fic = self._open_conf(self.FICHIER)
|
||||
# recherche_bl :
|
||||
# 1 : search sur champ blacklist et clubs compris
|
||||
# 0 : search plus général et clubs exclus
|
||||
if self.recherche_bl==1:
|
||||
liste = self.db.search("paiement=ok&blacklist=*%s*"%self.chaine)
|
||||
l_proprio = liste["adherent"]+liste["club"]
|
||||
else:
|
||||
l_proprio = self.db.search('paiement=ok&' + self.chaine)["adherent"]
|
||||
self.anim.iter=len(l_proprio)
|
||||
for proprio in l_proprio :
|
||||
self.anim.cycle()
|
||||
if self.recherche_bl==0 or self.chaine in proprio.blacklist_actif():
|
||||
# Pas la peine de renvoyer les machines complètement bloqués
|
||||
for m in proprio.machines():
|
||||
if not 'bloq' in m.blacklist_actif():
|
||||
fic.write(m.Nom()+'\n')
|
||||
fic.close()
|
||||
fic = self._open_conf(self.FICHIER)
|
||||
# recherche_bl :
|
||||
# 1 : search sur champ blacklist et clubs compris
|
||||
# 0 : search plus général et clubs exclus
|
||||
if self.recherche_bl==1:
|
||||
liste = self.db.search("paiement=ok&blacklist=*%s*"%self.chaine)
|
||||
l_proprio = liste["adherent"]+liste["club"]
|
||||
else:
|
||||
l_proprio = self.db.search('paiement=ok&' + self.chaine)["adherent"]
|
||||
self.anim.iter=len(l_proprio)
|
||||
for proprio in l_proprio :
|
||||
self.anim.cycle()
|
||||
if self.recherche_bl==0 or self.chaine in proprio.blacklist_actif():
|
||||
# Pas la peine de renvoyer les machines complètement bloqués
|
||||
for m in proprio.machines():
|
||||
if not 'bloq' in m.blacklist_actif():
|
||||
fic.write(m.Nom()+'\n')
|
||||
fic.close()
|
||||
|
||||
|
||||
|
||||
class squid_upload(squid) :
|
||||
""" Genère le fichier blacklist-upload pour squid """
|
||||
FICHIER = "/etc/squid/blacklist_upload"
|
||||
|
@ -66,17 +66,17 @@ class squid_carte(squid) :
|
|||
recherche_bl = 0
|
||||
|
||||
if not bl_carte_et_actif :
|
||||
# Inutile de relancer squid si la blacklist n'est pas activée
|
||||
restart_cmd = ''
|
||||
# Inutile de relancer squid si la blacklist n'est pas activée
|
||||
restart_cmd = ''
|
||||
|
||||
def _gen(self) :
|
||||
# Liste vide si la blacklist n'est pas activée
|
||||
if not bl_carte_et_actif :
|
||||
fic = self._open_conf(self.FICHIER)
|
||||
# on vide la blackliste
|
||||
fic.close()
|
||||
return
|
||||
self._mklist()
|
||||
# Liste vide si la blacklist n'est pas activée
|
||||
if not bl_carte_et_actif :
|
||||
fic = self._open_conf(self.FICHIER)
|
||||
# on vide la blackliste
|
||||
fic.close()
|
||||
return
|
||||
self._mklist()
|
||||
|
||||
class squid_chbre(squid) :
|
||||
""" Genère le fichier blacklist-chbre pour squid """
|
||||
|
|
|
@ -170,164 +170,164 @@ class autostatus(gen_config) :
|
|||
# FIN DE LA CONFIGURATION
|
||||
|
||||
def __str__ (self) :
|
||||
return "autostatus"
|
||||
return "autostatus"
|
||||
|
||||
def make_config (self, dico ) :
|
||||
"""
|
||||
Transforme le dico en suite lignes de configuration
|
||||
"""
|
||||
liste = dico.keys()
|
||||
liste.sort()
|
||||
append = ""
|
||||
for i in liste :
|
||||
append = append + " ".join( dico[i] ) + "\n"
|
||||
return append.encode('iso-8859-15')
|
||||
"""
|
||||
Transforme le dico en suite lignes de configuration
|
||||
"""
|
||||
liste = dico.keys()
|
||||
liste.sort()
|
||||
append = ""
|
||||
for i in liste :
|
||||
append = append + " ".join( dico[i] ) + "\n"
|
||||
return append.encode('iso-8859-15')
|
||||
|
||||
def mail_contact (self, nom) :
|
||||
# retourne le mail à qui envoyer les avis pour un serveur
|
||||
if nom in self.contact.keys() :
|
||||
return self.contact[nom]
|
||||
else :
|
||||
return 'nobody'
|
||||
|
||||
# retourne le mail à qui envoyer les avis pour un serveur
|
||||
if nom in self.contact.keys() :
|
||||
return self.contact[nom]
|
||||
else :
|
||||
return 'nobody'
|
||||
|
||||
def _gen (self) :
|
||||
|
||||
# machines crans
|
||||
################
|
||||
|
||||
machines = crans().machines()
|
||||
|
||||
# tri des machines par type
|
||||
bornes = {}
|
||||
switchs = {}
|
||||
serveurs = {}
|
||||
ferme = {}
|
||||
# machines crans
|
||||
################
|
||||
|
||||
machines = crans().machines()
|
||||
|
||||
# tri des machines par type
|
||||
bornes = {}
|
||||
switchs = {}
|
||||
serveurs = {}
|
||||
ferme = {}
|
||||
|
||||
# tri des machines
|
||||
for m in machines :
|
||||
# tri des machines
|
||||
for m in machines :
|
||||
|
||||
# machine exclue
|
||||
if m.nom() in self.exclude :
|
||||
continue
|
||||
|
||||
# les bornes
|
||||
if m.canal() :
|
||||
# C'est une borne
|
||||
if m.info() :
|
||||
# on regarde si c'est une borne de batiment
|
||||
if ( m.info()[0][0:3] == "Au " ) and ( len(m.info()[0]) == 5 ) :
|
||||
bornes[ "1-" + m.info()[0][4]+m.info()[0][3] + "-" + m.nom() ] = [ m.nom().split(".")[0] , m.nom() , 'none' , self.mail_contact(m.nom()) , m.info()[0] ]
|
||||
else :
|
||||
bornes[ "2-" + m.info()[0] + m.nom() ] = [ m.nom().split(".")[0] , m.nom() , 'none' , self.mail_contact(m.nom()) , m.info()[0] ]
|
||||
else :
|
||||
# on met les bornes non définies à la fin (ordre alphabétique)
|
||||
bornes[ "3-" + m.nom() ] = [ m.nom().split(".")[0] , m.nom() , 'none' , self.mail_contact(m.nom()) , 'Inutilise' ]
|
||||
# machine exclue
|
||||
if m.nom() in self.exclude :
|
||||
continue
|
||||
|
||||
# les bornes
|
||||
if m.canal() :
|
||||
# C'est une borne
|
||||
if m.info() :
|
||||
# on regarde si c'est une borne de batiment
|
||||
if ( m.info()[0][0:3] == "Au " ) and ( len(m.info()[0]) == 5 ) :
|
||||
bornes[ "1-" + m.info()[0][4]+m.info()[0][3] + "-" + m.nom() ] = [ m.nom().split(".")[0] , m.nom() , 'none' , self.mail_contact(m.nom()) , m.info()[0] ]
|
||||
else :
|
||||
bornes[ "2-" + m.info()[0] + m.nom() ] = [ m.nom().split(".")[0] , m.nom() , 'none' , self.mail_contact(m.nom()) , m.info()[0] ]
|
||||
else :
|
||||
# on met les bornes non définies à la fin (ordre alphabétique)
|
||||
bornes[ "3-" + m.nom() ] = [ m.nom().split(".")[0] , m.nom() , 'none' , self.mail_contact(m.nom()) , 'Inutilise' ]
|
||||
|
||||
# les switchs
|
||||
elif m.info() and 'switch' in m.info()[0].lower() :
|
||||
# les switchs
|
||||
elif m.info() and 'switch' in m.info()[0].lower() :
|
||||
|
||||
# est ce que c'est un batiment
|
||||
if 'bat' == m.nom()[0:3] :
|
||||
index = '1-' + m.nom().split(".")[0]
|
||||
else :
|
||||
index = '0-' + m.nom().split(".")[0]
|
||||
|
||||
# on ajoute au dictionnaire
|
||||
switchs[ index ] = [ m.nom().split(".")[0] , m.nom() , 'none' , self.mail_contact(m.nom()) , m.info()[0] ]
|
||||
# est ce que c'est un batiment
|
||||
if 'bat' == m.nom()[0:3] :
|
||||
index = '1-' + m.nom().split(".")[0]
|
||||
else :
|
||||
index = '0-' + m.nom().split(".")[0]
|
||||
|
||||
# on ajoute au dictionnaire
|
||||
switchs[ index ] = [ m.nom().split(".")[0] , m.nom() , 'none' , self.mail_contact(m.nom()) , m.info()[0] ]
|
||||
|
||||
# la ferme
|
||||
elif '.ferme.crans.org' in m.nom() :
|
||||
nom = ".".join(m.nom().split(".")[0:2])
|
||||
if m.info() :
|
||||
ferme[ nom ] = [ nom , m.nom() , 'none' , self.mail_contact(m.nom()) , m.info()[0] ]
|
||||
else :
|
||||
ferme[ nom ] = [ nom , m.nom() , 'none' , self.mail_contact(m.nom()) , 'Infos non disponibles' ]
|
||||
|
||||
# les serveurs
|
||||
else :
|
||||
if ".wifi.crans.org" in m.nom() :
|
||||
nom = m.nom().split(".")[0] + ".wifi"
|
||||
else :
|
||||
nom = m.nom().split(".")[0]
|
||||
if m.info() :
|
||||
serveurs[ nom ] = [ nom , m.nom() , 'none' , self.mail_contact(m.nom()) , m.info()[0] ]
|
||||
else :
|
||||
serveurs[ nom ] = [ nom , m.nom() , 'none' , self.mail_contact(m.nom()) , 'Infos non disponibles' ]
|
||||
|
||||
# route vers l'extérieur
|
||||
########################
|
||||
|
||||
# on récupère la route vers l'extérieur
|
||||
traceroute = commands.getoutput("/usr/bin/traceroute www.free.fr 2> /dev/null | sed 's/\*//g' | sed 's/ */ /g' | sed 's/^ //g' | sed 's/[(,)]//g' | cut -d ' ' -f 2,3").split("\n")
|
||||
|
||||
# initialisation des variables
|
||||
in_renater = 0
|
||||
route_to_ext = ''
|
||||
depends_to_ext = ''
|
||||
|
||||
for routeur in traceroute :
|
||||
|
||||
# on commence à rentrer dans la chaine des routeurs renater
|
||||
if 'renater.fr' in routeur :
|
||||
in_renater = 1
|
||||
|
||||
# on est plus dans les routeurs renater donc on arrête
|
||||
if in_renater and not 'renater.fr' in routeur :
|
||||
continue
|
||||
|
||||
# ajout du routeur
|
||||
|
||||
# ip
|
||||
tmp_ip = routeur.split(' ')[1]
|
||||
|
||||
# nom & desciption
|
||||
if routeur.split(' ')[1] in self.infos_routeurs.keys() :
|
||||
tmp_name = self.infos_routeurs[tmp_ip][0]
|
||||
tmp_desc = self.infos_routeurs[tmp_ip][1]
|
||||
else :
|
||||
tmp_name = routeur.split(' ')[0].split('.')[0]
|
||||
tmp_desc = 'Pas de description'
|
||||
|
||||
# dépendances
|
||||
if not depends_to_ext :
|
||||
tmp_depends = 'none'
|
||||
depends_to_ext = tmp_name
|
||||
else :
|
||||
tmp_depends = depends_to_ext
|
||||
depends_to_ext += ',' + tmp_name
|
||||
|
||||
# on l'ajoute à la route
|
||||
if route_to_ext :
|
||||
route_to_ext += '\n'
|
||||
route_to_ext += '%s %s %s %s %s' % (tmp_name, tmp_ip, tmp_depends,self.mail_contact(tmp_name),tmp_desc)
|
||||
# la ferme
|
||||
elif '.ferme.crans.org' in m.nom() :
|
||||
nom = ".".join(m.nom().split(".")[0:2])
|
||||
if m.info() :
|
||||
ferme[ nom ] = [ nom , m.nom() , 'none' , self.mail_contact(m.nom()) , m.info()[0] ]
|
||||
else :
|
||||
ferme[ nom ] = [ nom , m.nom() , 'none' , self.mail_contact(m.nom()) , 'Infos non disponibles' ]
|
||||
|
||||
# les serveurs
|
||||
else :
|
||||
if ".wifi.crans.org" in m.nom() :
|
||||
nom = m.nom().split(".")[0] + ".wifi"
|
||||
else :
|
||||
nom = m.nom().split(".")[0]
|
||||
if m.info() :
|
||||
serveurs[ nom ] = [ nom , m.nom() , 'none' , self.mail_contact(m.nom()) , m.info()[0] ]
|
||||
else :
|
||||
serveurs[ nom ] = [ nom , m.nom() , 'none' , self.mail_contact(m.nom()) , 'Infos non disponibles' ]
|
||||
|
||||
# route vers l'extérieur
|
||||
########################
|
||||
|
||||
# on récupère la route vers l'extérieur
|
||||
traceroute = commands.getoutput("/usr/bin/traceroute www.free.fr 2> /dev/null | sed 's/\*//g' | sed 's/ */ /g' | sed 's/^ //g' | sed 's/[(,)]//g' | cut -d ' ' -f 2,3").split("\n")
|
||||
|
||||
# initialisation des variables
|
||||
in_renater = 0
|
||||
route_to_ext = ''
|
||||
depends_to_ext = ''
|
||||
|
||||
for routeur in traceroute :
|
||||
|
||||
# on commence à rentrer dans la chaine des routeurs renater
|
||||
if 'renater.fr' in routeur :
|
||||
in_renater = 1
|
||||
|
||||
# on est plus dans les routeurs renater donc on arrête
|
||||
if in_renater and not 'renater.fr' in routeur :
|
||||
continue
|
||||
|
||||
# ajout du routeur
|
||||
|
||||
# ip
|
||||
tmp_ip = routeur.split(' ')[1]
|
||||
|
||||
# nom & desciption
|
||||
if routeur.split(' ')[1] in self.infos_routeurs.keys() :
|
||||
tmp_name = self.infos_routeurs[tmp_ip][0]
|
||||
tmp_desc = self.infos_routeurs[tmp_ip][1]
|
||||
else :
|
||||
tmp_name = routeur.split(' ')[0].split('.')[0]
|
||||
tmp_desc = 'Pas de description'
|
||||
|
||||
# dépendances
|
||||
if not depends_to_ext :
|
||||
tmp_depends = 'none'
|
||||
depends_to_ext = tmp_name
|
||||
else :
|
||||
tmp_depends = depends_to_ext
|
||||
depends_to_ext += ',' + tmp_name
|
||||
|
||||
# on l'ajoute à la route
|
||||
if route_to_ext :
|
||||
route_to_ext += '\n'
|
||||
route_to_ext += '%s %s %s %s %s' % (tmp_name, tmp_ip, tmp_depends,self.mail_contact(tmp_name),tmp_desc)
|
||||
|
||||
# services extérieurs
|
||||
#####################
|
||||
|
||||
services_exterieurs = {}
|
||||
for key in self.services_exterieurs.keys() :
|
||||
s = self.services_exterieurs[key]
|
||||
if s[2] :
|
||||
services_exterieurs[ key ] = [ s[0] + ':' + str(s[2]), s[1] , depends_to_ext, s[4] , s[3] ]
|
||||
else :
|
||||
services_exterieurs[ key ] = [ s[0] , s[1] , depends_to_ext, s[4] , s[3] ]
|
||||
# services extérieurs
|
||||
#####################
|
||||
|
||||
services_exterieurs = {}
|
||||
for key in self.services_exterieurs.keys() :
|
||||
s = self.services_exterieurs[key]
|
||||
if s[2] :
|
||||
services_exterieurs[ key ] = [ s[0] + ':' + str(s[2]), s[1] , depends_to_ext, s[4] , s[3] ]
|
||||
else :
|
||||
services_exterieurs[ key ] = [ s[0] , s[1] , depends_to_ext, s[4] , s[3] ]
|
||||
|
||||
# génération du fichier
|
||||
#######################
|
||||
|
||||
file = self._open_conf(self.CONFFILE, "#")
|
||||
|
||||
# génère le dictionnaire pour les modifications
|
||||
dico = {}
|
||||
dico['switchs'] = self.make_config(switchs)
|
||||
dico['bornes'] = self.make_config(bornes)
|
||||
dico['serveurs'] = self.make_config(serveurs)
|
||||
dico['ferme'] = self.make_config(ferme)
|
||||
dico['route'] = route_to_ext.encode('iso-8859-15')
|
||||
dico['exterieur'] = self.make_config(services_exterieurs)
|
||||
|
||||
# on écrit dans le fichier de configuration
|
||||
file.write( self.matrice % dico )
|
||||
|
||||
# on ferme le fichier
|
||||
file.close()
|
||||
# génération du fichier
|
||||
#######################
|
||||
|
||||
file = self._open_conf(self.CONFFILE, "#")
|
||||
|
||||
# génère le dictionnaire pour les modifications
|
||||
dico = {}
|
||||
dico['switchs'] = self.make_config(switchs)
|
||||
dico['bornes'] = self.make_config(bornes)
|
||||
dico['serveurs'] = self.make_config(serveurs)
|
||||
dico['ferme'] = self.make_config(ferme)
|
||||
dico['route'] = route_to_ext.encode('iso-8859-15')
|
||||
dico['exterieur'] = self.make_config(services_exterieurs)
|
||||
|
||||
# on écrit dans le fichier de configuration
|
||||
file.write( self.matrice % dico )
|
||||
|
||||
# on ferme le fichier
|
||||
file.close()
|
||||
|
|
|
@ -6,12 +6,12 @@
|
|||
argument : nom du switch
|
||||
|
||||
procédure de configuration initiale :
|
||||
* mot de passe admin (password manager user-name <username>)
|
||||
* upgrade firmware (copy tftp flash 138.231.136.7 <file>)
|
||||
* reboot (boot)
|
||||
* génération clef ssh (crypto key generate ssh)
|
||||
* copie fichier de conf (copy tftp startup-config 138.231.136.7 <file>)
|
||||
* faire le stacking et le snmpv3 à la main
|
||||
* mot de passe admin (password manager user-name <username>)
|
||||
* upgrade firmware (copy tftp flash 138.231.136.7 <file>)
|
||||
* reboot (boot)
|
||||
* génération clef ssh (crypto key generate ssh)
|
||||
* copie fichier de conf (copy tftp startup-config 138.231.136.7 <file>)
|
||||
* faire le stacking et le snmpv3 à la main
|
||||
pour les reconfiguration juste copier le fichier de conf
|
||||
"""
|
||||
|
||||
|
@ -116,153 +116,153 @@ exit
|
|||
rad_template = "radius-server host %s\n"
|
||||
|
||||
def __init__(self,truc):
|
||||
""" truc est soit :
|
||||
* une _liste_ de chambres => reconfig de ces chambres
|
||||
* un _tulpe_ de noms de switch => reconfig de ces swiths"""
|
||||
self.db = crans_ldap() # connexion LDAP
|
||||
if type(truc) == list :
|
||||
# On enlève les chambres "CRA", "????" et EXT qui n'ont pas besion de config
|
||||
self.chbres = [ch for ch in truc if (ch not in [ "CRA", "????", "EXT" ]) ]
|
||||
self.switch = None
|
||||
else :
|
||||
self.chbres = None
|
||||
self.switch = truc
|
||||
|
||||
""" truc est soit :
|
||||
* une _liste_ de chambres => reconfig de ces chambres
|
||||
* un _tulpe_ de noms de switch => reconfig de ces swiths"""
|
||||
self.db = crans_ldap() # connexion LDAP
|
||||
if type(truc) == list :
|
||||
# On enlève les chambres "CRA", "????" et EXT qui n'ont pas besion de config
|
||||
self.chbres = [ch for ch in truc if (ch not in [ "CRA", "????", "EXT" ]) ]
|
||||
self.switch = None
|
||||
else :
|
||||
self.chbres = None
|
||||
self.switch = truc
|
||||
|
||||
def __str__(self) :
|
||||
return 'switchs'
|
||||
return 'switchs'
|
||||
|
||||
def restart(self) :
|
||||
if self.chbre :
|
||||
# Tout est déja fait
|
||||
return
|
||||
####### Vu qu'il n'y a pas de serveur tftp ici
|
||||
# on excécute pas le truc en dessous
|
||||
#for switch in self.switch :
|
||||
# self.aff = anim('\treboot de %s' % switch)
|
||||
# sw = hptools.switch(switch)
|
||||
# sw.update()
|
||||
if self.chbre :
|
||||
# Tout est déja fait
|
||||
return
|
||||
####### Vu qu'il n'y a pas de serveur tftp ici
|
||||
# on excécute pas le truc en dessous
|
||||
#for switch in self.switch :
|
||||
# self.aff = anim('\treboot de %s' % switch)
|
||||
# sw = hptools.switch(switch)
|
||||
# sw.update()
|
||||
|
||||
def gen_conf(self) :
|
||||
if self.chbres :
|
||||
self.chbres.sort()
|
||||
for chbre in self.chbres :
|
||||
self.configure_chbre(chbre)
|
||||
elif self.switch :
|
||||
for switch in self.switch :
|
||||
self.configure_switch(switch)
|
||||
|
||||
if self.chbres :
|
||||
self.chbres.sort()
|
||||
for chbre in self.chbres :
|
||||
self.configure_chbre(chbre)
|
||||
elif self.switch :
|
||||
for switch in self.switch :
|
||||
self.configure_switch(switch)
|
||||
|
||||
def configure_chbre(self,chbre) :
|
||||
""" Recontigure la chambre fournie chambre """
|
||||
try :
|
||||
bat = chbre[0].lower()
|
||||
if bat in bat_switchs :
|
||||
prise = sw_chbre(chbre)
|
||||
prise.reconfigure() # Vitesse et nom (juste au cas ou ca aurait changé)
|
||||
elif bat in bat_manuels :
|
||||
class prise_non_manageable :
|
||||
def __init__(self,chbre) :
|
||||
self.chbre = chbre
|
||||
|
||||
def __mail(self,sujet) :
|
||||
To = "clef%s@crans.org" % self.chbre[0].lower()
|
||||
From = To
|
||||
conn=smtplib.SMTP('localhost')
|
||||
txt_mail = "From: Crans scripts <%(From)s>\n"
|
||||
txt_mail+= "To: %(To)s\n"
|
||||
txt_mail+= "Subject: (CRANS) %s\n\nMerci." % sujet
|
||||
conn.sendmail(From, To , txt_mail % { 'From' : From, 'To' : To })
|
||||
conn.quit()
|
||||
|
||||
def disable(self) :
|
||||
self.__mail("Chambre %s à débrancher." % self.chbre)
|
||||
def enable(self) :
|
||||
self.__mail("Chambre %s à brancher." % self.chbre)
|
||||
|
||||
prise=prise_non_manageable(chbre)
|
||||
|
||||
else :
|
||||
# Rien a faire
|
||||
print OK
|
||||
return True
|
||||
|
||||
""" Recontigure la chambre fournie chambre """
|
||||
try :
|
||||
bat = chbre[0].lower()
|
||||
if bat in bat_switchs :
|
||||
prise = sw_chbre(chbre)
|
||||
prise.reconfigure() # Vitesse et nom (juste au cas ou ca aurait changé)
|
||||
elif bat in bat_manuels :
|
||||
class prise_non_manageable :
|
||||
def __init__(self,chbre) :
|
||||
self.chbre = chbre
|
||||
|
||||
def __mail(self,sujet) :
|
||||
To = "clef%s@crans.org" % self.chbre[0].lower()
|
||||
From = To
|
||||
conn=smtplib.SMTP('localhost')
|
||||
txt_mail = "From: Crans scripts <%(From)s>\n"
|
||||
txt_mail+= "To: %(To)s\n"
|
||||
txt_mail+= "Subject: (CRANS) %s\n\nMerci." % sujet
|
||||
conn.sendmail(From, To , txt_mail % { 'From' : From, 'To' : To })
|
||||
conn.quit()
|
||||
|
||||
def disable(self) :
|
||||
self.__mail("Chambre %s à débrancher." % self.chbre)
|
||||
def enable(self) :
|
||||
self.__mail("Chambre %s à brancher." % self.chbre)
|
||||
|
||||
prise=prise_non_manageable(chbre)
|
||||
|
||||
else :
|
||||
# Rien a faire
|
||||
print OK
|
||||
return True
|
||||
|
||||
|
||||
a = self.db.search('chbre=%s&paiement=ok' % chbre)
|
||||
a = a['adherent'] + a['club']
|
||||
if a and 'bloq' not in a[0].blacklist_actif() :
|
||||
# Il faut activer la prise
|
||||
anim('\tactivation chbre %s' % chbre)
|
||||
prise.enable()
|
||||
else :
|
||||
# Il faut désactiver la prise
|
||||
anim('\tdésactivation chbre %s' % chbre)
|
||||
prise.disable()
|
||||
|
||||
print OK
|
||||
except :
|
||||
print ERREUR
|
||||
if self.debug :
|
||||
import traceback
|
||||
traceback.print_exc()
|
||||
return False
|
||||
|
||||
return True
|
||||
a = self.db.search('chbre=%s&paiement=ok' % chbre)
|
||||
a = a['adherent'] + a['club']
|
||||
if a and 'bloq' not in a[0].blacklist_actif() :
|
||||
# Il faut activer la prise
|
||||
anim('\tactivation chbre %s' % chbre)
|
||||
prise.enable()
|
||||
else :
|
||||
# Il faut désactiver la prise
|
||||
anim('\tdésactivation chbre %s' % chbre)
|
||||
prise.disable()
|
||||
|
||||
print OK
|
||||
except :
|
||||
print ERREUR
|
||||
if self.debug :
|
||||
import traceback
|
||||
traceback.print_exc()
|
||||
return False
|
||||
|
||||
return True
|
||||
|
||||
def configure_switch(self,switch) :
|
||||
self.aff = anim('\tconfiguration de %s' % switch)
|
||||
try:
|
||||
warn = self.__configure_switch(switch)
|
||||
self.aff.reinit()
|
||||
if warn :
|
||||
print WARNING
|
||||
if self.debug :
|
||||
sys.stderr.write(warn)
|
||||
else :
|
||||
print OK
|
||||
except :
|
||||
self.aff.reinit()
|
||||
print ERREUR
|
||||
self._restore()
|
||||
return 1
|
||||
self.aff = anim('\tconfiguration de %s' % switch)
|
||||
try:
|
||||
warn = self.__configure_switch(switch)
|
||||
self.aff.reinit()
|
||||
if warn :
|
||||
print WARNING
|
||||
if self.debug :
|
||||
sys.stderr.write(warn)
|
||||
else :
|
||||
print OK
|
||||
except :
|
||||
self.aff.reinit()
|
||||
print ERREUR
|
||||
self._restore()
|
||||
return 1
|
||||
|
||||
def __configure_switch(self,switch) :
|
||||
""" Génère le fichier de conf du switch donné """
|
||||
conn = hpswitch(switch)
|
||||
### Récupération données du switch
|
||||
# Batiment et num-Aéro du switch-b
|
||||
bat = switch[3].lower()
|
||||
""" Génère le fichier de conf du switch donné """
|
||||
conn = hpswitch(switch)
|
||||
### Récupération données du switch
|
||||
# Batiment et num-Aéro du switch-b
|
||||
bat = switch[3].lower()
|
||||
sw_num = int(switch[5])
|
||||
|
||||
# Conf radius
|
||||
from secrets import radius_key
|
||||
shuffle(self.rad_servs)
|
||||
from secrets import radius_key
|
||||
shuffle(self.rad_servs)
|
||||
rad = self.rad_template * len(self.rad_servs)
|
||||
params = { 'switch' : switch, 'bat' : bat.upper() ,
|
||||
'radius_key' : radius_key ,
|
||||
'radius-serveurs' : rad[:-1] % tuple(self.rad_servs)}
|
||||
params = { 'switch' : switch, 'bat' : bat.upper() ,
|
||||
'radius_key' : radius_key ,
|
||||
'radius-serveurs' : rad[:-1] % tuple(self.rad_servs)}
|
||||
|
||||
# Nombre de prises et modèle
|
||||
nb_prises = conn.nb_prises()
|
||||
modele = conn.version()
|
||||
if not nb_prises or not modele :
|
||||
raise RuntimeError("Erreur : impossible de déterminer les caractéristiques du switch.")
|
||||
params['modele'] = modele.split()[1]
|
||||
|
||||
# IP
|
||||
params['ip'] = commands.getoutput("host %s" % switch).split()[-1]
|
||||
|
||||
### Configuration prises
|
||||
params['INTERFACES_CONF'] = ''
|
||||
|
||||
# Dictionnaire prise -> chambre
|
||||
prise_chbres = reverse(bat)
|
||||
|
||||
# Prises occupées par des machines du Cr@ns
|
||||
crans_prises={}
|
||||
for m in self.db.search('prise=%s%i*' % (bat.upper(), sw_num))['machine'] :
|
||||
try: crans_prises[m.prise()].append(m)
|
||||
except: crans_prises[m.prise()] = [ m ]
|
||||
# Nombre de prises et modèle
|
||||
nb_prises = conn.nb_prises()
|
||||
modele = conn.version()
|
||||
if not nb_prises or not modele :
|
||||
raise RuntimeError("Erreur : impossible de déterminer les caractéristiques du switch.")
|
||||
params['modele'] = modele.split()[1]
|
||||
|
||||
# IP
|
||||
params['ip'] = commands.getoutput("host %s" % switch).split()[-1]
|
||||
|
||||
### Configuration prises
|
||||
params['INTERFACES_CONF'] = ''
|
||||
|
||||
# Dictionnaire prise -> chambre
|
||||
prise_chbres = reverse(bat)
|
||||
|
||||
# Prises occupées par des machines du Cr@ns
|
||||
crans_prises={}
|
||||
for m in self.db.search('prise=%s%i*' % (bat.upper(), sw_num))['machine'] :
|
||||
try: crans_prises[m.prise()].append(m)
|
||||
except: crans_prises[m.prise()] = [ m ]
|
||||
|
||||
self.aff.iter = nb_prises+1
|
||||
self.aff.iter = nb_prises+1
|
||||
|
||||
# Param-Aètres à affecter-b
|
||||
for key in ( 'uplinks', 'non_uplinks', 'prises_filtrage_mac' ) :
|
||||
|
@ -273,17 +273,17 @@ exit
|
|||
'default_tagged' : [] , 'default_untagged' : [] }
|
||||
|
||||
# G-Aénération de la conf de chaque prise-b
|
||||
for prise in range(1,nb_prises+1):
|
||||
self.aff.cycle()
|
||||
for prise in range(1,nb_prises+1):
|
||||
self.aff.cycle()
|
||||
|
||||
# Conf par d-Aéfaut : activée, autonégociation-b
|
||||
prise_params = { 'prise' : prise , 'speed' : '', 'etat' : '' }
|
||||
annu_prise = '%i%02i' % (sw_num, prise) # prise telle que notée dans l'annuaire
|
||||
|
||||
if uplink_prises[bat].has_key(int(annu_prise)) :
|
||||
### Prise d'uplink
|
||||
prise_params['nom'] = uplink_prises[bat][int(annu_prise)]
|
||||
params['uplinks'].append(prise)
|
||||
# Conf par d-Aéfaut : activée, autonégociation-b
|
||||
prise_params = { 'prise' : prise , 'speed' : '', 'etat' : '' }
|
||||
annu_prise = '%i%02i' % (sw_num, prise) # prise telle que notée dans l'annuaire
|
||||
|
||||
if uplink_prises[bat].has_key(int(annu_prise)) :
|
||||
### Prise d'uplink
|
||||
prise_params['nom'] = uplink_prises[bat][int(annu_prise)]
|
||||
params['uplinks'].append(prise)
|
||||
vlans['default_untagged'].append(prise)
|
||||
vlans['adm_tagged'].append(prise)
|
||||
vlans['wifi_tagged'].append(prise)
|
||||
|
@ -292,31 +292,31 @@ exit
|
|||
|
||||
params['non_uplinks'].append(prise)
|
||||
|
||||
if crans_prises.has_key("%s%s" % (bat.upper(), annu_prise)) :
|
||||
### Prise réservée à l'association
|
||||
wifi=0
|
||||
adm=0
|
||||
autres=0
|
||||
for m in crans_prises["%s%s" % (bat.upper(), annu_prise)] :
|
||||
if m.canal() : wifi+=1
|
||||
if crans_prises.has_key("%s%s" % (bat.upper(), annu_prise)) :
|
||||
### Prise réservée à l'association
|
||||
wifi=0
|
||||
adm=0
|
||||
autres=0
|
||||
for m in crans_prises["%s%s" % (bat.upper(), annu_prise)] :
|
||||
if m.canal() : wifi+=1
|
||||
elif m.Nom().find('.adm.crans.org')!=-1 : adm+=1
|
||||
else : autres+=1
|
||||
if autres==0 and adm==0 :
|
||||
# Vlan wifi uniquement
|
||||
else : autres+=1
|
||||
if autres==0 and adm==0 :
|
||||
# Vlan wifi uniquement
|
||||
if wifi == 1 :
|
||||
prise_params['nom'] = "Wifi_%s" % m.nom().split(".")[0]
|
||||
else :
|
||||
prise_params['nom'] = "Wifi"
|
||||
vlans['wifi_untagged'].append(prise)
|
||||
elif wifi==0 and autres==0 :
|
||||
# Vlan adm uniquement
|
||||
vlans['wifi_untagged'].append(prise)
|
||||
elif wifi==0 and autres==0 :
|
||||
# Vlan adm uniquement
|
||||
if amd == 1 :
|
||||
prise_params['nom'] = m.nom().split(".")[0]
|
||||
else :
|
||||
prise_params['nom'] = "Uplink_adm"
|
||||
vlans['adm_untagged'].append(prise)
|
||||
else :
|
||||
# Tous les vlans
|
||||
else :
|
||||
# Tous les vlans
|
||||
prise_params['nom'] = "Prise_crans"
|
||||
vlans['default_untagged'].append(prise)
|
||||
vlans['adm_tagged'].append(prise)
|
||||
|
@ -337,7 +337,7 @@ exit
|
|||
# Prise non référencée dans l'annuaire
|
||||
prise_params['nom'] = "Pas_dans_l'annuaire"
|
||||
prise_params['etat']='\n disable'
|
||||
params['INTERFACES_CONF'] += self.interface_template % prise_params
|
||||
params['INTERFACES_CONF'] += self.interface_template % prise_params
|
||||
continue
|
||||
|
||||
params['prises_filtrage_mac'].append(prise)
|
||||
|
@ -348,9 +348,9 @@ exit
|
|||
if len(chbres) > 1 : prise_params['nom'] += 's'
|
||||
for chbre in chbres :
|
||||
prise_params['nom'] += '_%s%s' % (bat.upper(), chbre)
|
||||
|
||||
|
||||
# Besoin d'activer la prise ?
|
||||
prise_params['etat']='\n disable'
|
||||
prise_params['etat']='\n disable'
|
||||
for chbre in chbres :
|
||||
res = self.db.search('chbre=%s%s&paiement=ok' % (bat.upper(), chbre) )
|
||||
for res in res['adherent'] + res['club'] :
|
||||
|
@ -358,48 +358,48 @@ exit
|
|||
prise_params['etat']=''
|
||||
break
|
||||
|
||||
params['INTERFACES_CONF'] += self.interface_template % prise_params
|
||||
params['INTERFACES_CONF'] += self.interface_template % prise_params
|
||||
|
||||
# Petite verif
|
||||
if not params['uplinks'] or not params['non_uplinks'] :
|
||||
raise RuntimeError('Switch sans uplink ou sans prise adhérent.')
|
||||
|
||||
def mk_list(liste_prise) :
|
||||
"""
|
||||
transforme une liste de prises en une chaine pour le switch
|
||||
exemple : 1, 3, 4, 5, 6, 7, 9, 10, 11, 12 => 1,3-7,9-12
|
||||
"""
|
||||
# Petite verif
|
||||
if not params['uplinks'] or not params['non_uplinks'] :
|
||||
raise RuntimeError('Switch sans uplink ou sans prise adhérent.')
|
||||
|
||||
def mk_list(liste_prise) :
|
||||
"""
|
||||
transforme une liste de prises en une chaine pour le switch
|
||||
exemple : 1, 3, 4, 5, 6, 7, 9, 10, 11, 12 => 1,3-7,9-12
|
||||
"""
|
||||
if not liste_prise : return ''
|
||||
liste_prise.sort()
|
||||
liste_prise.sort()
|
||||
|
||||
# initialisation
|
||||
i = liste_prise.pop(0)
|
||||
groupe = [ i, i ]
|
||||
result = []
|
||||
|
||||
liste_prise.append(9999) # apparaitra jamais dans la liste
|
||||
|
||||
while liste_prise :
|
||||
nouveau = liste_prise.pop(0)
|
||||
if nouveau == groupe[1] + 1 :
|
||||
groupe[1] += 1
|
||||
else :
|
||||
# Ajout du groupe au résultat
|
||||
if groupe[0] == groupe[1] :
|
||||
result.append(str(groupe[0]))
|
||||
else :
|
||||
result.append('-'.join(map(str,groupe)))
|
||||
# Réinit de groupe
|
||||
groupe = [ nouveau, nouveau ]
|
||||
|
||||
return ','.join(result)
|
||||
# initialisation
|
||||
i = liste_prise.pop(0)
|
||||
groupe = [ i, i ]
|
||||
result = []
|
||||
|
||||
liste_prise.append(9999) # apparaitra jamais dans la liste
|
||||
|
||||
while liste_prise :
|
||||
nouveau = liste_prise.pop(0)
|
||||
if nouveau == groupe[1] + 1 :
|
||||
groupe[1] += 1
|
||||
else :
|
||||
# Ajout du groupe au résultat
|
||||
if groupe[0] == groupe[1] :
|
||||
result.append(str(groupe[0]))
|
||||
else :
|
||||
result.append('-'.join(map(str,groupe)))
|
||||
# Réinit de groupe
|
||||
groupe = [ nouveau, nouveau ]
|
||||
|
||||
return ','.join(result)
|
||||
|
||||
# Saut de ligne parasite
|
||||
params['INTERFACES_CONF'] = params['INTERFACES_CONF'][:-1]
|
||||
|
||||
# Conversion des listes
|
||||
for key in [ 'prises_filtrage_mac', 'uplinks', 'non_uplinks' ] :
|
||||
params[key] = mk_list(params[key])
|
||||
|
||||
# Conversion des listes
|
||||
for key in [ 'prises_filtrage_mac', 'uplinks', 'non_uplinks' ] :
|
||||
params[key] = mk_list(params[key])
|
||||
for key, prises in vlans.items() :
|
||||
vlans[key]=mk_list(prises)
|
||||
|
||||
|
@ -414,19 +414,19 @@ exit
|
|||
|
||||
# Ecriture
|
||||
fd = self._open_conf(self.CONF_REP + switch + '.conf')
|
||||
fd.write(self.config % params)
|
||||
fd.close()
|
||||
|
||||
fd.write(self.config % params)
|
||||
fd.close()
|
||||
|
||||
if __name__ == '__main__' :
|
||||
if '-h' in sys.argv or '--help' in sys.argv or len(sys.argv) == 1 :
|
||||
print "%s <switch>" % sys.argv[0].split('/')[-1].split('.')[0]
|
||||
print "Génération du fichier de configuration des switchs donnés."
|
||||
sys.exit(255)
|
||||
print "%s <switch>" % sys.argv[0].split('/')[-1].split('.')[0]
|
||||
print "Génération du fichier de configuration des switchs donnés."
|
||||
sys.exit(255)
|
||||
|
||||
if sys.argv[1] == 'all' :
|
||||
switchs = all_switchs()
|
||||
switchs = all_switchs()
|
||||
else :
|
||||
switchs = tuple(sys.argv[1:])
|
||||
switchs = tuple(sys.argv[1:])
|
||||
sw = switch(switchs)
|
||||
sw.debug = 1
|
||||
sw.reconfigure()
|
||||
|
|
|
@ -48,12 +48,12 @@ class conf_wifi_ng(gen_config) :
|
|||
clients = self.db.search('host=*.wifi.crans.org&paiement=ok')['machine'] + \
|
||||
invite().machines()
|
||||
bornes = self.db.search('host=*.wifi.crans.org&ipsec!=*')['machine']
|
||||
|
||||
print OK
|
||||
|
||||
print OK
|
||||
self.gen_isakmpd(clients)
|
||||
self.gen_macip(clients, bornes)
|
||||
self.gen_bornes(bornes)
|
||||
self.anim=anim('\tfin reconfigurations')
|
||||
self.anim=anim('\tfin reconfigurations')
|
||||
|
||||
def gen_bornes(self, bornes):
|
||||
"""Génération de la configuration des bornes"""
|
||||
|
@ -64,7 +64,7 @@ class conf_wifi_ng(gen_config) :
|
|||
COMMON = "%s/common" % ROOT
|
||||
DEFAULT = "%s/default" % ROOT
|
||||
for borne in bornes:
|
||||
self.anim=anim('\treconfiguration de %s' % borne.nom())
|
||||
self.anim=anim('\treconfiguration de %s' % borne.nom())
|
||||
# Il s'agit de faire l'union du répertoire common et du
|
||||
# répertoire propre (s'il existe) ou alors du répertoire default
|
||||
# On supprime le répertoire de travail
|
||||
|
@ -134,7 +134,7 @@ NVRAM_wl0_radio=%(ON)d
|
|||
self.anim.cycle()
|
||||
if 'bloq' in machine.blacklist_actif() : continue
|
||||
fd.write("%s %s\n" % (machine.mac(), machine.ip()))
|
||||
self.anim.reinit()
|
||||
self.anim.reinit()
|
||||
print OK
|
||||
|
||||
def gen_isakmpd(self, clients):
|
||||
|
@ -240,5 +240,5 @@ Netmask= 0.0.0.0
|
|||
fd.write(blocs)
|
||||
fd.write(net_crans)
|
||||
fd.close()
|
||||
self.anim.reinit()
|
||||
self.anim.reinit()
|
||||
print OK
|
||||
|
|
|
@ -387,7 +387,7 @@ if __name__ == '__main__' :
|
|||
except getopt.error, msg :
|
||||
print msg
|
||||
sys.exit(1)
|
||||
|
||||
|
||||
cmds = []
|
||||
firmware=''
|
||||
for opt, val in options :
|
||||
|
@ -395,28 +395,28 @@ if __name__ == '__main__' :
|
|||
print "Usage : %s [[-c commande1] -c commande2...] [-U firmware] regex "
|
||||
print "Envoi les commandes données au switchs matchant la regex"
|
||||
print "si aucune commande est founie lit l'entree standart"
|
||||
print "L'envoi de firmware ne fait pas rebooter le switch"
|
||||
print "L'envoi de firmware ne fait pas rebooter le switch"
|
||||
sys.exit(0)
|
||||
|
||||
elif opt=='-c' :
|
||||
cmds.append(val)
|
||||
|
||||
elif opt=='-U' :
|
||||
firmware=val
|
||||
|
||||
|
||||
elif opt=='-U' :
|
||||
firmware=val
|
||||
|
||||
# Quels switchs ?
|
||||
switchs=[]
|
||||
if arg :
|
||||
re=sre.compile(arg[0])
|
||||
for sw in all_switchs() :
|
||||
if re.match(sw) :
|
||||
switchs.append(sw)
|
||||
|
||||
re=sre.compile(arg[0])
|
||||
for sw in all_switchs() :
|
||||
if re.match(sw) :
|
||||
switchs.append(sw)
|
||||
|
||||
if not switchs :
|
||||
print "Aucun switch trouvé"
|
||||
print "Note : il faut une _regex_ (!= wilcards au sens du shell)"
|
||||
sys.exit(3)
|
||||
|
||||
print "Aucun switch trouvé"
|
||||
print "Note : il faut une _regex_ (!= wilcards au sens du shell)"
|
||||
sys.exit(3)
|
||||
|
||||
if not cmds and not firmware :
|
||||
cmds=map(str.strip,sys.stdin.readlines())
|
||||
|
||||
|
@ -429,13 +429,13 @@ if __name__ == '__main__' :
|
|||
|
||||
for sw in switchs :
|
||||
print sw
|
||||
try:
|
||||
try:
|
||||
# Au cas ou le switch ne répondrai pas
|
||||
s = hpswitch(sw)
|
||||
if firmware :
|
||||
s.upgrade(firmware)
|
||||
if firmware :
|
||||
s.upgrade(firmware)
|
||||
for cmd in cmds :
|
||||
print s.send_cmd(cmd)
|
||||
except :
|
||||
print 'ERREUR'
|
||||
|
||||
|
||||
|
|
|
@ -185,16 +185,16 @@ def format_mac(mac) :
|
|||
class service :
|
||||
""" Défini un service à redémarrer """
|
||||
def __init__(self,nom,args=[],start=[]) :
|
||||
""" nom du service
|
||||
liste des arguments
|
||||
liste d'horaires de démarages """
|
||||
self.nom=nom
|
||||
self.args=args
|
||||
self.start=map(int,start)
|
||||
|
||||
""" nom du service
|
||||
liste des arguments
|
||||
liste d'horaires de démarages """
|
||||
self.nom=nom
|
||||
self.args=args
|
||||
self.start=map(int,start)
|
||||
|
||||
def __str__(self) :
|
||||
return "%s(%s) à partir du %s" % (self.nom, \
|
||||
','.join(self.args), \
|
||||
return "%s(%s) à partir du %s" % (self.nom, \
|
||||
','.join(self.args), \
|
||||
' et '.join(map(lambda t:time.strftime(date_format,time.gmtime(t)), self.start)))
|
||||
|
||||
class crans_ldap :
|
||||
|
@ -234,9 +234,9 @@ class crans_ldap :
|
|||
|
||||
def __del__(self) :
|
||||
# Destruction des locks résiduels
|
||||
if hasattr(self,'_locks') :
|
||||
for lock in self._locks :
|
||||
self.remove_lock(lock)
|
||||
if hasattr(self,'_locks') :
|
||||
for lock in self._locks :
|
||||
self.remove_lock(lock)
|
||||
|
||||
def connect(self):
|
||||
""" Initialisation des connexion vers le serveur LDAP """
|
||||
|
@ -368,16 +368,16 @@ class crans_ldap :
|
|||
if l != lockid :
|
||||
# C'est locké par un autre process que le notre
|
||||
# il tourne encore ?
|
||||
if l.split('-')[0] == hostname and os.system('ps %s > /dev/null 2>&1' % l.split('-')[1] ) :
|
||||
# Il ne tourne plus
|
||||
self.remove_lock(res[0]) # delock
|
||||
return self.lock(item,valeur) # relock
|
||||
if l.split('-')[0] == hostname and os.system('ps %s > /dev/null 2>&1' % l.split('-')[1] ) :
|
||||
# Il ne tourne plus
|
||||
self.remove_lock(res[0]) # delock
|
||||
return self.lock(item,valeur) # relock
|
||||
raise EnvironmentError(u'Objet (%s=%s) locké, patienter.' % (item, valeur), l)
|
||||
else :
|
||||
if not hasattr(self,'_locks') :
|
||||
self._locks = [lock_dn]
|
||||
else :
|
||||
self._locks.append(lock_dn)
|
||||
else :
|
||||
if not hasattr(self,'_locks') :
|
||||
self._locks = [lock_dn]
|
||||
else :
|
||||
self._locks.append(lock_dn)
|
||||
|
||||
def remove_lock(self,lockdn) :
|
||||
""" Destruction d'un lock
|
||||
|
@ -385,11 +385,11 @@ class crans_ldap :
|
|||
# Mettre des verifs ?
|
||||
if lockdn!='*' :
|
||||
self.conn.delete_s(lockdn)
|
||||
try:
|
||||
self._locks.remove(lockdn)
|
||||
except:
|
||||
# Pas grave si ca foire, le lock n'y est plus
|
||||
pass
|
||||
try:
|
||||
self._locks.remove(lockdn)
|
||||
except:
|
||||
# Pas grave si ca foire, le lock n'y est plus
|
||||
pass
|
||||
else :
|
||||
locks = self.list_locks()
|
||||
for l in locks :
|
||||
|
@ -403,78 +403,78 @@ class crans_ldap :
|
|||
""" Si new = None retourne la liste des services à redémarrer
|
||||
Si new est fourni et ne commence pas par - ajoute le service à la liste
|
||||
avec les arguments args (args doit être une liste).
|
||||
start indique la date (secondes depuis epoch) à partir du moment ou
|
||||
cette action doit être effectué
|
||||
start indique la date (secondes depuis epoch) à partir du moment ou
|
||||
cette action doit être effectué
|
||||
Si new commence par - supprime le service si son start est plus vieux que maintenant
|
||||
Si new commence par -- supprime dans condition.
|
||||
Si new commence par -- supprime dans condition.
|
||||
"""
|
||||
if new : new = preattr(new)[1]
|
||||
|
||||
if new : new = preattr(new)[1]
|
||||
|
||||
# Quels services sont déjà à redémarrer ?
|
||||
serv = {} # { service : [ arguments ] }
|
||||
serv_dates = {} # { service : [ dates de restart ] }
|
||||
services = []
|
||||
serv_dates = {} # { service : [ dates de restart ] }
|
||||
services = []
|
||||
for s in self.conn.search_s(self.base_services,1,'objectClass=service') :
|
||||
s=s[1]
|
||||
serv[s['cn'][0]] = s.get('args',[])
|
||||
serv_dates[s['cn'][0]] = s.get('start',[])
|
||||
services.append(service(s['cn'][0],s.get('args',[]),s.get('start',[])))
|
||||
|
||||
# Retourne la liste des services à redémarrer
|
||||
if not new : return services
|
||||
serv_dates[s['cn'][0]] = s.get('start',[])
|
||||
services.append(service(s['cn'][0],s.get('args',[]),s.get('start',[])))
|
||||
|
||||
# Retourne la liste des services à redémarrer
|
||||
if not new : return services
|
||||
|
||||
# Effacement d'un service
|
||||
if new[0] == '-' :
|
||||
if new[1] == '-' :
|
||||
# Double -- on enlève quelque soit la date
|
||||
remove_dn='cn=%s,%s' % ( new[2:], self.base_services )
|
||||
else :
|
||||
# On enlève uniquement si la date est passée
|
||||
remove_dn='cn=%s,%s' % ( new[1:], self.base_services )
|
||||
if not serv.has_key(new[1:]) :
|
||||
# Existe pas => rien à faire
|
||||
return
|
||||
keep_date=[]
|
||||
for date in serv_dates[new[1:]] :
|
||||
if time.time() < int(date) :
|
||||
keep_date.append(date)
|
||||
if keep_date :
|
||||
self.conn.modify_s(remove_dn,ldap.modlist.modifyModlist({'start' : serv_dates[new[1:]]}, { 'start' : keep_date }))
|
||||
remove_dn=None
|
||||
|
||||
if remove_dn :
|
||||
# Supression
|
||||
try : self.conn.delete_s(remove_dn)
|
||||
except : pass
|
||||
# Si n'existe pas => Erreur mais le résultat est la.
|
||||
return
|
||||
# Effacement d'un service
|
||||
if new[0] == '-' :
|
||||
if new[1] == '-' :
|
||||
# Double -- on enlève quelque soit la date
|
||||
remove_dn='cn=%s,%s' % ( new[2:], self.base_services )
|
||||
else :
|
||||
# On enlève uniquement si la date est passée
|
||||
remove_dn='cn=%s,%s' % ( new[1:], self.base_services )
|
||||
if not serv.has_key(new[1:]) :
|
||||
# Existe pas => rien à faire
|
||||
return
|
||||
keep_date=[]
|
||||
for date in serv_dates[new[1:]] :
|
||||
if time.time() < int(date) :
|
||||
keep_date.append(date)
|
||||
if keep_date :
|
||||
self.conn.modify_s(remove_dn,ldap.modlist.modifyModlist({'start' : serv_dates[new[1:]]}, { 'start' : keep_date }))
|
||||
remove_dn=None
|
||||
|
||||
if remove_dn :
|
||||
# Supression
|
||||
try : self.conn.delete_s(remove_dn)
|
||||
except : pass
|
||||
# Si n'existe pas => Erreur mais le résultat est la.
|
||||
return
|
||||
|
||||
serv_dn = 'cn=%s,%s' % ( new, self.base_services )
|
||||
|
||||
# Petite fonction à appliquer aux arguments
|
||||
if type(args) == str : args = [ args ]
|
||||
if type(args) == str : args = [ args ]
|
||||
args=map(lambda x:preattr(x)[1] ,args)
|
||||
if type(start) == int : start = [ start ]
|
||||
start=map(lambda x:preattr(x)[1] ,start)
|
||||
|
||||
if type(start) == int : start = [ start ]
|
||||
start=map(lambda x:preattr(x)[1] ,start)
|
||||
|
||||
if new in serv.keys() :
|
||||
modlist = []
|
||||
|
||||
modlist = []
|
||||
|
||||
new_args = []
|
||||
# Nouveaux arguments ?
|
||||
# Nouveaux arguments ?
|
||||
for arg in args :
|
||||
if arg not in serv[new] :
|
||||
new_args.append(arg)
|
||||
if new_args :
|
||||
modlist += ldap.modlist.modifyModlist({ 'args' : serv[new]}, { 'args' : serv[new] + new_args })
|
||||
|
||||
new_date = []
|
||||
# Nouvelle date ?
|
||||
for date in start :
|
||||
if date not in serv_dates[new] :
|
||||
new_date.append(date)
|
||||
if new_date :
|
||||
modlist += ldap.modlist.modifyModlist({'start' : serv_dates[new]}, { 'start' : serv_dates[new] + new_date })
|
||||
if new_args :
|
||||
modlist += ldap.modlist.modifyModlist({ 'args' : serv[new]}, { 'args' : serv[new] + new_args })
|
||||
|
||||
new_date = []
|
||||
# Nouvelle date ?
|
||||
for date in start :
|
||||
if date not in serv_dates[new] :
|
||||
new_date.append(date)
|
||||
if new_date :
|
||||
modlist += ldap.modlist.modifyModlist({'start' : serv_dates[new]}, { 'start' : serv_dates[new] + new_date })
|
||||
|
||||
if modlist :
|
||||
try :
|
||||
|
@ -484,11 +484,11 @@ class crans_ldap :
|
|||
pass
|
||||
# else rien à faire
|
||||
else :
|
||||
# Entrée non présente -> ajout
|
||||
# Entrée non présente -> ajout
|
||||
modlist = ldap.modlist.addModlist({ 'objectClass' : 'service' ,
|
||||
'cn' : new ,
|
||||
'args' : args ,
|
||||
'start' : start } )
|
||||
'start' : start } )
|
||||
try :
|
||||
self.conn.add_s(serv_dn,modlist)
|
||||
except ldap.ALREADY_EXISTS :
|
||||
|
@ -533,8 +533,8 @@ class crans_ldap :
|
|||
el = '(%s=%s*)' % ( champ, expr)
|
||||
elif champ == 'macAddress' :
|
||||
# Formatage adresse mac
|
||||
try: el = '(macAddress=%s)' % format_mac(expr)
|
||||
except : pass
|
||||
try: el = '(macAddress=%s)' % format_mac(expr)
|
||||
except : pass
|
||||
elif champ == 'paiement' and expr == 'ok' :
|
||||
# Paiement donnant droit à une connexion maintenant ?
|
||||
# il doit avoir payé pour
|
||||
|
@ -620,14 +620,14 @@ class crans_ldap :
|
|||
if not r['machine'] and not r['adherent'] and not r['club'] :
|
||||
# Pas de réponses
|
||||
return result
|
||||
elif len(conds) == 1 :
|
||||
# Filtre sur un seul champ
|
||||
# => on retourne tout
|
||||
for i in filtres :
|
||||
if not r[i] : continue
|
||||
for res in r[i] :
|
||||
result[i].append(globals()[i](res,mode,self.conn))
|
||||
elif not r['adherent'] and not r['club'] :
|
||||
elif len(conds) == 1 :
|
||||
# Filtre sur un seul champ
|
||||
# => on retourne tout
|
||||
for i in filtres :
|
||||
if not r[i] : continue
|
||||
for res in r[i] :
|
||||
result[i].append(globals()[i](res,mode,self.conn))
|
||||
elif not r['adherent'] and not r['club'] :
|
||||
# Il n'y avait seulement un filtre machine
|
||||
# => on retourne uniquement les machines trouvées
|
||||
for m in r['machine'] :
|
||||
|
@ -810,26 +810,26 @@ class base_classes_crans(crans_ldap) :
|
|||
# Verif que les dates sont OK
|
||||
if new[0] == 'now' :
|
||||
new[0] = time.strftime(date_format)
|
||||
debut=0
|
||||
debut=0
|
||||
else :
|
||||
try : debut=int(time.mktime(time.strptime(new[0],date_format)))
|
||||
except : raise ValueError(u'Date de début blacklist invalide')
|
||||
|
||||
if new[1] == 'now' :
|
||||
if new[1] == 'now' :
|
||||
new[1] = time.strftime(date_format)
|
||||
fin=0
|
||||
elif new[1]!='-' :
|
||||
fin=0
|
||||
elif new[1]!='-' :
|
||||
try : fin=int(time.mktime(time.strptime(new[1],date_format)))
|
||||
except : raise ValueError(u'Date de fin blacklist invalide')
|
||||
else :
|
||||
fin = -1
|
||||
else :
|
||||
fin = -1
|
||||
|
||||
if debut == fin :
|
||||
raise ValueError(u'Dates de début et fin identiques')
|
||||
if debut == fin :
|
||||
raise ValueError(u'Dates de début et fin identiques')
|
||||
|
||||
# On d-Aépasse la fin de sanction d'1min pour être sur quelle périmé.-b
|
||||
fin=fin+60
|
||||
|
||||
|
||||
new_c = ','.join(new)
|
||||
new_c = preattr(new_c)[1]
|
||||
|
||||
|
@ -841,16 +841,16 @@ class base_classes_crans(crans_ldap) :
|
|||
if self._data['blacklist'] != liste :
|
||||
self._data['blacklist']=liste
|
||||
self.modifs.append('blacklist_' + new[2])
|
||||
if not hasattr(self,"_blacklist_restart") :
|
||||
self._blacklist_restart={}
|
||||
if not self._blacklist_restart.has_key(new[2]) :
|
||||
self._blacklist_restart[new[2]] = [ debut, fin ]
|
||||
else :
|
||||
if debut not in self._blacklist_restart[new[2]] :
|
||||
self._blacklist_restart[new[2]].append(debut)
|
||||
if fin!=-1 and fin not in self._blacklist_restart[new[2]] :
|
||||
self._blacklist_restart[new[2]].append(fin)
|
||||
|
||||
if not hasattr(self,"_blacklist_restart") :
|
||||
self._blacklist_restart={}
|
||||
if not self._blacklist_restart.has_key(new[2]) :
|
||||
self._blacklist_restart[new[2]] = [ debut, fin ]
|
||||
else :
|
||||
if debut not in self._blacklist_restart[new[2]] :
|
||||
self._blacklist_restart[new[2]].append(debut)
|
||||
if fin!=-1 and fin not in self._blacklist_restart[new[2]] :
|
||||
self._blacklist_restart[new[2]].append(fin)
|
||||
|
||||
return liste
|
||||
|
||||
def restore(self) :
|
||||
|
@ -925,13 +925,13 @@ class base_classes_crans(crans_ldap) :
|
|||
modif = modif.replace("solde", "debit %s Euros" % str(diff) )
|
||||
else :
|
||||
modif = modif.replace("solde", "credit %s Euros" % str(-diff) )
|
||||
|
||||
if 'droits' in self.modifs:
|
||||
anciens_droits = self._init_data.get('droits',[])
|
||||
nouveaux_droits = self._data.get('droits',[])
|
||||
droits_ajoutes = ''.join( [ '+%s' % decode(d) for d in nouveaux_droits if d not in anciens_droits ] )
|
||||
droits_enleves = ''.join( [ '-%s' % decode(d) for d in anciens_droits if d not in nouveaux_droits ] )
|
||||
modif = modif.replace("droits", "droits : " + droits_ajoutes + droits_enleves )
|
||||
|
||||
if 'droits' in self.modifs:
|
||||
anciens_droits = self._init_data.get('droits',[])
|
||||
nouveaux_droits = self._data.get('droits',[])
|
||||
droits_ajoutes = ''.join( [ '+%s' % decode(d) for d in nouveaux_droits if d not in anciens_droits ] )
|
||||
droits_enleves = ''.join( [ '-%s' % decode(d) for d in anciens_droits if d not in nouveaux_droits ] )
|
||||
modif = modif.replace("droits", "droits : " + droits_ajoutes + droits_enleves )
|
||||
|
||||
timestamp = localtime()
|
||||
hist = "%s, %s" % ( time.strftime(date_format, timestamp), script_utilisateur )
|
||||
|
@ -996,9 +996,9 @@ class base_classes_crans(crans_ldap) :
|
|||
|
||||
### Génération de la liste de services à redémarrer
|
||||
# Quasiement tout est traité dans les classes filles.
|
||||
if hasattr(self,"_blacklist_restart") :
|
||||
for n,t in self._blacklist_restart.items() :
|
||||
self.services_to_restart("blacklist_%s"%n,[],t)
|
||||
if hasattr(self,"_blacklist_restart") :
|
||||
for n,t in self._blacklist_restart.items() :
|
||||
self.services_to_restart("blacklist_%s"%n,[],t)
|
||||
|
||||
# Reinitialisation
|
||||
self._init_data = self._data.copy()
|
||||
|
@ -2182,8 +2182,8 @@ class machine(base_classes_crans) :
|
|||
|
||||
def exempt(self,new=None) :
|
||||
"""
|
||||
Liste des réseaux vers lesquels on ne compte pas l'upload
|
||||
Cette liste est transférée dans la base postgres de komaz
|
||||
Liste des réseaux vers lesquels on ne compte pas l'upload
|
||||
Cette liste est transférée dans la base postgres de komaz
|
||||
Pour ajouter un réseau new doit être la chaîne
|
||||
représentant le réseau à ajouter
|
||||
Pour modifier new doit être une liste de la forme :
|
||||
|
@ -2384,7 +2384,7 @@ class machine(base_classes_crans) :
|
|||
self.services_to_restart('conf_wifi_ng')
|
||||
|
||||
# Reconfiguration clients wifi ?
|
||||
if self.__typ in ('wifi','borne') and ( 'ipHostNumber' in self.modifs or 'host' in self.modifs or 'macAddress' in self.modifs ) :
|
||||
if self.__typ in ('wifi','borne') and ( 'ipHostNumber' in self.modifs or 'host' in self.modifs or 'macAddress' in self.modifs ) :
|
||||
self.services_to_restart('conf_wifi_ng')
|
||||
|
||||
# Regénération blackliste nécessaire ?
|
||||
|
@ -2398,10 +2398,10 @@ class machine(base_classes_crans) :
|
|||
self.services_to_restart('autostatus')
|
||||
self.services_to_restart('mail_modif',['ip=%s' % self.ip()])
|
||||
|
||||
# Synchronisation avec la base pgsql pour les exemptions
|
||||
if 'exempt' in self.modifs or 'ipHostNumber' in self.modifs :
|
||||
self.services_to_restart('exemptions')
|
||||
|
||||
# Synchronisation avec la base pgsql pour les exemptions
|
||||
if 'exempt' in self.modifs or 'ipHostNumber' in self.modifs :
|
||||
self.services_to_restart('exemptions')
|
||||
|
||||
# Remise à zéro
|
||||
self.modifs=[]
|
||||
|
||||
|
|
|
@ -18,8 +18,8 @@ License: Python Software Foundation License
|
|||
|
||||
Noah Spurrier
|
||||
|
||||
$Revision: 1.1 $
|
||||
$Date: 2005-03-05 15:43:59 $
|
||||
$Revision: 1.2 $
|
||||
$Date: 2005-10-18 08:38:22 $
|
||||
"""
|
||||
|
||||
|
||||
|
@ -43,7 +43,7 @@ Currently pexpect is intended for UNIX operating systems."""
|
|||
|
||||
|
||||
__version__ = '0.999'
|
||||
__revision__ = '$Revision: 1.1 $'
|
||||
__revision__ = '$Revision: 1.2 $'
|
||||
__all__ = ['ExceptionPexpect', 'EOF', 'TIMEOUT', 'spawn', 'run',
|
||||
'__version__', '__revision__']
|
||||
|
||||
|
@ -682,8 +682,8 @@ class spawn:
|
|||
else:
|
||||
raise
|
||||
except TIMEOUT:
|
||||
self.before = incoming
|
||||
self.after = TIMEOUT
|
||||
self.before = incoming
|
||||
self.after = TIMEOUT
|
||||
if TIMEOUT in pattern_list:
|
||||
#self.buffer = ''
|
||||
return pattern_list.index(TIMEOUT)
|
||||
|
@ -737,16 +737,16 @@ class spawn:
|
|||
incoming = incoming + c
|
||||
|
||||
except EOF:
|
||||
self.before = incoming
|
||||
self.after = EOF
|
||||
self.before = incoming
|
||||
self.after = EOF
|
||||
if EOF in pattern_list:
|
||||
#self.buffer = ''
|
||||
return pattern_list.index(EOF)
|
||||
else:
|
||||
raise
|
||||
except TIMEOUT:
|
||||
self.before = incoming
|
||||
self.after = TIMEOUT
|
||||
self.before = incoming
|
||||
self.after = TIMEOUT
|
||||
if TIMEOUT in pattern_list:
|
||||
#self.buffer = ''
|
||||
return pattern_list.index(TIMEOUT)
|
||||
|
|
|
@ -19,22 +19,22 @@ from ldap_crans import mailexist
|
|||
def load(file) :
|
||||
""" Charge l'objet (adhérent, machine ou club contenu dans le fichier fourni """
|
||||
try :
|
||||
fd=open(file,'rb')
|
||||
fd=open(file,'rb')
|
||||
except :
|
||||
print "Impossible d'ouvrir le fichier demandé."
|
||||
sys.exit(1)
|
||||
print "Impossible d'ouvrir le fichier demandé."
|
||||
sys.exit(1)
|
||||
|
||||
obj = cPickle.load(fd)
|
||||
|
||||
try :
|
||||
# Si machine vérif si le proprio est encore dans la base
|
||||
test_proprio = obj.proprietaire()
|
||||
if test_proprio.Nom() != obj.proprio :
|
||||
raise
|
||||
# Propriétaire encore dans la base => on récupère les infos de la base
|
||||
del obj.proprio
|
||||
# Si machine vérif si le proprio est encore dans la base
|
||||
test_proprio = obj.proprietaire()
|
||||
if test_proprio.Nom() != obj.proprio :
|
||||
raise
|
||||
# Propriétaire encore dans la base => on récupère les infos de la base
|
||||
del obj.proprio
|
||||
except :
|
||||
pass
|
||||
pass
|
||||
|
||||
### Modifs pour permettre une restauration
|
||||
# On supprime les infos de aid, mid ou cid
|
||||
|
@ -56,23 +56,23 @@ aff(obj)
|
|||
|
||||
def restore_adher(adh) :
|
||||
if adh.compte() and mailexist(adh.compte()) :
|
||||
print "AVERTISSEMENT : le login %s à déja été réattribué." % adh.compte()
|
||||
print " il faudra recréer un compte avec un login différent"
|
||||
prompt('Appuyez sur ENTREE pour continuer')
|
||||
adh._data['mail'] = []
|
||||
print "AVERTISSEMENT : le login %s à déja été réattribué." % adh.compte()
|
||||
print " il faudra recréer un compte avec un login différent"
|
||||
prompt('Appuyez sur ENTREE pour continuer')
|
||||
adh._data['mail'] = []
|
||||
modif_adher(adh)
|
||||
|
||||
|
||||
def restore_machine(machine) :
|
||||
try :
|
||||
obj.proprio # crash si l'adhérent est encore dans la base
|
||||
# L'adhérent est plus dans la base
|
||||
t = prompt("Ratacher la machine à un [C]lub ou un [A]dhérent ?")
|
||||
t = t.lower()
|
||||
if t in 'ac' :
|
||||
i = prompt("Entrez l'%sid auquel ratacher la machine : %sid =" % (t,t) )
|
||||
machine.dn = '%sid=%s,%s' % (t, i, machine.dn.split(',',1)[1] )
|
||||
obj.proprio # crash si l'adhérent est encore dans la base
|
||||
# L'adhérent est plus dans la base
|
||||
t = prompt("Ratacher la machine à un [C]lub ou un [A]dhérent ?")
|
||||
t = t.lower()
|
||||
if t in 'ac' :
|
||||
i = prompt("Entrez l'%sid auquel ratacher la machine : %sid =" % (t,t) )
|
||||
machine.dn = '%sid=%s,%s' % (t, i, machine.dn.split(',',1)[1] )
|
||||
except :
|
||||
pass
|
||||
pass
|
||||
set_machine(machine)
|
||||
|
||||
def restore_club(club) :
|
||||
|
|
|
@ -16,7 +16,7 @@ for droit in [ u'Nounou', u'Apprenti', u'Mod
|
|||
|
||||
txt = '%s\n' % droit
|
||||
for adh in adhs :
|
||||
noms.append(u'%s' % adh.Nom().encode('iso-8859-1'))
|
||||
noms.append(u'%s' % adh.Nom().encode('iso-8859-1'))
|
||||
|
||||
txt += u' %s' % '\n '.join(noms)
|
||||
|
||||
|
|
|
@ -15,9 +15,9 @@ txts = []
|
|||
for m in machines :
|
||||
# on vérifie qu'on l'a pas encore traité
|
||||
if m.ip() in done :
|
||||
continue
|
||||
continue
|
||||
if m.proprietaire().__class__ == crans :
|
||||
continue
|
||||
continue
|
||||
done.append(m.ip())
|
||||
|
||||
# texte pour la machine
|
||||
|
@ -25,13 +25,13 @@ for m in machines :
|
|||
txt += u'Propriétaire : %s\n' % m.proprietaire().Nom().encode('iso-8859-1')
|
||||
txt += u'Machine : %s\n' % m.nom()
|
||||
if m.portTCPin() :
|
||||
txt += u'ports TCP in : %s\n' % m.portTCPin()
|
||||
txt += u'ports TCP in : %s\n' % m.portTCPin()
|
||||
if m.portTCPout() :
|
||||
txt += u'ports TCP out : %s\n' % m.portTCPout()
|
||||
txt += u'ports TCP out : %s\n' % m.portTCPout()
|
||||
if m.portUDPin() :
|
||||
txt += u'ports UDP in : %s\n' % m.portUDPin()
|
||||
txt += u'ports UDP in : %s\n' % m.portUDPin()
|
||||
if m.portUDPout() :
|
||||
txt += u'ports UDP out : %s\n' % m.portUDPout()
|
||||
txt += u'ports UDP out : %s\n' % m.portUDPout()
|
||||
|
||||
txts.append(txt.strip())
|
||||
|
||||
|
|
|
@ -14,9 +14,9 @@ txts = []
|
|||
|
||||
for c in comptes :
|
||||
if not c.compte() :
|
||||
continue
|
||||
continue
|
||||
quota = getoutput('quota %s | grep "/dev/" | awk \'{ print $1" "$3" "$4 }\'' % c.compte() )
|
||||
if quota != '/dev/sda1 400000 600000\n/dev/sda2 102400 153600' and quota != '/dev/sda2 102400 153600\n/dev/sda1 400000 600000' :
|
||||
txts.append( '%s (%s)\n%s' % (c.Nom(), c.compte(), quota) )
|
||||
txts.append( '%s (%s)\n%s' % (c.Nom(), c.compte(), quota) )
|
||||
|
||||
print '\n- - - - - - = = = = = = # # # # # # # # = = = = = = - - - - - -\n'.join(txts).encode('iso-8859-1')
|
||||
|
|
|
@ -13,7 +13,7 @@ txts = []
|
|||
|
||||
for a in adherents :
|
||||
if a.solde() == 0 :
|
||||
continue
|
||||
continue
|
||||
|
||||
# texte pour l'adhérent
|
||||
txt = u''
|
||||
|
|
|
@ -25,7 +25,7 @@ class interroge_switch (threading.Thread) :
|
|||
sw = hpswitch(self.switch)
|
||||
prise = sw.where_is_mac(mac)
|
||||
if prise != None :
|
||||
print "%-10s => prise %-2s : %s" % (self.switch.encode('iso-8859-15').replace('.adm.crans.org',''), str(prise), sw.nom(None, prise))
|
||||
print "%-10s => prise %-2s : %s" % (self.switch.encode('iso-8859-15').replace('.adm.crans.org',''), str(prise), sw.nom(None, prise))
|
||||
|
||||
# on onterroge trois fois car il donne pas toujours les clients
|
||||
for switch in ['backbone'] + all_switchs():
|
||||
|
|
|
@ -29,10 +29,10 @@ mac_done=[]
|
|||
def done (mac) :
|
||||
global mac_done
|
||||
if mac in mac_done :
|
||||
return True
|
||||
return True
|
||||
else :
|
||||
mac_done.append(mac)
|
||||
return False
|
||||
mac_done.append(mac)
|
||||
return False
|
||||
|
||||
# liste des résultats
|
||||
results = []
|
||||
|
@ -40,40 +40,40 @@ results = []
|
|||
# classe d'interrogation des bornes
|
||||
class interroge_borne (threading.Thread) :
|
||||
def __init__ (self, db, borne, mac = None) :
|
||||
threading.Thread.__init__(self)
|
||||
self.borne = borne
|
||||
self.mac = mac
|
||||
self.db = db
|
||||
self.start()
|
||||
threading.Thread.__init__(self)
|
||||
self.borne = borne
|
||||
self.mac = mac
|
||||
self.db = db
|
||||
self.start()
|
||||
|
||||
def aff_client (self, mac, rssi) :
|
||||
if done(mac) :
|
||||
return
|
||||
|
||||
res = db.search("mac=%s" % mac)['machine']
|
||||
if not res:
|
||||
client_nom = '????'
|
||||
coul_rssi = 'rouge'
|
||||
rssi = 0
|
||||
else:
|
||||
# On va choisir la bonne couleur pour le RSSI
|
||||
if rssi > -88:
|
||||
coul_rssi = 'vert'
|
||||
elif rssi > -93:
|
||||
coul_rssi = 'jaune'
|
||||
else:
|
||||
coul_rssi = 'rouge'
|
||||
global results
|
||||
results.append('%-10s %-30s (%-15s, RSSI: %s)' % (self.borne.nom().split('.')[0], res[0].proprietaire().Nom(), res[0].nom().split('.')[0],coul("%d" % rssi, coul_rssi)))
|
||||
if done(mac) :
|
||||
return
|
||||
|
||||
res = db.search("mac=%s" % mac)['machine']
|
||||
if not res:
|
||||
client_nom = '????'
|
||||
coul_rssi = 'rouge'
|
||||
rssi = 0
|
||||
else:
|
||||
# On va choisir la bonne couleur pour le RSSI
|
||||
if rssi > -88:
|
||||
coul_rssi = 'vert'
|
||||
elif rssi > -93:
|
||||
coul_rssi = 'jaune'
|
||||
else:
|
||||
coul_rssi = 'rouge'
|
||||
global results
|
||||
results.append('%-10s %-30s (%-15s, RSSI: %s)' % (self.borne.nom().split('.')[0], res[0].proprietaire().Nom(), res[0].nom().split('.')[0],coul("%d" % rssi, coul_rssi)))
|
||||
|
||||
def run (self) :
|
||||
nom = self.borne.nom()
|
||||
if not borne_etat(nom) :
|
||||
return
|
||||
clients = borne_clients_canal(nom)['mac-rssi']
|
||||
for (mac, rssi) in clients :
|
||||
if not self.mac.upper() or self.mac == mac.upper() :
|
||||
self.aff_client(mac,rssi)
|
||||
nom = self.borne.nom()
|
||||
if not borne_etat(nom) :
|
||||
return
|
||||
clients = borne_clients_canal(nom)['mac-rssi']
|
||||
for (mac, rssi) in clients :
|
||||
if not self.mac.upper() or self.mac == mac.upper() :
|
||||
self.aff_client(mac,rssi)
|
||||
|
||||
# on onterroge trois fois car il donne pas toujours les clients
|
||||
for i in range(0,3) :
|
||||
|
@ -81,7 +81,7 @@ for i in range(0,3) :
|
|||
resultat = {}
|
||||
bornes = db.search('canal=*')['machine']
|
||||
for borne in bornes :
|
||||
interroge_borne(db, borne, mac)
|
||||
interroge_borne(db, borne, mac)
|
||||
|
||||
# on attend la fin de threads
|
||||
while len(threading.enumerate()) > 1 :
|
||||
|
|
|
@ -251,21 +251,21 @@ def list_bornes(bornes) :
|
|||
# Données
|
||||
try :
|
||||
l = b.info()[0]
|
||||
if len(l) > 11 :
|
||||
l = l[0:11]
|
||||
if len(l) > 11 :
|
||||
l = l[0:11]
|
||||
except :
|
||||
l = u'????'
|
||||
|
||||
if borne_etat(b.nom()):
|
||||
if borne_etat(b.nom()):
|
||||
etat = ok
|
||||
else:
|
||||
etat = nok
|
||||
|
||||
if '-' in b.puissance() :
|
||||
puiss = coul(b.puissance(),'rouge')
|
||||
else :
|
||||
puiss = b.puissance()
|
||||
|
||||
|
||||
if '-' in b.puissance() :
|
||||
puiss = coul(b.puissance(),'rouge')
|
||||
else :
|
||||
puiss = b.puissance()
|
||||
|
||||
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)
|
||||
|
@ -752,8 +752,8 @@ def prise_etat(chbre) :
|
|||
# Switch non manageable ou down
|
||||
f += u', erreur de communication avec le switch'
|
||||
except :
|
||||
f = u'info prise non dispo : erreur prog'
|
||||
|
||||
f = u'info prise non dispo : erreur prog'
|
||||
|
||||
return f
|
||||
|
||||
##############################################################################
|
||||
|
|
Loading…
Add table
Add a link
Reference in a new issue