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
|
@ -60,37 +60,37 @@ for adresse in adresses :
|
|||
os.system("barcode -n -E -b %s%s -o %s" % (adresse,time.strftime("%Y%m%d-%H%M",time.localtime()),barcode))
|
||||
data = db.search("mail=%s" % adresse)
|
||||
try :
|
||||
prenom = data['adherent'][0].prenom().encode('iso8859-15')
|
||||
nom = data['adherent'][0].nom().encode('iso8859-15')
|
||||
chbre = data['adherent'][0].chbre()
|
||||
prenom = data['adherent'][0].prenom().encode('iso8859-15')
|
||||
nom = data['adherent'][0].nom().encode('iso8859-15')
|
||||
chbre = data['adherent'][0].chbre()
|
||||
except :
|
||||
sys.exit("Erreur : l'adresse < %s > n'a pas été trouvée dans la base" % adresse)
|
||||
|
||||
sys.exit("Erreur : l'adresse < %s > n'a pas été trouvée dans la base" % adresse)
|
||||
|
||||
chbres.append(chbre)
|
||||
date = time.strftime("%A %d %B %Y",time.localtime(time.time()+15*24*3600))
|
||||
|
||||
if adresse == adresses[0] :
|
||||
file.write("\\newcommand{\prenom}{%s}\n" % prenom)
|
||||
file.write("\\newcommand{\\nom}{%s}\n" % nom)
|
||||
file.write("\\newcommand{\chambre}{%s}\n" % chbre)
|
||||
file.write("\\newcommand{\email}{\url{%s}}\n" % adresse)
|
||||
file.write("\\newcommand{\deconnexion}{%s}\n" % date)
|
||||
file.write("\\newcommand{\prenom}{%s}\n" % prenom)
|
||||
file.write("\\newcommand{\\nom}{%s}\n" % nom)
|
||||
file.write("\\newcommand{\chambre}{%s}\n" % chbre)
|
||||
file.write("\\newcommand{\email}{\url{%s}}\n" % adresse)
|
||||
file.write("\\newcommand{\deconnexion}{%s}\n" % date)
|
||||
|
||||
else :
|
||||
file.write("\\renewcommand{\prenom}{%s}\n" % prenom)
|
||||
file.write("\\renewcommand{\\nom}{%s}\n" % nom)
|
||||
file.write("\\renewcommand{\chambre}{%s}\n" % chbre)
|
||||
file.write("\\renewcommand{\email}{\url{%s}}\n" % adresse)
|
||||
file.write("\\renewcommand{\deconnexion}{%s}\n" % date)
|
||||
file.write("\\renewcommand{\prenom}{%s}\n" % prenom)
|
||||
file.write("\\renewcommand{\\nom}{%s}\n" % nom)
|
||||
file.write("\\renewcommand{\chambre}{%s}\n" % chbre)
|
||||
file.write("\\renewcommand{\email}{\url{%s}}\n" % adresse)
|
||||
file.write("\\renewcommand{\deconnexion}{%s}\n" % date)
|
||||
|
||||
tex_src = open(texsrc, 'r')
|
||||
file.write(tex_src.read())
|
||||
tex_src.close()
|
||||
|
||||
if adresse != adresses[len(adresses)-1] :
|
||||
file.write('\\newpage')
|
||||
file.write('\\newpage')
|
||||
else :
|
||||
file.write('\end{document}')
|
||||
file.write('\end{document}')
|
||||
|
||||
file.close()
|
||||
#os.system("latex %s" % mailtex)
|
||||
|
@ -107,7 +107,7 @@ from email.MIMEBase import MIMEBase
|
|||
from email.MIMEText import MIMEText
|
||||
from email.MIMEMultipart import MIMEMultipart
|
||||
from email.Encoders import encode_base64
|
||||
|
||||
|
||||
msg = MIMEMultipart()
|
||||
msg['Subject'] = "Fiche(s) d'avertissement de mail invalide - %s" % time.strftime("%d/%m/%Y",time.localtime(time.time()))
|
||||
msg['From'] = "%s <%s>" % (cableur.Nom(), cableur.mail())
|
||||
|
@ -133,16 +133,16 @@ while (1 == 1):
|
|||
print " [Envoyer, Abandonner]"
|
||||
r = sys.stdin.readline().strip()
|
||||
if (r == "e" or r == "E"):
|
||||
# Send the email via our own SMTP server.
|
||||
s = smtplib.SMTP()
|
||||
s.connect()
|
||||
s.sendmail(msg['From'], (msg['To'],msg['Cc']), msg.as_string())
|
||||
s.close()
|
||||
print "Mail envoyé !"
|
||||
break
|
||||
# Send the email via our own SMTP server.
|
||||
s = smtplib.SMTP()
|
||||
s.connect()
|
||||
s.sendmail(msg['From'], (msg['To'],msg['Cc']), msg.as_string())
|
||||
s.close()
|
||||
print "Mail envoyé !"
|
||||
break
|
||||
if (r == "a" or r == "A"):
|
||||
print "Abandon"
|
||||
os.system("rm -f %s" % pdf)
|
||||
break
|
||||
print "Abandon"
|
||||
os.system("rm -f %s" % pdf)
|
||||
break
|
||||
|
||||
os.system("rm -f %s %s" % (mailtex.replace(".tex",".*"),barcode))
|
||||
|
|
|
@ -373,21 +373,21 @@ def bilan(DB, dbNames, duree, cur_time, disp_all = 0) :
|
|||
print printCounters(0, 1) + " | HOST"
|
||||
print "="*77
|
||||
for l in liste[0:top10_length] :
|
||||
# Test si le DNS de la machine existe (donc si la machine est inscrite au crans)
|
||||
try:
|
||||
host = socket.gethostbyaddr( l[-1] ) [0]
|
||||
bad = 0
|
||||
except socket.error :
|
||||
host = l[-1]
|
||||
bad = 1
|
||||
|
||||
if not resolve_names :
|
||||
# On veut l'IP
|
||||
host = l[-1]
|
||||
|
||||
if bad :
|
||||
host = "NoDNS_" + host
|
||||
|
||||
# Test si le DNS de la machine existe (donc si la machine est inscrite au crans)
|
||||
try:
|
||||
host = socket.gethostbyaddr( l[-1] ) [0]
|
||||
bad = 0
|
||||
except socket.error :
|
||||
host = l[-1]
|
||||
bad = 1
|
||||
|
||||
if not resolve_names :
|
||||
# On veut l'IP
|
||||
host = l[-1]
|
||||
|
||||
if bad :
|
||||
host = "NoDNS_" + host
|
||||
|
||||
print printCounters(l)+ (" |%s" % host)
|
||||
|
||||
|
||||
|
@ -491,14 +491,14 @@ if os.path.isfile(lock_name) :
|
|||
msg=string.strip(string.join(msg[1:], '') )
|
||||
q = os.system("ps -o pid,tty,user,etime,command " +pid)
|
||||
if q==256:
|
||||
print "PID lock no trouvé => delock"
|
||||
try :
|
||||
os.remove(lock_name)
|
||||
except :
|
||||
None
|
||||
print "PID lock no trouvé => delock"
|
||||
try :
|
||||
os.remove(lock_name)
|
||||
except :
|
||||
None
|
||||
else :
|
||||
print "Script lockant en activité, sortie"
|
||||
sys.exit(255)
|
||||
print "Script lockant en activité, sortie"
|
||||
sys.exit(255)
|
||||
|
||||
#Locking
|
||||
lock_fd=open(lock_name, "w")
|
||||
|
@ -529,7 +529,7 @@ for [key, val] in optlist :
|
|||
pickleName=val
|
||||
if key == '-s' :
|
||||
store_all = 1
|
||||
if key == '-n' :
|
||||
if key == '-n' :
|
||||
resolve_names = 0
|
||||
if key == '-T' :
|
||||
if duree == 0 :
|
||||
|
@ -538,7 +538,7 @@ for [key, val] in optlist :
|
|||
sduree = int( float(val) * 3600 * 24 )
|
||||
if key == '-c' :
|
||||
sort_column = int(val) -1
|
||||
|
||||
|
||||
if duree == 0:
|
||||
duree = 24*3600
|
||||
if not logFNames :
|
||||
|
|
|
@ -23,75 +23,75 @@ import nntplib,string,os,StringIO
|
|||
def LFsplit(s):
|
||||
res=""
|
||||
while len(s)>80 :
|
||||
pos=string.find(s,' ',65,80)
|
||||
if pos < 0 :
|
||||
res=res+s[0:75]+'\n'
|
||||
s=s[75:len(s)+1]
|
||||
else :
|
||||
res=res+s[0:pos]+'\n'
|
||||
s=s[pos+1:len(s)+1]
|
||||
pos=string.find(s,' ',65,80)
|
||||
if pos < 0 :
|
||||
res=res+s[0:75]+'\n'
|
||||
s=s[75:len(s)+1]
|
||||
else :
|
||||
res=res+s[0:pos]+'\n'
|
||||
s=s[pos+1:len(s)+1]
|
||||
if len(s)>0:
|
||||
res=res+s
|
||||
res=res+s
|
||||
return res
|
||||
|
||||
for uid in os.listdir('/var/local/cvsweb/checkins/'):
|
||||
try:
|
||||
so = []
|
||||
so = []
|
||||
fi = open('/var/local/cvsweb/checkins/'+uid,'r')
|
||||
|
||||
so.append("From: CVS admin <root@crans.org>\n" + \
|
||||
("Subject: CVS Commit par %s\n" % uid)+ \
|
||||
"Organization: Crans Internet Site\n" + \
|
||||
"Newsgroups: crans.cvs-checkins\n" + \
|
||||
"Reply-To: Nounous <nounou@crans.org>\n" + \
|
||||
"Followup-To: crans.informatique\n" )
|
||||
so.append("From: CVS admin <root@crans.org>\n" + \
|
||||
("Subject: CVS Commit par %s\n" % uid)+ \
|
||||
"Organization: Crans Internet Site\n" + \
|
||||
"Newsgroups: crans.cvs-checkins\n" + \
|
||||
"Reply-To: Nounous <nounou@crans.org>\n" + \
|
||||
"Followup-To: crans.informatique\n" )
|
||||
|
||||
so.append("MIME-Version: 1.0\n" + \
|
||||
"Content-Type: text/plain\n")
|
||||
so.append("\n")
|
||||
envoie = 0
|
||||
links_base="http://www.crans.org/cgi-bin/cvsweb"
|
||||
while 1:
|
||||
s = fi.readline()
|
||||
if not s: break
|
||||
envoie = 1
|
||||
links=['Liens vers les diffs sur cvsweb :\n']
|
||||
diffok = 0
|
||||
|
||||
# On essaye de créer les liens vers cvsweb automatiquement.
|
||||
try:
|
||||
if s[0:3]=="web":
|
||||
link=string.split(s)
|
||||
for file in link[1:]:
|
||||
file=string.split(file,",")
|
||||
if not string.split(file[0],".")[-1] in ['jpg','jpeg','gif','png']:
|
||||
links.append("%s/%s/%s.diff?r1=%s&r2=%s\n" % (links_base,link[0],file[0],file[1],file[2]))
|
||||
diffok = 1
|
||||
# S'il y a au moins un diff affichable, on donne le lien.
|
||||
if diffok:
|
||||
links.append('\n')
|
||||
s=string.join(links,'')
|
||||
else:
|
||||
s=LFsplit(s)
|
||||
so.append(s)
|
||||
except:
|
||||
so.append(s)
|
||||
# Avec une signature c'est plus propre.
|
||||
so.append("\n" + \
|
||||
"-- \n" + \
|
||||
"Notification automatique des CVS commits sur le site du CR@NS.\n"+ \
|
||||
"Voir http://www.crans.org/cgi-bin/cvsweb/web/ pour accéder aux archives CVS complètes.")
|
||||
so.append("MIME-Version: 1.0\n" + \
|
||||
"Content-Type: text/plain\n")
|
||||
so.append("\n")
|
||||
envoie = 0
|
||||
links_base="http://www.crans.org/cgi-bin/cvsweb"
|
||||
while 1:
|
||||
s = fi.readline()
|
||||
if not s: break
|
||||
envoie = 1
|
||||
links=['Liens vers les diffs sur cvsweb :\n']
|
||||
diffok = 0
|
||||
|
||||
# On essaye de créer les liens vers cvsweb automatiquement.
|
||||
try:
|
||||
if s[0:3]=="web":
|
||||
link=string.split(s)
|
||||
for file in link[1:]:
|
||||
file=string.split(file,",")
|
||||
if not string.split(file[0],".")[-1] in ['jpg','jpeg','gif','png']:
|
||||
links.append("%s/%s/%s.diff?r1=%s&r2=%s\n" % (links_base,link[0],file[0],file[1],file[2]))
|
||||
diffok = 1
|
||||
# S'il y a au moins un diff affichable, on donne le lien.
|
||||
if diffok:
|
||||
links.append('\n')
|
||||
s=string.join(links,'')
|
||||
else:
|
||||
s=LFsplit(s)
|
||||
so.append(s)
|
||||
except:
|
||||
so.append(s)
|
||||
# Avec une signature c'est plus propre.
|
||||
so.append("\n" + \
|
||||
"-- \n" + \
|
||||
"Notification automatique des CVS commits sur le site du CR@NS.\n"+ \
|
||||
"Voir http://www.crans.org/cgi-bin/cvsweb/web/ pour accéder aux archives CVS complètes.")
|
||||
|
||||
|
||||
# maintenant, on envoie :
|
||||
# maintenant, on envoie :
|
||||
|
||||
if envoie:
|
||||
sso = string.join(so,'')
|
||||
fso = StringIO.StringIO(sso)
|
||||
nntplib.NNTP('news.crans.org').post(fso)
|
||||
#print sso
|
||||
fi.close()
|
||||
os.unlink('/var/local/cvsweb/checkins/'+uid)
|
||||
if envoie:
|
||||
sso = string.join(so,'')
|
||||
fso = StringIO.StringIO(sso)
|
||||
nntplib.NNTP('news.crans.org').post(fso)
|
||||
#print sso
|
||||
fi.close()
|
||||
os.unlink('/var/local/cvsweb/checkins/'+uid)
|
||||
except:
|
||||
raise
|
||||
raise
|
||||
|
||||
|
|
|
@ -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
|
||||
|
||||
##############################################################################
|
||||
|
|
|
@ -23,14 +23,14 @@ def GrabInfos(aDB):
|
|||
maison = os.listdir('/home')
|
||||
|
||||
for login in maison:
|
||||
compte = CompteRec.CCompte(login)
|
||||
compte = CompteRec.CCompte(login)
|
||||
|
||||
if compte: # il y a un .info, un .plan ou un .www :
|
||||
aDB.Put(login,compte)
|
||||
|
||||
i = i - 1
|
||||
if not i: break # en debogage, on ne mouline pas tous les comptes !
|
||||
|
||||
if compte: # il y a un .info, un .plan ou un .www :
|
||||
aDB.Put(login,compte)
|
||||
|
||||
i = i - 1
|
||||
if not i: break # en debogage, on ne mouline pas tous les comptes !
|
||||
|
||||
|
||||
|
||||
|
||||
|
|
|
@ -37,239 +37,239 @@ class CCompte:
|
|||
Plan = None
|
||||
URL = None # nom de fichier relatif de la page Web
|
||||
# en général .www/index.html
|
||||
# ou alors URL
|
||||
# ou alors URL
|
||||
|
||||
|
||||
def __init__(self,login = ""):
|
||||
""" Initialisation.
|
||||
""" Initialisation.
|
||||
|
||||
Cette méthode analyse le contenu du compte (login) et remplit
|
||||
self en conséquence. Il est renvoyé 0 dans self.Actif si le compte
|
||||
ne contient ni .info ni .plan. """
|
||||
Cette méthode analyse le contenu du compte (login) et remplit
|
||||
self en conséquence. Il est renvoyé 0 dans self.Actif si le compte
|
||||
ne contient ni .info ni .plan. """
|
||||
|
||||
self.Actif = 0
|
||||
self.Compte = strip(login)
|
||||
|
||||
if not login : return # en principe, on est en de-shelvage ...
|
||||
self.Actif = 0
|
||||
self.Compte = strip(login)
|
||||
|
||||
if not login : return # en principe, on est en de-shelvage ...
|
||||
|
||||
Path = "/home/" + login + "/"
|
||||
|
||||
try: # lecture du .info
|
||||
Path = "/home/" + login + "/"
|
||||
|
||||
try: # lecture du .info
|
||||
f_info = open(Path + ".info","r")
|
||||
info = f_info.readlines()
|
||||
info = f_info.readlines()
|
||||
|
||||
self.ParseInfo(info,login)
|
||||
except:
|
||||
self.ParseInfo(info,login)
|
||||
except:
|
||||
# faut probablement gueuler (sauf si le fichier est
|
||||
# légitimement absent)
|
||||
pass
|
||||
pass
|
||||
|
||||
if not (self.URL):
|
||||
url = ""
|
||||
# rien mis ? on essaye index.html et index.htm dans .www/ :
|
||||
if os.path.isfile("/home/"+login+"/www/index.html"):
|
||||
url = "/~"+login+"/index.html"
|
||||
elif os.path.isfile("/home/"+login+"/www/index.htm"):
|
||||
url = "/~"+login+"/index.htm"
|
||||
elif os.path.isfile("/home/"+login+"/www/default.htm"):
|
||||
url = "/~"+login+"/default.htm"
|
||||
self.URL = url
|
||||
if not (self.URL):
|
||||
url = ""
|
||||
# rien mis ? on essaye index.html et index.htm dans .www/ :
|
||||
if os.path.isfile("/home/"+login+"/www/index.html"):
|
||||
url = "/~"+login+"/index.html"
|
||||
elif os.path.isfile("/home/"+login+"/www/index.htm"):
|
||||
url = "/~"+login+"/index.htm"
|
||||
elif os.path.isfile("/home/"+login+"/www/default.htm"):
|
||||
url = "/~"+login+"/default.htm"
|
||||
self.URL = url
|
||||
|
||||
try: # lecture du .plan
|
||||
f_plan = open(Path + ".plan","r")
|
||||
self.Plan = f_plan.readlines()[:30]
|
||||
self.Active = 1
|
||||
except:
|
||||
pass
|
||||
try: # lecture du .plan
|
||||
f_plan = open(Path + ".plan","r")
|
||||
self.Plan = f_plan.readlines()[:30]
|
||||
self.Active = 1
|
||||
except:
|
||||
pass
|
||||
|
||||
try: # lecture du .project
|
||||
f_project = open(Path + ".project","r")
|
||||
self.Projet = f_project.readlines()[:30]
|
||||
self.Active = 1
|
||||
except:
|
||||
pass
|
||||
try: # lecture du .project
|
||||
f_project = open(Path + ".project","r")
|
||||
self.Projet = f_project.readlines()[:30]
|
||||
self.Active = 1
|
||||
except:
|
||||
pass
|
||||
|
||||
|
||||
# à ce stade, l'objet est prêt à l'emploi
|
||||
# à ce stade, l'objet est prêt à l'emploi
|
||||
|
||||
def ParseInfo (self,info , login):
|
||||
""" Analyse un fichier .info.
|
||||
""" Analyse un fichier .info.
|
||||
|
||||
cette routine analyse un fichier .info et transfère ses
|
||||
informations si elles sont cohérentes.
|
||||
Les erreurs sont envoyees a self.DisplayError
|
||||
cette routine analyse un fichier .info et transfère ses
|
||||
informations si elles sont cohérentes.
|
||||
Les erreurs sont envoyees a self.DisplayError
|
||||
"""
|
||||
|
||||
nom = None
|
||||
compte = None
|
||||
pseudo = None
|
||||
email = login + "@crans.org"
|
||||
logo = None
|
||||
photo = None
|
||||
devise = None
|
||||
projet = None
|
||||
section = None
|
||||
adresse = None
|
||||
telephone = None
|
||||
url = None
|
||||
version = 1
|
||||
|
||||
for ligne in info :
|
||||
if lstrip(ligne)[:1] == '#': continue # commentaire
|
||||
|
||||
nom = None
|
||||
compte = None
|
||||
pseudo = None
|
||||
email = login + "@crans.org"
|
||||
logo = None
|
||||
photo = None
|
||||
devise = None
|
||||
projet = None
|
||||
section = None
|
||||
adresse = None
|
||||
telephone = None
|
||||
url = None
|
||||
version = 1
|
||||
|
||||
for ligne in info :
|
||||
if lstrip(ligne)[:1] == '#': continue # commentaire
|
||||
|
||||
|
||||
ligne = rstrip(ligne) # vire le \012 final
|
||||
spl_ligne = split(ligne,":")
|
||||
champ = lower(strip(spl_ligne[0]))
|
||||
valeur = strip(join(spl_ligne[1:],":"))
|
||||
|
||||
|
||||
try:
|
||||
if champ=="compte": compte = strip(valeur)
|
||||
elif champ=="nom": nom = valeur
|
||||
elif champ=="pseudo": pseudo = valeur
|
||||
elif champ=="email": email = valeur
|
||||
elif champ=="logo": logo = valeur
|
||||
elif champ=="photo": photo = valeur
|
||||
elif champ=="devise": devise = valeur
|
||||
elif champ=="section": section = valeur
|
||||
elif champ=="adresse": adresse = valeur
|
||||
elif champ=="telephone": telephone = valeur
|
||||
elif champ=="url" : url = valeur
|
||||
elif champ=="version" : version = atoi(strip(valeur))
|
||||
|
||||
ligne = rstrip(ligne) # vire le \012 final
|
||||
spl_ligne = split(ligne,":")
|
||||
champ = lower(strip(spl_ligne[0]))
|
||||
valeur = strip(join(spl_ligne[1:],":"))
|
||||
|
||||
|
||||
try:
|
||||
if champ=="compte": compte = strip(valeur)
|
||||
elif champ=="nom": nom = valeur
|
||||
elif champ=="pseudo": pseudo = valeur
|
||||
elif champ=="email": email = valeur
|
||||
elif champ=="logo": logo = valeur
|
||||
elif champ=="photo": photo = valeur
|
||||
elif champ=="devise": devise = valeur
|
||||
elif champ=="section": section = valeur
|
||||
elif champ=="adresse": adresse = valeur
|
||||
elif champ=="telephone": telephone = valeur
|
||||
elif champ=="url" : url = valeur
|
||||
elif champ=="version" : version = atoi(strip(valeur))
|
||||
except:
|
||||
erreur = [" une erreur est survenue sur le champ "+champ+
|
||||
". Il y a toutes les chances que tu n'aie pas "
|
||||
" respecté la syntaxe de .info. \012",
|
||||
" selon toutes probabilités, une autre erreur "
|
||||
"va se déclencher... on laisse courir.\012",
|
||||
" (non critique)","\012"]
|
||||
self.DisplayError(login,erreur)
|
||||
pass
|
||||
erreur = [" une erreur est survenue sur le champ "+champ+
|
||||
". Il y a toutes les chances que tu n'aie pas "
|
||||
" respecté la syntaxe de .info. \012",
|
||||
" selon toutes probabilités, une autre erreur "
|
||||
"va se déclencher... on laisse courir.\012",
|
||||
" (non critique)","\012"]
|
||||
self.DisplayError(login,erreur)
|
||||
pass
|
||||
|
||||
|
||||
if (url) and (url[:7] != "http://") and (url[:1] != "/"):
|
||||
# c'est un nom de fichier.... on verifie qu'il commence par .www
|
||||
if url[:5] != ".www/" :
|
||||
erreur = ["Le champ url doit etre un URL ou un nom de fichier"
|
||||
"commencant par .www/ \012","(non critique) \012",
|
||||
"\012"]
|
||||
self.DisplayError(login,erreur)
|
||||
else: # c'est bon.. on en fait un url relatif au site...
|
||||
url = "/~"+login+url[:4]
|
||||
pass
|
||||
|
||||
|
||||
if strip(compte) != strip(login):
|
||||
erreur = ["Le champ 'Compte' et le login ne correspondent pas !",
|
||||
" (fatal) ",""]
|
||||
self.DisplayError(login,erreur)
|
||||
raise SyntaxError
|
||||
|
||||
if (url) and (url[:7] != "http://") and (url[:1] != "/"):
|
||||
# c'est un nom de fichier.... on verifie qu'il commence par .www
|
||||
if url[:5] != ".www/" :
|
||||
erreur = ["Le champ url doit etre un URL ou un nom de fichier"
|
||||
"commencant par .www/ \012","(non critique) \012",
|
||||
"\012"]
|
||||
self.DisplayError(login,erreur)
|
||||
else: # c'est bon.. on en fait un url relatif au site...
|
||||
url = "/~"+login+url[:4]
|
||||
pass
|
||||
|
||||
|
||||
if strip(compte) != strip(login):
|
||||
erreur = ["Le champ 'Compte' et le login ne correspondent pas !",
|
||||
" (fatal) ",""]
|
||||
self.DisplayError(login,erreur)
|
||||
raise SyntaxError
|
||||
|
||||
if version < 1:
|
||||
erreur = ["La version du fichier (champ Version) est inférieure ",
|
||||
"a 1 ",
|
||||
"(non critique)",""]
|
||||
self.DisplayError(login,erreur)
|
||||
#raise SyntaxError
|
||||
if version < 1:
|
||||
erreur = ["La version du fichier (champ Version) est inférieure ",
|
||||
"a 1 ",
|
||||
"(non critique)",""]
|
||||
self.DisplayError(login,erreur)
|
||||
#raise SyntaxError
|
||||
|
||||
if version > 1:
|
||||
erreur = ["Ce mkinfos est probablement obsolète ou une erreur "
|
||||
" existe sur le champ Version. ",
|
||||
" (non critique)",""]
|
||||
self.DisplayError(login,erreur)
|
||||
if version > 1:
|
||||
erreur = ["Ce mkinfos est probablement obsolète ou une erreur "
|
||||
" existe sur le champ Version. ",
|
||||
" (non critique)",""]
|
||||
self.DisplayError(login,erreur)
|
||||
|
||||
|
||||
self.Compte = compte
|
||||
self.Actif = 1
|
||||
self.Pseudo = pseudo
|
||||
self.Email = email
|
||||
self.Logo = logo
|
||||
self.Photo = photo
|
||||
self.Devise = devise
|
||||
self.Section = section
|
||||
self.Projet = projet
|
||||
self.Adresse = adresse
|
||||
self.Telephone = telephone
|
||||
self.Nom = nom
|
||||
self.URL = url
|
||||
self.Compte = compte
|
||||
self.Actif = 1
|
||||
self.Pseudo = pseudo
|
||||
self.Email = email
|
||||
self.Logo = logo
|
||||
self.Photo = photo
|
||||
self.Devise = devise
|
||||
self.Section = section
|
||||
self.Projet = projet
|
||||
self.Adresse = adresse
|
||||
self.Telephone = telephone
|
||||
self.Nom = nom
|
||||
self.URL = url
|
||||
|
||||
if logo:
|
||||
try:
|
||||
self.FindLogo()
|
||||
except:
|
||||
erreur = ["Erreur a la récupération du logo",
|
||||
"(non critique)",
|
||||
""]
|
||||
self.DisplayError(login,erreur)
|
||||
pass
|
||||
|
||||
if logo:
|
||||
try:
|
||||
self.FindLogo()
|
||||
except:
|
||||
erreur = ["Erreur a la récupération du logo",
|
||||
"(non critique)",
|
||||
""]
|
||||
self.DisplayError(login,erreur)
|
||||
pass
|
||||
|
||||
|
||||
def DisplayError(self, login, errorlines):
|
||||
""" Affiche une erreur de compilation du .info de 'login'.
|
||||
|
||||
errorlines contient un tableau de chaines de caracteres.
|
||||
En general, on changera cette routine (par exemple pour
|
||||
envoyer un mail a 'login'
|
||||
"""
|
||||
""" Affiche une erreur de compilation du .info de 'login'.
|
||||
|
||||
errorlines contient un tableau de chaines de caracteres.
|
||||
En general, on changera cette routine (par exemple pour
|
||||
envoyer un mail a 'login'
|
||||
"""
|
||||
|
||||
print "Erreur dans .info , compte =",login
|
||||
for i in errorlines:
|
||||
print i
|
||||
print ""
|
||||
print "Erreur dans .info , compte =",login
|
||||
for i in errorlines:
|
||||
print i
|
||||
print ""
|
||||
|
||||
|
||||
|
||||
def FindLogo(self):
|
||||
""" Récupere le logo.
|
||||
|
||||
Cette routine récupere le logo contenu dans le champ Logo du compte
|
||||
'account' et le stocke dans $InfoDir/$login.logo.extension
|
||||
Le champ Logo du compte est alors mis à jour.
|
||||
"""
|
||||
|
||||
|
||||
import urllib # urllib.urlopen()
|
||||
import posixpath # posixpath.splitext()
|
||||
""" Récupere le logo.
|
||||
|
||||
Cette routine récupere le logo contenu dans le champ Logo du compte
|
||||
'account' et le stocke dans $InfoDir/$login.logo.extension
|
||||
Le champ Logo du compte est alors mis à jour.
|
||||
"""
|
||||
|
||||
|
||||
import urllib # urllib.urlopen()
|
||||
import posixpath # posixpath.splitext()
|
||||
|
||||
# Où sont stockés les logos
|
||||
InfoDir = "/home/httpd/html/info-2/"
|
||||
InfoPath = "/info-2/"
|
||||
|
||||
if not self.Logo:
|
||||
return # rien a faire !
|
||||
logopath = self.Logo
|
||||
self.Logo = ""
|
||||
olddir = os.getcwd()
|
||||
# Où sont stockés les logos
|
||||
InfoDir = "/home/httpd/html/info-2/"
|
||||
InfoPath = "/info-2/"
|
||||
|
||||
if not self.Logo:
|
||||
return # rien a faire !
|
||||
logopath = self.Logo
|
||||
self.Logo = ""
|
||||
olddir = os.getcwd()
|
||||
|
||||
os.chdir("/home/"+self.Compte)
|
||||
try:
|
||||
rf = urllib.urlopen(logopath)
|
||||
|
||||
base,ext = posixpath.splitext(logopath)
|
||||
logoname = self.Compte + ".logo" + ext
|
||||
f = open(InfoDir + logoname,"w")
|
||||
os.chdir("/home/"+self.Compte)
|
||||
try:
|
||||
rf = urllib.urlopen(logopath)
|
||||
|
||||
base,ext = posixpath.splitext(logopath)
|
||||
logoname = self.Compte + ".logo" + ext
|
||||
f = open(InfoDir + logoname,"w")
|
||||
|
||||
data = rf.read(-1) # tout d'un coup !
|
||||
data = rf.read(-1) # tout d'un coup !
|
||||
|
||||
f.write(data) # hop !
|
||||
f.write(data) # hop !
|
||||
|
||||
# on ferme !
|
||||
f.close()
|
||||
rf = None
|
||||
# on ferme !
|
||||
f.close()
|
||||
rf = None
|
||||
|
||||
# bon on peut mettre a jour le compte maintenant !
|
||||
self.Logo = InfoPath + logoname
|
||||
finally:
|
||||
os.chdir(olddir)
|
||||
# bon on peut mettre a jour le compte maintenant !
|
||||
self.Logo = InfoPath + logoname
|
||||
finally:
|
||||
os.chdir(olddir)
|
||||
|
||||
|
||||
|
||||
|
||||
|
||||
|
||||
|
||||
# A ce stade : on a defini une classe "CCompte" capable d'analyser le .info
|
||||
# et le .plan, une fois donne un nom de login.
|
||||
|
||||
# test debug :
|
||||
|
||||
if 0:
|
||||
if 0:
|
||||
A = CCompte("chepelov")
|
||||
print A.__dict__
|
||||
|
|
|
@ -22,15 +22,15 @@ class CInfoDb:
|
|||
db = None
|
||||
|
||||
def __init__(self,filename,mode="rw"):
|
||||
self.db = shelve.open(filename,mode)
|
||||
|
||||
self.db = shelve.open(filename,mode)
|
||||
|
||||
def __del__(self):
|
||||
self.db.close()
|
||||
self.db.close()
|
||||
|
||||
def Put(self,name,obj):
|
||||
""" Ajoute un element."""
|
||||
self.db[name] = obj
|
||||
""" Ajoute un element."""
|
||||
self.db[name] = obj
|
||||
|
||||
def Get(self,name):
|
||||
""" recupere un element. """
|
||||
return self.db[name]
|
||||
""" recupere un element. """
|
||||
return self.db[name]
|
||||
|
|
|
@ -13,7 +13,7 @@ import sys
|
|||
import commands
|
||||
|
||||
#Excluded = ['snepa','lasauce','cineclub','innomine','hubris','gmpcad',
|
||||
# 'jdr','coope','asme','sono','rilem','krobot']
|
||||
# 'jdr','coope','asme','sono','rilem','krobot']
|
||||
Excluded = []
|
||||
|
||||
|
||||
|
@ -48,40 +48,40 @@ compteur = 4
|
|||
for key in keys:
|
||||
compte = DB.Get(key)
|
||||
#sys.stderr.write('%s\n'%key)
|
||||
|
||||
|
||||
try:
|
||||
if compte.URL and not (compte.Compte in Excluded):
|
||||
s = ' <td align="center" valign="center" width="25%">\n\
|
||||
if compte.URL and not (compte.Compte in Excluded):
|
||||
s = ' <td align="center" valign="center" width="25%">\n\
|
||||
<font style="font-size: x-small" face="Verdana, Tahoma, Arial, Helvetica, sans-serif" color="#000000" >\n'
|
||||
|
||||
if compte.Logo : l = compte.Logo
|
||||
else: l = "/images/crans-mini.jpg"
|
||||
|
||||
if compte.Logo : l = compte.Logo
|
||||
else: l = "/images/crans-mini.jpg"
|
||||
|
||||
url = compte.URL
|
||||
s = s + ' <a href="' + url + '"><img src="'+l+'" alt="*" border=0></a><br>'
|
||||
if compte.Nom: nom = compte.Nom
|
||||
else: nom = compte.Compte
|
||||
url = compte.URL
|
||||
s = s + ' <a href="' + url + '"><img src="'+l+'" alt="*" border=0></a><br>'
|
||||
if compte.Nom: nom = compte.Nom
|
||||
else: nom = compte.Compte
|
||||
|
||||
|
||||
s = s + '\n <b> <a href="' + url + '">' + nom + '</a></b><br>'
|
||||
|
||||
if compte.Pseudo:
|
||||
s = s + '\n «'+compte.Pseudo+'»<br>'
|
||||
|
||||
if compteur == 0:
|
||||
print " </tr>\n <tr>"
|
||||
s = s + '\n <b> <a href="' + url + '">' + nom + '</a></b><br>'
|
||||
|
||||
if compte.Pseudo:
|
||||
s = s + '\n «'+compte.Pseudo+'»<br>'
|
||||
|
||||
if compteur == 0:
|
||||
print " </tr>\n <tr>"
|
||||
|
||||
print s, # qu'il y ait ou non un pseudo !!!
|
||||
|
||||
if compte.Devise:
|
||||
s = '\n <font style="font-size: xx-small"><i>'+compte.Devise+'</i></font>'
|
||||
print s,
|
||||
print '\n </font>\n </td>'
|
||||
if compte.Devise:
|
||||
s = '\n <font style="font-size: xx-small"><i>'+compte.Devise+'</i></font>'
|
||||
print s,
|
||||
print '\n </font>\n </td>'
|
||||
|
||||
compteur = (compteur + 1)%4
|
||||
compteur = (compteur + 1)%4
|
||||
|
||||
except:
|
||||
pass
|
||||
pass
|
||||
|
||||
print " </tr>\n\
|
||||
</table>\n\
|
||||
|
|
|
@ -17,44 +17,44 @@ def chap_ok(password, challenge, clear_pass) :
|
|||
retourne False sinon
|
||||
"""
|
||||
try :
|
||||
challenge = binascii.a2b_hex(challenge.replace('0x',''))
|
||||
password = binascii.a2b_hex(password.replace('0x',''))
|
||||
challenge = binascii.a2b_hex(challenge.replace('0x',''))
|
||||
password = binascii.a2b_hex(password.replace('0x',''))
|
||||
if md5.new(password[0] + clear_pass + challenge).digest() == password[1:] :
|
||||
return True
|
||||
return True
|
||||
except :
|
||||
pass
|
||||
pass
|
||||
|
||||
return False
|
||||
|
||||
if __name__ == '__main__' :
|
||||
# Test chap (comme cela on est sur que c'est bien un switch qui demande)
|
||||
mac=os.getenv('USER_NAME','').replace('"','')
|
||||
|
||||
|
||||
if not chap_ok(os.getenv('CHAP_PASSWORD'), os.getenv('CHAP_CHALLENGE'), mac) :
|
||||
sys.stdout.write("Echec test CHAP")
|
||||
sys.exit(-1)
|
||||
sys.stdout.write("Echec test CHAP")
|
||||
sys.exit(-1)
|
||||
|
||||
# Mac dans la base LDAP
|
||||
m=crans_ldap().search('mac=%s'%mac)['machine']
|
||||
if len(m)!=1 :
|
||||
sys.stdout.write("Pb recherche mac (nb résultat !=1)")
|
||||
sys.exit(-1)
|
||||
sys.stdout.write("Pb recherche mac (nb résultat !=1)")
|
||||
sys.exit(-1)
|
||||
|
||||
# N'appartient pas au Crans (évite les spoof)
|
||||
proprio=m[0].proprietaire()
|
||||
# if proprio.__class__ == crans :
|
||||
# sys.stdout.write("Machine du crans")
|
||||
# sys.exit(-1)
|
||||
# sys.stdout.write("Machine du crans")
|
||||
# sys.exit(-1)
|
||||
|
||||
# Paiment ok ?
|
||||
paid=max(proprio.paiement()+[0])
|
||||
if dat[1]==9 :
|
||||
# En septembre les anciennes adhésion sont OK
|
||||
ann_scol -= 1
|
||||
# En septembre les anciennes adhésion sont OK
|
||||
ann_scol -= 1
|
||||
if ann_scol > paid :
|
||||
sys.stdout.write("Echec test LDAP")
|
||||
sys.exit(-1)
|
||||
|
||||
sys.stdout.write("Echec test LDAP")
|
||||
sys.exit(-1)
|
||||
|
||||
# C'est bon
|
||||
sys.stdout.write("Acces OK")
|
||||
sys.exit(0)
|
||||
|
|
|
@ -17,23 +17,23 @@ def identification ( password ) :
|
|||
#si le fichier existe le code est bon (evite les problemes par rapport au fait de
|
||||
# stocker les codes dans un fichier
|
||||
if password in os.listdir('/var/impression/codes'):
|
||||
if password in os.listdir('/var/impression/codes'):
|
||||
os.remove("/var/impression/codes/%s" %password)
|
||||
return 1
|
||||
if password in os.listdir('/var/impression/codes'):
|
||||
os.remove("/var/impression/codes/%s" %password)
|
||||
return 1
|
||||
else :
|
||||
return 0
|
||||
return 0
|
||||
|
||||
if __name__ == '__main__' :
|
||||
# on récupère le code dans les variables d'environement
|
||||
try :
|
||||
code = os.getenv('USER_PASSWORD','').replace('"','')
|
||||
code = os.getenv('USER_PASSWORD','').replace('"','')
|
||||
except :
|
||||
code = ''
|
||||
code = ''
|
||||
|
||||
# test de l'authentification
|
||||
if identification(code) :
|
||||
# c'est bon
|
||||
sys.exit(0)
|
||||
# c'est bon
|
||||
sys.exit(0)
|
||||
else :
|
||||
# c'est pas bon
|
||||
sys.exit(1)
|
||||
# c'est pas bon
|
||||
sys.exit(1)
|
||||
|
|
|
@ -1,14 +1,14 @@
|
|||
#! /usr/bin/env python
|
||||
# -*- coding: iso-8859-15 -*-
|
||||
|
||||
# $Id: secours.py,v 1.2 2005-08-27 11:56:50 pauget Exp $
|
||||
# $Id: secours.py,v 1.3 2005-10-18 08:38:22 bernat Exp $
|
||||
|
||||
""" Script de reconfigure des services en connexion de secours
|
||||
Arguments :
|
||||
test : teste la connexion et passe en secours si besoin
|
||||
normal : force la connexion normale
|
||||
secours : force la connexion de secours
|
||||
auto : permet la modification automatique de l'état
|
||||
test : teste la connexion et passe en secours si besoin
|
||||
normal : force la connexion normale
|
||||
secours : force la connexion de secours
|
||||
auto : permet la modification automatique de l'état
|
||||
Sans argument configure les services comme indiqué dans etat_maitre
|
||||
|
||||
Frédéric Pauget août 2005
|
||||
|
@ -27,7 +27,7 @@ if hostname == 'rouge' :
|
|||
cmds = [ '/etc/init.d/postfix restart' , '/etc/init.d/bind9 reload' ]
|
||||
elif hostname == 'sila' :
|
||||
fichiers = { '/etc/bind/named.conf.options' : '//' ,
|
||||
'/etc/squid/squid.conf' : '#' }
|
||||
'/etc/squid/squid.conf' : '#' }
|
||||
cmds = [ '/etc/init.d/squid reload' , '/etc/init.d/bind9 reload' ]
|
||||
elif hostname == 'bleu' :
|
||||
fichiers = { '/etc/postfix/main.cf' : '#' }
|
||||
|
@ -70,34 +70,34 @@ def edit(file,comment,etat) :
|
|||
new = ''
|
||||
reste = 0 # Nombre de lignes restant à traiter
|
||||
while line :
|
||||
l = line.rstrip()
|
||||
l = line.rstrip()
|
||||
mo = sre.match('^(.*)'+signal+'(|-.)$',l)
|
||||
if (mo and len(mo.group(1)) > 1) or reste:
|
||||
# Ligne pour secours
|
||||
if not sre.match('^' + comment,l) and etat == 'normal':
|
||||
# On est actuellement configuré en secours
|
||||
# Il faut passer en normal
|
||||
new += comment + line
|
||||
elif sre.match('^' + comment,l) and etat == 'secours' :
|
||||
# On est actuellement configuré en normal
|
||||
# Il faut passer en secours
|
||||
new += line.replace(comment,'',1)
|
||||
else :
|
||||
# Rien à faire, on est bien configuré
|
||||
new += line
|
||||
# Ligne pour secours
|
||||
if not sre.match('^' + comment,l) and etat == 'normal':
|
||||
# On est actuellement configuré en secours
|
||||
# Il faut passer en normal
|
||||
new += comment + line
|
||||
elif sre.match('^' + comment,l) and etat == 'secours' :
|
||||
# On est actuellement configuré en normal
|
||||
# Il faut passer en secours
|
||||
new += line.replace(comment,'',1)
|
||||
else :
|
||||
# Rien à faire, on est bien configuré
|
||||
new += line
|
||||
if reste :
|
||||
reste -= 1
|
||||
elif mo and len(mo.group(1)) == 0:
|
||||
# On a une ligne avec secours uniquement, c'est les n
|
||||
# prochaines lignes qui font foi
|
||||
try : reste = int(mo.group(2)[1:])
|
||||
except : reste = 1
|
||||
# prochaines lignes qui font foi
|
||||
try : reste = int(mo.group(2)[1:])
|
||||
except : reste = 1
|
||||
new += line
|
||||
else :
|
||||
# Ligne normale
|
||||
new += line
|
||||
else :
|
||||
# Ligne normale
|
||||
new += line
|
||||
|
||||
line = fd.readline()
|
||||
line = fd.readline()
|
||||
|
||||
fd.close()
|
||||
|
||||
|
@ -109,45 +109,45 @@ if __name__ == '__main__' :
|
|||
etat_maitre, mode = map(str.strip,open(path+'/etat_maitre').readlines())
|
||||
nouvel_etat = etat_maitre
|
||||
try:
|
||||
etat_actuel = open('%s/etat_%s' % (path,hostname)).readline().strip()
|
||||
etat_actuel = open('%s/etat_%s' % (path,hostname)).readline().strip()
|
||||
except :
|
||||
etat_actuel = None
|
||||
|
||||
etat_actuel = None
|
||||
|
||||
if len(sys.argv) == 2 :
|
||||
if sys.argv[1] == 'secours' :
|
||||
print "Connexion de secours forcée."
|
||||
nouvel_etat = 'secours'
|
||||
nouvel_etat = 'secours'
|
||||
mode = 'manuel'
|
||||
open(path+'/etat_maitre','w').write('%s\n%s'% (nouvel_etat,mode))
|
||||
open(path+'/etat_maitre','w').write('%s\n%s'% (nouvel_etat,mode))
|
||||
|
||||
elif sys.argv[1] == 'normal' :
|
||||
print "Connexion normale forcée."
|
||||
nouvel_etat = 'normal'
|
||||
nouvel_etat = 'normal'
|
||||
mode = 'manuel'
|
||||
open(path+'/etat_maitre','w').write('%s\n%s'% (nouvel_etat,mode))
|
||||
|
||||
elif sys.argv[1] in ( 'auto', 'test' ) :
|
||||
open(path+'/etat_maitre','w').write('%s\n%s'% (nouvel_etat,mode))
|
||||
|
||||
elif sys.argv[1] in ( 'auto', 'test' ) :
|
||||
if sys.argv[1] == 'auto' :
|
||||
mode = 'auto'
|
||||
|
||||
if mode != 'auto' :
|
||||
print 'Mode manuel, passer en mode auto pour tester'
|
||||
sys.exit(1)
|
||||
|
||||
# On choisi le mode de connexion
|
||||
if normal_ok() : nouvel_etat = 'normal'
|
||||
else : nouvel_etat = 'secours'
|
||||
|
||||
if nouvel_etat != etat_maitre or sys.argv[1] == 'auto' :
|
||||
open(path + '/etat_maitre','w').write('%s\n%s'% (nouvel_etat,mode))
|
||||
|
||||
mode = 'auto'
|
||||
|
||||
if mode != 'auto' :
|
||||
print 'Mode manuel, passer en mode auto pour tester'
|
||||
sys.exit(1)
|
||||
|
||||
# On choisi le mode de connexion
|
||||
if normal_ok() : nouvel_etat = 'normal'
|
||||
else : nouvel_etat = 'secours'
|
||||
|
||||
if nouvel_etat != etat_maitre or sys.argv[1] == 'auto' :
|
||||
open(path + '/etat_maitre','w').write('%s\n%s'% (nouvel_etat,mode))
|
||||
|
||||
print "Mode %s" % mode
|
||||
|
||||
|
||||
if nouvel_etat == etat_actuel :
|
||||
print etat_actuel
|
||||
print etat_actuel
|
||||
else :
|
||||
# Il faut changer
|
||||
sys.stderr.write("Passage en mode %s\n" % nouvel_etat) # Ecriture sur stderr pour le cron
|
||||
sys.stderr.write("Passage en mode %s\n" % nouvel_etat) # Ecriture sur stderr pour le cron
|
||||
for f, c in fichiers.items() :
|
||||
try:
|
||||
print 'Edition de %s' % f
|
||||
|
@ -155,7 +155,7 @@ if __name__ == '__main__' :
|
|||
except:
|
||||
import traceback
|
||||
traceback.print_exc()
|
||||
open('%s/etat_%s' % (path,hostname),'w').write(nouvel_etat)
|
||||
open('%s/etat_%s' % (path,hostname),'w').write(nouvel_etat)
|
||||
for c in cmds :
|
||||
os.system(c)
|
||||
os.system(c)
|
||||
|
||||
|
|
|
@ -84,12 +84,12 @@ infections = curseur.fetchall()
|
|||
liste_virus=""
|
||||
for i in range(1,len(infections)):
|
||||
IP=infections[i][0]
|
||||
print IP
|
||||
try:
|
||||
hostname = socket.gethostbyaddr("%s"%IP)[0]
|
||||
except socket.herror:
|
||||
continue
|
||||
liste_virus+="%s\n"%(str(hostname))
|
||||
print IP
|
||||
try:
|
||||
hostname = socket.gethostbyaddr("%s"%IP)[0]
|
||||
except socket.herror:
|
||||
continue
|
||||
liste_virus+="%s\n"%(str(hostname))
|
||||
|
||||
|
||||
# Machines utilisant des protocoles P2P :
|
||||
|
@ -102,10 +102,10 @@ for i in range(0,len(p2p)):
|
|||
IP=p2p[i][0]
|
||||
protocole = p2p[i][1]
|
||||
hostname = socket.gethostbyaddr("%s"%IP)[0]
|
||||
requete = "SELECT COUNT(ip_src) from p2p where date > timestamp 'now' - interval '1 day' and ip_src='%s'"%IP
|
||||
requete = "SELECT COUNT(ip_src) from p2p where date > timestamp 'now' - interval '1 day' and ip_src='%s'"%IP
|
||||
curseur.execute(requete)
|
||||
paquets=curseur.fetchall()
|
||||
liste_p2p+="%10s\t%20s\t%s\n"%(str(protocole),str(hostname),str(paquets[0][0]))
|
||||
paquets=curseur.fetchall()
|
||||
liste_p2p+="%10s\t%20s\t%s\n"%(str(protocole),str(hostname),str(paquets[0][0]))
|
||||
|
||||
|
||||
#############
|
||||
|
@ -157,7 +157,7 @@ corps = message %{'From':expediteur,
|
|||
'liste_virus':liste_virus,
|
||||
'liste_exemptes':liste_exemptes,
|
||||
'liste_serveurs':liste_serveurs,
|
||||
'seuil':5}
|
||||
'seuil':5}
|
||||
|
||||
#corps = corps.encode('iso 8859-15')
|
||||
mail.sendmail('disconnect@crans.org','disconnect@crans.org',corps)
|
||||
|
|
|
@ -19,7 +19,7 @@ elif os.getuid() != 101 :
|
|||
|
||||
def usage(erreur=None) :
|
||||
if erreur :
|
||||
print erreur
|
||||
print erreur
|
||||
print """Usage :
|
||||
%(p)s start [<numero carte> [<transpondeur>]]:
|
||||
démarrage le transpondeur donné sur la carte donnée,
|
||||
|
|
|
@ -69,7 +69,7 @@ def gen_sap() :
|
|||
ip, port, nom_chaine = line.strip().split(':')
|
||||
file.write(chaine_template % {
|
||||
'nom' : nom_chaine,
|
||||
'langue': nom_chaine.split()[0],
|
||||
'langue': nom_chaine.split()[0],
|
||||
'ip' : ip,
|
||||
'port' : port} )
|
||||
ok=1
|
||||
|
@ -117,9 +117,9 @@ if __name__ == '__main__' :
|
|||
signal.signal(signal.SIGINT,term)
|
||||
|
||||
while 1 :
|
||||
try :
|
||||
gen_sap()
|
||||
except no_data :
|
||||
try :
|
||||
gen_sap()
|
||||
except no_data :
|
||||
# Rien n'est diffusé
|
||||
kill()
|
||||
else :
|
||||
|
|
|
@ -64,10 +64,10 @@ pids=%(pids)s
|
|||
mumudvb = "/usr/local/bin/mumudvb "
|
||||
|
||||
def __cmp__(a,b) :
|
||||
for attr in ( 'card', 'freq', 'chaines' ) :
|
||||
if getattr(a,attr) != getattr(b,attr) :
|
||||
return -2
|
||||
return 0
|
||||
for attr in ( 'card', 'freq', 'chaines' ) :
|
||||
if getattr(a,attr) != getattr(b,attr) :
|
||||
return -2
|
||||
return 0
|
||||
|
||||
def __init__(self,card) :
|
||||
""" Initalisation card est le numéro (entier) de la carte
|
||||
|
|
|
@ -1,5 +1,5 @@
|
|||
#! /usr/bin/env python
|
||||
# -*- coding: iso8859-15 -*-
|
||||
# -*- coding: iso-8859-15 -*-
|
||||
|
||||
""" Défini les transpondeurs à associer à chacune des cartes """
|
||||
|
||||
|
@ -10,29 +10,29 @@ host = gethostname()
|
|||
|
||||
transpondeurs = { 'canard' : [ TNT_R4_498000(0) ,
|
||||
Hotbird_12476(1) ,
|
||||
Hotbird_10911(2) ,
|
||||
Hotbird_12597(3) ,
|
||||
Hotbird_12577(4) ],
|
||||
'lapin' : [ Hotbird_11242(0) ,
|
||||
Hotbird_10911(2) ,
|
||||
Hotbird_12597(3) ,
|
||||
Hotbird_12577(4) ],
|
||||
'lapin' : [ Hotbird_11242(0) ,
|
||||
Hotbird_11604(1) ,
|
||||
TNT_R1_586000(2) ,
|
||||
TNT_R6_562000(3) ,
|
||||
TNT_R2_474000(4) ,
|
||||
TNT_R3_522000(5) ],
|
||||
'oie' : [ Hotbird_12245(0) ,
|
||||
Hotbird_11137(1) ,
|
||||
Hotbird_10873(2) ,
|
||||
Hotbird_11304(3) ,
|
||||
Hotbird_11623(4) ]
|
||||
}
|
||||
TNT_R1_586000(2) ,
|
||||
TNT_R6_562000(3) ,
|
||||
TNT_R2_474000(4) ,
|
||||
TNT_R3_522000(5) ],
|
||||
'oie' : [ Hotbird_12245(0) ,
|
||||
Hotbird_11137(1) ,
|
||||
Hotbird_10873(2) ,
|
||||
Hotbird_11304(3) ,
|
||||
Hotbird_11623(4) ]
|
||||
}
|
||||
|
||||
conf = transpondeurs.get(host,[])
|
||||
|
||||
|
||||
if __name__ == '__main__' :
|
||||
import sys
|
||||
if len(sys.argv) == 2 :
|
||||
conf = transpondeurs.get(sys.argv[1],[])
|
||||
conf = transpondeurs.get(sys.argv[1],[])
|
||||
for t in conf :
|
||||
print t
|
||||
for chaine in t.chaines.values() :
|
||||
print '\t%s' % chaine
|
||||
print t
|
||||
for chaine in t.chaines.values() :
|
||||
print '\t%s' % chaine
|
||||
|
|
|
@ -12,13 +12,13 @@ sys.stdout.write('Nom d\'utilisateur (au format prenom.nom) : ')
|
|||
while True :
|
||||
user = sys.stdin.readline().strip()
|
||||
if user :
|
||||
break
|
||||
break
|
||||
|
||||
while True :
|
||||
pass1 = getpass('Mot de passe : ')
|
||||
pass2 = getpass('Retappez le mot de passe : ')
|
||||
if pass1 == pass2 :
|
||||
break
|
||||
break
|
||||
print 'Les deux mot de passe ne correpondent pas !'
|
||||
|
||||
f = open('/usr/scripts/wifiweb/utilisateurs.py','a+')
|
||||
|
|
|
@ -34,7 +34,7 @@ action = form.getvalue('action','auth')
|
|||
try :
|
||||
url = os.environ['HTTP_REFERER']
|
||||
if '?' in url :
|
||||
url = url.split('?')[0]
|
||||
url = url.split('?')[0]
|
||||
except :
|
||||
url = ''
|
||||
|
||||
|
@ -63,13 +63,13 @@ def message_nok (texte) :
|
|||
def bouton (url='', sid='', action='', caption='') :
|
||||
txt = ''
|
||||
if url :
|
||||
txt += '<form action="%s" method="POST">\n' % url
|
||||
txt += '<form action="%s" method="POST">\n' % url
|
||||
else :
|
||||
txt += '<form method="POST">\n'
|
||||
txt += '<form method="POST">\n'
|
||||
if sid :
|
||||
txt += '<input type="hidden" name="sid" value="%s">\n' % sid
|
||||
txt += '<input type="hidden" name="sid" value="%s">\n' % sid
|
||||
if action :
|
||||
txt += '<input type="hidden" name="action" value="%s">' % action
|
||||
txt += '<input type="hidden" name="action" value="%s">' % action
|
||||
txt += '<input type="submit" value="%s">\n</form>' % caption
|
||||
return txt
|
||||
|
||||
|
@ -84,7 +84,7 @@ if action == 'valid-auth' :
|
|||
sess.data['user'] = form.getvalue('user','')
|
||||
sess.data['password'] = sha.new(form.getvalue('password','')).hexdigest()
|
||||
if users.has_key( sess.data['user'] + ':' + sess.data['password'] ) :
|
||||
log(sess.data['user'] + ' s\'est connecté' )
|
||||
log(sess.data['user'] + ' s\'est connecté' )
|
||||
action = 'index'
|
||||
|
||||
if not sess.data.has_key('user') or not sess.data.has_key('password') :
|
||||
|
@ -93,25 +93,25 @@ if not sess.data.has_key('user') or not sess.data.has_key('password') :
|
|||
if action != 'auth' :
|
||||
|
||||
if users.has_key( sess.data['user'] + ':' + sess.data['password'] ) :
|
||||
# droits de l'utilisateur
|
||||
#########################
|
||||
# droits de l'utilisateur
|
||||
#########################
|
||||
|
||||
# construction de la liste des bornes modifiables
|
||||
bornes_modifiables = []
|
||||
if len(users[ sess.data['user'] + ':' + sess.data['password'] ]) :
|
||||
for lieu in users[ sess.data['user'] + ':' + sess.data['password'] ] :
|
||||
for borne in db.search('canal=*&info=<lieu>%s*' % lieu )['machine'] :
|
||||
nom = borne.nom().encode('iso-8859-15').split('.')[0]
|
||||
if nom not in bornes_modifiables :
|
||||
bornes_modifiables.append(nom)
|
||||
|
||||
# construction de la liste des bornes modifiables
|
||||
bornes_modifiables = []
|
||||
if len(users[ sess.data['user'] + ':' + sess.data['password'] ]) :
|
||||
for lieu in users[ sess.data['user'] + ':' + sess.data['password'] ] :
|
||||
for borne in db.search('canal=*&info=<lieu>%s*' % lieu )['machine'] :
|
||||
nom = borne.nom().encode('iso-8859-15').split('.')[0]
|
||||
if nom not in bornes_modifiables :
|
||||
bornes_modifiables.append(nom)
|
||||
|
||||
else :
|
||||
# erreur d'authentification
|
||||
###########################
|
||||
|
||||
log(sess.data['user'] + ' erreur d\'authentification' )
|
||||
page.add('<font color="red">Erreur d\'authentification !</font><br><br>')
|
||||
action = 'auth'
|
||||
# erreur d'authentification
|
||||
###########################
|
||||
|
||||
log(sess.data['user'] + ' erreur d\'authentification' )
|
||||
page.add('<font color="red">Erreur d\'authentification !</font><br><br>')
|
||||
action = 'auth'
|
||||
|
||||
######################################################
|
||||
# page : authentification
|
||||
|
@ -136,33 +136,33 @@ if action == 'auth' :
|
|||
|
||||
if action == 'desactive' and bornes_modifiables :
|
||||
if form.getvalue('borne','') in bornes_modifiables :
|
||||
log(sess.data['user'] + ' a désactivé %s' % form.getvalue('borne','') )
|
||||
page.add('<font color="blue">La borne <b>%s</b> sera désactivée dans quelques instants</font><br><br>' % form.getvalue('borne','') )
|
||||
borne = db.search('host=%s.wifi.crans.org' % form.getvalue('borne',''), 'w' )['machine'][0]
|
||||
if int(borne.puissance()) > 0 :
|
||||
borne.puissance(-int(borne.puissance()))
|
||||
borne.save()
|
||||
action = 'liste-bornes'
|
||||
log(sess.data['user'] + ' a désactivé %s' % form.getvalue('borne','') )
|
||||
page.add('<font color="blue">La borne <b>%s</b> sera désactivée dans quelques instants</font><br><br>' % form.getvalue('borne','') )
|
||||
borne = db.search('host=%s.wifi.crans.org' % form.getvalue('borne',''), 'w' )['machine'][0]
|
||||
if int(borne.puissance()) > 0 :
|
||||
borne.puissance(-int(borne.puissance()))
|
||||
borne.save()
|
||||
action = 'liste-bornes'
|
||||
else :
|
||||
log(sess.data['user'] + ' a tenté de désactiver %s' % form.getvalue('borne','') )
|
||||
action = 'erreur-droits'
|
||||
log(sess.data['user'] + ' a tenté de désactiver %s' % form.getvalue('borne','') )
|
||||
action = 'erreur-droits'
|
||||
|
||||
######################################################
|
||||
# activation d'un borne
|
||||
|
||||
if action == 'active' and bornes_modifiables :
|
||||
if form.getvalue('borne','') in bornes_modifiables :
|
||||
log(sess.data['user'] + ' a activé %s' % form.getvalue('borne','') )
|
||||
page.add('<font color="blue">La borne <b>%s</b> sera réactivée dans quelques instants</font><br><br>' % form.getvalue('borne','') )
|
||||
borne = db.search('host=%s.wifi.crans.org' % form.getvalue('borne',''),'w' )['machine'][0]
|
||||
if int(borne.puissance()) < 0 :
|
||||
borne.puissance(int(borne.puissance().replace('-','')))
|
||||
borne.save()
|
||||
action = 'liste-bornes'
|
||||
log(sess.data['user'] + ' a activé %s' % form.getvalue('borne','') )
|
||||
page.add('<font color="blue">La borne <b>%s</b> sera réactivée dans quelques instants</font><br><br>' % form.getvalue('borne','') )
|
||||
borne = db.search('host=%s.wifi.crans.org' % form.getvalue('borne',''),'w' )['machine'][0]
|
||||
if int(borne.puissance()) < 0 :
|
||||
borne.puissance(int(borne.puissance().replace('-','')))
|
||||
borne.save()
|
||||
action = 'liste-bornes'
|
||||
else :
|
||||
log(sess.data['user'] + ' a tenté d\'activer %s' % form.getvalue('borne','') )
|
||||
page.add('<font color="red">Vous n\'êtes pas authorisé à modifier la borne <b>%s</b></font><br><br>' % form.getvalue('borne','') )
|
||||
action = 'erreur-droits'
|
||||
log(sess.data['user'] + ' a tenté d\'activer %s' % form.getvalue('borne','') )
|
||||
page.add('<font color="red">Vous n\'êtes pas authorisé à modifier la borne <b>%s</b></font><br><br>' % form.getvalue('borne','') )
|
||||
action = 'erreur-droits'
|
||||
|
||||
######################################################
|
||||
# page : liste des bornes
|
||||
|
@ -171,41 +171,41 @@ if action == 'liste-bornes' and bornes_modifiables :
|
|||
page.sous_titre('Liste des bornes')
|
||||
|
||||
for b in bornes_modifiables :
|
||||
try :
|
||||
borne = db.search('host=%s.wifi.crans.org' % b)['machine'][0]
|
||||
except :
|
||||
log('borne non existante : %s' % b)
|
||||
continue
|
||||
|
||||
# formulaire
|
||||
page.add('<form method=\"POST\">')
|
||||
page.add('<input type="hidden" name="sid" value="%s">' % sid )
|
||||
page.add('<input type="hidden" name="borne" value="%s">' % b)
|
||||
|
||||
# titre
|
||||
if '-' in borne.puissance() :
|
||||
# réactivation
|
||||
page.add('<b><u>%s</u></b> <font color="red">(borne désactivée)</font>' % borne.Nom().encode('iso-8859-15'))
|
||||
page.add('<input type="hidden" name="action" value="active">')
|
||||
else :
|
||||
# désctivation
|
||||
page.add('<b><u>%s</u></b> <font color="green">(borne activée)</font>' % borne.Nom().encode('iso-8859-15'))
|
||||
page.add('<input type="hidden" name="action" value="desactive">')
|
||||
page.add('<br>')
|
||||
|
||||
# commentaires
|
||||
page.add('<table><tr><td width=\"20\"> </td><td>')
|
||||
page.add('<br>'.join( filter(lambda x : re.match("^\<.*\>", x) == None, borne.info() ) ).encode('iso-8859-15'))
|
||||
page.add('</td></tr></table>')
|
||||
|
||||
# bouton de validation
|
||||
if '-' in borne.puissance() :
|
||||
page.add('<input type="submit" value="Réactiver %s">' % b)
|
||||
else :
|
||||
page.add('<input type="submit" value="Désactiver %s">' % b)
|
||||
try :
|
||||
borne = db.search('host=%s.wifi.crans.org' % b)['machine'][0]
|
||||
except :
|
||||
log('borne non existante : %s' % b)
|
||||
continue
|
||||
|
||||
# formulaire
|
||||
page.add('<form method=\"POST\">')
|
||||
page.add('<input type="hidden" name="sid" value="%s">' % sid )
|
||||
page.add('<input type="hidden" name="borne" value="%s">' % b)
|
||||
|
||||
# titre
|
||||
if '-' in borne.puissance() :
|
||||
# réactivation
|
||||
page.add('<b><u>%s</u></b> <font color="red">(borne désactivée)</font>' % borne.Nom().encode('iso-8859-15'))
|
||||
page.add('<input type="hidden" name="action" value="active">')
|
||||
else :
|
||||
# désctivation
|
||||
page.add('<b><u>%s</u></b> <font color="green">(borne activée)</font>' % borne.Nom().encode('iso-8859-15'))
|
||||
page.add('<input type="hidden" name="action" value="desactive">')
|
||||
page.add('<br>')
|
||||
|
||||
# commentaires
|
||||
page.add('<table><tr><td width=\"20\"> </td><td>')
|
||||
page.add('<br>'.join( filter(lambda x : re.match("^\<.*\>", x) == None, borne.info() ) ).encode('iso-8859-15'))
|
||||
page.add('</td></tr></table>')
|
||||
|
||||
# bouton de validation
|
||||
if '-' in borne.puissance() :
|
||||
page.add('<input type="submit" value="Réactiver %s">' % b)
|
||||
else :
|
||||
page.add('<input type="submit" value="Désactiver %s">' % b)
|
||||
|
||||
# fin du formulaire
|
||||
page.add('</form>')
|
||||
# fin du formulaire
|
||||
page.add('</form>')
|
||||
|
||||
# menu de fin de page
|
||||
page.add( "<center><table><tr><td>%s</td><td>%s</td><td>%s</td></tr></center>" % ( bouton(url,sid,'liste-bornes','Actualiser'), bouton_menu, bouton_quitter ) )
|
||||
|
@ -228,7 +228,7 @@ if action == 'index' :
|
|||
# menu principal
|
||||
page.sous_titre("Menu principal")
|
||||
if bornes_modifiables :
|
||||
page.add('<a href="?sid=%s&action=liste-bornes">Activation/désactivation d\'une borne</a><br>' % sid )
|
||||
page.add('<a href="?sid=%s&action=liste-bornes">Activation/désactivation d\'une borne</a><br>' % sid )
|
||||
# menu de bas de page
|
||||
page.add("<center>%s</center>" % bouton_quitter )
|
||||
|
||||
|
|
|
@ -7,85 +7,85 @@ from time import time
|
|||
class session :
|
||||
|
||||
def __init__ (self, sid = None) :
|
||||
"""
|
||||
Si sid est fournit, on regarde si la session est valide ;
|
||||
on soulève un exeption si il y a un problème
|
||||
|
||||
Si sid n'est pas fourni un créé une nouvelle session
|
||||
"""
|
||||
self.save = True
|
||||
|
||||
if sid :
|
||||
|
||||
# on vérifie la validité
|
||||
if not os.access( self._sess_file(sid), os.W_OK ) :
|
||||
raise ValueError, 'Session inconnue'
|
||||
|
||||
# on exporte le sid
|
||||
self.sid = sid
|
||||
|
||||
# on lit les données
|
||||
self.data = {}
|
||||
f = open(self._sess_file(sid))
|
||||
for i in f.readlines() :
|
||||
if not i.strip() :
|
||||
continue
|
||||
key = i.split(' ')[0]
|
||||
value = ' '.join(i.split(' ')[1:]).strip()
|
||||
self.data[key] = value
|
||||
|
||||
if int(self.data['perime']) < int(time()) :
|
||||
self.destroy()
|
||||
raise ValueError, 'Session périmée'
|
||||
|
||||
else :
|
||||
|
||||
# on créé un nouveau sid
|
||||
self.data = {}
|
||||
ok = False
|
||||
while not ok :
|
||||
sid = ''.join( [ random.choice('abcdefghijklmnopqrstuvwxyz0123456789') for i in range(0,30) ])
|
||||
# est ce que la session existe ?
|
||||
if not os.path.exists(self._sess_file(sid)) :
|
||||
# on créé un nouveau fichier avec un timeout de 60
|
||||
f = os.open(self._sess_file(sid), os.O_WRONLY + os.O_CREAT , 0600)
|
||||
f
|
||||
# on valide
|
||||
ok = True
|
||||
self.sid = sid
|
||||
|
||||
# on initialise les données
|
||||
self.data = {'timeout' : '600'}
|
||||
|
||||
"""
|
||||
Si sid est fournit, on regarde si la session est valide ;
|
||||
on soulève un exeption si il y a un problème
|
||||
|
||||
Si sid n'est pas fourni un créé une nouvelle session
|
||||
"""
|
||||
self.save = True
|
||||
|
||||
if sid :
|
||||
|
||||
# on vérifie la validité
|
||||
if not os.access( self._sess_file(sid), os.W_OK ) :
|
||||
raise ValueError, 'Session inconnue'
|
||||
|
||||
# on exporte le sid
|
||||
self.sid = sid
|
||||
|
||||
# on lit les données
|
||||
self.data = {}
|
||||
f = open(self._sess_file(sid))
|
||||
for i in f.readlines() :
|
||||
if not i.strip() :
|
||||
continue
|
||||
key = i.split(' ')[0]
|
||||
value = ' '.join(i.split(' ')[1:]).strip()
|
||||
self.data[key] = value
|
||||
|
||||
if int(self.data['perime']) < int(time()) :
|
||||
self.destroy()
|
||||
raise ValueError, 'Session périmée'
|
||||
|
||||
else :
|
||||
|
||||
# on créé un nouveau sid
|
||||
self.data = {}
|
||||
ok = False
|
||||
while not ok :
|
||||
sid = ''.join( [ random.choice('abcdefghijklmnopqrstuvwxyz0123456789') for i in range(0,30) ])
|
||||
# est ce que la session existe ?
|
||||
if not os.path.exists(self._sess_file(sid)) :
|
||||
# on créé un nouveau fichier avec un timeout de 60
|
||||
f = os.open(self._sess_file(sid), os.O_WRONLY + os.O_CREAT , 0600)
|
||||
f
|
||||
# on valide
|
||||
ok = True
|
||||
self.sid = sid
|
||||
|
||||
# on initialise les données
|
||||
self.data = {'timeout' : '600'}
|
||||
|
||||
def _sess_file (self, sid = None) :
|
||||
""" Retourne le nom du fichier correspondant à la session """
|
||||
if not sid :
|
||||
sid = self.sid
|
||||
return '/tmp/pysession-%s' % sid
|
||||
""" Retourne le nom du fichier correspondant à la session """
|
||||
if not sid :
|
||||
sid = self.sid
|
||||
return '/tmp/pysession-%s' % sid
|
||||
|
||||
def __del__ (self) :
|
||||
""" On enregsitre la session à la destruction de l'instance """
|
||||
|
||||
if self.save :
|
||||
# epok de peromption
|
||||
self.data['perime'] = str(int(time() + int(self.data['timeout'])))
|
||||
""" On enregsitre la session à la destruction de l'instance """
|
||||
|
||||
if self.save :
|
||||
# epok de peromption
|
||||
self.data['perime'] = str(int(time() + int(self.data['timeout'])))
|
||||
|
||||
f = open(self._sess_file(), 'w')
|
||||
for k in self.data.keys() :
|
||||
f.write( '%s %s\n' % (k,self.data[k]) )
|
||||
f.close()
|
||||
f = open(self._sess_file(), 'w')
|
||||
for k in self.data.keys() :
|
||||
f.write( '%s %s\n' % (k,self.data[k]) )
|
||||
f.close()
|
||||
|
||||
def destroy(self) :
|
||||
""" Supprime la session """
|
||||
self.save = False
|
||||
os.remove( self._sess_file() )
|
||||
""" Supprime la session """
|
||||
self.save = False
|
||||
os.remove( self._sess_file() )
|
||||
|
||||
# on supprime toutes les vieilles sessions
|
||||
for file in os.listdir('/tmp') :
|
||||
if file[0:10] == 'pysession-' :
|
||||
#print file[10:]
|
||||
try :
|
||||
s = session(file[10:])
|
||||
s.save = False
|
||||
except :
|
||||
continue
|
||||
#print file[10:]
|
||||
try :
|
||||
s = session(file[10:])
|
||||
s.save = False
|
||||
except :
|
||||
continue
|
||||
|
|
|
@ -16,10 +16,10 @@ def Cellule(texte, couleur, f) :
|
|||
def execute(macro, text) :
|
||||
|
||||
try :
|
||||
f = open('/usr/scripts/secours/etat_maitre')
|
||||
if f.readline().strip() == 'normal' :
|
||||
return Cellule('Nous sommes actuellement en connexion normale.','lime',macro.formatter)
|
||||
else :
|
||||
return Cellule('Nous sommes actuellement en connexion de secours.','red',macro.formatter)
|
||||
f = open('/usr/scripts/secours/etat_maitre')
|
||||
if f.readline().strip() == 'normal' :
|
||||
return Cellule('Nous sommes actuellement en connexion normale.','lime',macro.formatter)
|
||||
else :
|
||||
return Cellule('Nous sommes actuellement en connexion de secours.','red',macro.formatter)
|
||||
except :
|
||||
return Cellule('Impossible de déterminer l\'état de la connexion.','yellow',macro.formatter)
|
||||
return Cellule('Impossible de déterminer l\'état de la connexion.','yellow',macro.formatter)
|
||||
|
|
Loading…
Add table
Add a link
Reference in a new issue