[lib] ajout des fichiers non suivis

darcs-hash:20090609134320-bd074-f4df3e57ff2a6e60f07e25cda773524c8e20de3c.gz
parent dce8ccb6
#!/usr/bin/env python
# -*- coding: iso-8859-15 -*-
# #############################################################
# ..
# .... ............ ........
# . ....... . .... ..
# . ... .. .. .. .. ..... . ..
# .. .. ....@@@. .. . ........ .
# .. . .. ..@.@@..@@. .@@@@@@@ @@@@@@. ....
# .@@@@. .@@@@. .@@@@..@@.@@..@@@..@@@..@@@@.... ....
# @@@@... .@@@.. @@ @@ .@..@@..@@...@@@. .@@@@@. ..
# .@@@.. . @@@. @@.@@..@@.@@..@@@ @@ .@@@@@@.. .....
# ...@@@.... @@@ .@@.......... ........ ..... ..
# . ..@@@@.. . .@@@@. .. ....... . .............
# . .. .... .. .. . ... ....
# . . .... ............. .. ...
# .. .. ... ........ ... ...
# ................................
#
# #############################################################
"""
cp.py
Fonctions pour cherrypy (intranet)
Copyright (c) 2006 by www.crans.org
"""
import cherrypy
def log(string, keyword = "INTRANET", level = 0):
"""Utilise la fonction log de cherrypy avec quelques modification
-> introduit le login de la session en cours s'il existe
"""
try:
login = cherrypy.session['uid']
string = "[%s] %s" % ( login, string )
except:
pass
cherrypy.log(string, keyword, level)
#!/usr/bin/env python
# -*- coding: utf-8 -*-
# #############################################################
# ..
# .... ............ ........
# . ....... . .... ..
# . ... .. .. .. .. ..... . ..
# .. .. ....@@@. .. . ........ .
# .. . .. ..@.@@..@@. .@@@@@@@ @@@@@@. ....
# .@@@@. .@@@@. .@@@@..@@.@@..@@@..@@@..@@@@.... ....
# @@@@... .@@@.. @@ @@ .@..@@..@@...@@@. .@@@@@. ..
# .@@@.. . @@@. @@.@@..@@.@@..@@@ @@ .@@@@@@.. .....
# ...@@@.... @@@ .@@.......... ........ ..... ..
# . ..@@@@.. . .@@@@. .. ....... . .............
# . .. .... .. .. . ... ....
# . . .... ............. .. ...
# .. .. ... ........ ... ...
# ................................
#
# #############################################################
# authentification.py
#
# Fonction de login et petite classe utilisateur
#
# Auteur: Grégoire Détrez <gdetrez@crans.org>
# Copyright (c) 2008 by www.crans.org
# #############################################################
import ldap
#import cransldap
import models
import fields
LDAP_SERVER = "ldap.adm.crans.org"
# Petite classe Avec les infos de base de l'utilisateur
class User(models.Model):
prenom = fields.stringField( "Prénom" )
nom = fields.stringField( "Nom" )
mail = fields.stringField( "Couriel" )
uid = fields.loginField( "Identifiant" )
aid = fields.intField( "aid" )
droits = fields.listField( "Droits", fields.stringField(None) )
def is_nounou(self):
return u"Nounou" in self.droits
class AuthentificationFailed(Exception):
def __str__(self):
return "Oups, auth failed"
def login( id, password ):
""" returns a User object """
con = ldap.open( LDAP_SERVER )
try:
user_dn = get_dn_from_id( id, con )
except ValueError:
raise AuthentificationFailed
try:
con.bind_s(user_dn, password)
except ldap.INVALID_CREDENTIALS, e:
raise AuthentificationFailed
data = con.search_s(user_dn, ldap.SCOPE_SUBTREE)
con.unbind()
data = data[0][1]
return User(data)
def get_dn_from_id( id, ldap_connexion=None ):
if ldap_connexion == None:
ldap_connexion = ldap.open( LDAP_SERVER )
try:
aid = int( id )
user_dn = "aid=%d,ou=data,dc=crans,dc=org" % aid
return user_dn
except ValueError:
data = ldap_connexion.search_s("ou=data,dc=crans,dc=org",
ldap.SCOPE_SUBTREE,
"uid=%s" % id)
if len(data) != 1:
raise ValueError, "Id invalid"
else: return data[0][0]
#!/usr/bin/env python
# -*- coding: utf-8 -*-
# #############################################################
# ..
# .... ............ ........
# . ....... . .... ..
# . ... .. .. .. .. ..... . ..
# .. .. ....@@@. .. . ........ .
# .. . .. ..@.@@..@@. .@@@@@@@ @@@@@@. ....
# .@@@@. .@@@@. .@@@@..@@.@@..@@@..@@@..@@@@.... ....
# @@@@... .@@@.. @@ @@ .@..@@..@@...@@@. .@@@@@. ..
# .@@@.. . @@@. @@.@@..@@.@@..@@@ @@ .@@@@@@.. .....
# ...@@@.... @@@ .@@.......... ........ ..... ..
# . ..@@@@.. . .@@@@. .. ....... . .............
# . .. .... .. .. . ... ....
# . . .... ............. .. ...
# .. .. ... ........ ... ...
# ................................
#
# #############################################################
# __init__.py
#
# Fields: outils pour passer les informations de la base
# vers les objets python et vice-versa
#
# Auteur: Grégoire Détrez <gdetrez@crans.org>
# Copyright (c) 2008 by www.crans.org
# #############################################################
import re
class baseField(object):
def __init__(self, name):
self.name = name
def _save_field( self, data ):
return data
def _load_field( self, data ):
return str(data)
def load( self, ldap_data ):
if ldap_data == None: return None
return self._load_field( ldap_data[0] )
def save( self, field_data ):
return [ self._save_field( field_data )]
class stringField( baseField ):
pass
class reField( stringField ):
def __init__( self, name, expr ):
baseField.__init__(self, name)
self.expr = re.compile(expr)
def _save_field(self, field_data):
if self.expr.match( field_data ):
return field_data
else:
raise ValueError, "Incorect value for field %s" % self.name
class macField( reField ):
def __init__( self, name ):
self = reField.__init__(self, name, "^([0-9a-fA-F]{2}:){5}[0-9a-fA-F]{2}$")
def _save_field( self, data ):
data = data.lower()
if not self.expr.match( data ):
data = re.sub( "[^0-9a-fA-F]", "", data )
if len(data) == 12:
data = data[0:2] + ":" + data[2:4] + ":" + data [4:6] + ":" + data[6:8] + ":" + data[8:10] + ":" + data[10:12]
return reField._save_field( self, data )
class ipField( reField ):
def __init__( self, name ):
self = reField.__init__(self, name, "^(\d{1,3}\.){3}\d{1,3}$")
class emailField( reField ):
def __init__( self, name, suffix=None ):
stringField.__init__( self, name)
self.expr = re.compile("^(?P<prefix>[\w\+]+)(@(?P<suffix>[\w\.]+\.\w{1,3}))?$" )
self.suffix = suffix
def _load_field(self, data):
if self.suffix:
m = self.expr.match( data )
if m.group('suffix'):
return data
else:
return data + u"@" + self.suffix
else:
return data
def _save_field(self, data):
m = self.expr.match( data )
if m:
if self.suffix and m.group("suffix") == self.suffix:
return m.group("prefix")
return data
else:
raise ValueError, "Mail invalid"
class loginField( reField ):
def __init__( self, name ):
self = reField.__init__(self, name, "^[a-z]{4,}$")
class listField( baseField ):
def __init__( self, name, type_field ):
baseField.__init__(self, name)
self.type_field = type_field
def load( self, ldap_data ):
if ldap_data == None: return []
return map( self.type_field._load_field, ldap_data )
def save( self, field_data ):
return map( self.type_field._save_field, field_data )
class historyField( baseField ):
pass
class pathField( baseField ):
pass
class intField( baseField ):
def _load_field( self, ldap_data ):
return int( ldap_data )
def _save_field(self, field_data ):
return str( field_data )
class booleanField( baseField ):
def _load_field( self, ldap_data ):
return ldap_data == 'TRUE'
def _save_field( self, field_Data ):
if field_data: return 'TRUE'
else: return 'FALSE'
class telField( reField ):
def __init__(self, name ):
reField.__init__( self, name, "^\d{10}$")
def _save_field( self, data ):
return reField._save_field( self, re.sub("[\ \.,]", "", data ) )
if __name__ == "__main__":
import unittest
class TestFields(unittest.TestCase):
def setUp(self):
pass
def testBaseField( self ):
field = baseField( "Un nom" )
assert field.load(["un test"]) == "un test"
assert field.save("un test") == ["un test"]
def testStringField( self ):
field = stringField( "Un nom" )
assert field.load(["une string"]) == "une string"
assert field.save("une string") == ["une string"]
def testReField( self ):
field = reField( "Un nom", "^[A-Z][a-z]+$" )
assert field.load(["Coucou"]) == "Coucou"
assert field.save("Coucou") == ["Coucou"]
self.assertRaises(ValueError, field.save, "")
self.assertRaises(ValueError, field.save, "coucou")
self.assertRaises(ValueError, field.save, "coucou monde")
self.assertRaises(ValueError, field.save, "Coucou monde")
def testMacField( self ):
field = macField( "Un nom" )
assert field.load(["00:0f:20:57:6e:81"]) == "00:0f:20:57:6e:81"
assert field.save("00:0f:20:57:6e:81") == ["00:0f:20:57:6e:81"]
assert field.save("00:0F:20:57:6E:81") == ["00:0f:20:57:6e:81"]
assert field.save("000f20576e81") == ["00:0f:20:57:6e:81"]
assert field.save("00 0f 20 57 6e 81") == ["00:0f:20:57:6e:81"]
self.assertRaises(ValueError, field.save, "00:0f:20:57:6e:81:34")
self.assertRaises(ValueError, field.save, "00:0f:20:57:6e:8")
self.assertRaises(ValueError, field.save, "00:0f:20:57:6e")
self.assertRaises(ValueError, field.save, "00:0f:20:57:6k:81")
def testIpField( self ):
field = ipField( "Un nom" )
assert field.load(["129.168.0.34"]) == "129.168.0.34"
assert field.save("129.168.0.34") == ["129.168.0.34"]
self.assertRaises(ValueError, field.save, "192.16.8")
self.assertRaises(ValueError, field.save, "192.16.8.2.3")
self.assertRaises(ValueError, field.save, "192.16.8.e")
self.assertRaises(ValueError, field.save, "125.34..56")
def testEmailField( self ):
field = emailField( "Un email", suffix="crans.org" )
assert field.load(["toto@exemple.com"]) == "toto@exemple.com"
assert field.save("toto@exemple.com") == ["toto@exemple.com"]
assert field.load(["toto@crans.org"]) == "toto@crans.org"
assert field.load(["toto"]) == "toto@crans.org"
assert field.save("toto") == ["toto"]
assert field.save("toto@crans.org") == ["toto"]
self.assertRaises(ValueError, field.save, "toto@")
self.assertRaises(ValueError, field.save, "toto@test")
self.assertRaises(ValueError, field.save, "test.com")
def testLoginField( self ):
field = loginField( "Un nom" )
assert field.load(["toto"]) == "toto"
assert field.save("toto") == ["toto"]
# def testHistoryField( self ):
# field = baseField( "Un nom" )
# assert field.load(["un test"]) == "un test"
# assert field.save("un test") == ["un test"]
def testListField( self ):
field = listField( "Un nom", stringField(None) )
assert field.load(["un test"]) == ["un test"]
assert field.load(["un test", "un autre"]) == ["un test", "un autre"]
def testTelField( self ):
field = telField( "Un nom" )
assert field.load(["0606060606"]) == "0606060606"
assert field.save("0606060606") == ["0606060606"]
assert field.save("06 060 606 06") == ["0606060606"]
assert field.save("06 06 06 06 06") == ["0606060606"]
self.assertRaises(ValueError, field.save, "06060606")
self.assertRaises(ValueError, field.save, "06060606060606")
unittest.main()
#!/usr/bin/env python
# -*- coding: utf-8 -*-
# #############################################################
# ..
# .... ............ ........
# . ....... . .... ..
# . ... .. .. .. .. ..... . ..
# .. .. ....@@@. .. . ........ .
# .. . .. ..@.@@..@@. .@@@@@@@ @@@@@@. ....
# .@@@@. .@@@@. .@@@@..@@.@@..@@@..@@@..@@@@.... ....
# @@@@... .@@@.. @@ @@ .@..@@..@@...@@@. .@@@@@. ..
# .@@@.. . @@@. @@.@@..@@.@@..@@@ @@ .@@@@@@.. .....
# ...@@@.... @@@ .@@.......... ........ ..... ..
# . ..@@@@.. . .@@@@. .. ....... . .............
# . .. .... .. .. . ... ....
# . . .... ............. .. ...
# .. .. ... ........ ... ...
# ................................
#
# #############################################################
# models.py
#
# Classe de base pour mapper automatiquement des
# enregistrements ldap et des objets python
#
# Auteur: Grégoire Détrez <gdetrez@crans.org>
# Copyright (c) 2008 by www.crans.org
# #############################################################
import fields
class MetaModel(type):
def __init__(cls, name, bases, attrs):
super(type, cls).__init__(cls, name, bases, attrs)
_fields = {}
for item_name in attrs:
if isinstance(attrs[item_name], fields.baseField):
_fields[item_name] = attrs[item_name]
setattr(cls, "_model_fields", _fields)
class Model(object):
__metaclass__ = MetaModel
def __init__( self, data ):
k = self._model_fields
for a_field in self._model_fields:
val = self._model_fields[a_field].load(data.get(a_field, None))
setattr(self, a_field, val)
"""
__init__.py
Fonction de base pour les mails.
Copyright (c) 2006 by www.crans.org
"""
SENDMAIL = "/usr/sbin/sendmail" # sendmail location
def quickSend(From=None, To=None, Subject=None, Text=None, disconnect_on_bounce=0):
"""envoie d'un mail"""
OPTIONS = ' -t' #extract recipient from headers
if disconnect_on_bounce:
OPTIONS+= ' -V -f bounces'
from os import popen
p = popen("%s -t %s" % (SENDMAIL, OPTIONS), "w")
p.write("From: %s\n" % From)
p.write("To: %s\n" % To)
p.write("Subject: %s\n" % Subject)
p.write("\n") # blank line separating headers from body
p.write("%s\n" % Text)
sts = p.close()
if sts:
print "Sendmail exit status", sts
This diff is collapsed.
#! /usr/bin/env python
import re, commands
import crans.utils.logs
import logging
LOGGER = logging.getLogger("crans.autologout")
LOGGER.addHandler(crans.utils.logs.CransFileHandler("autologout"))
LOGGER.setLevel(logging.WARNING)
def run_autologout():
LOGGER.debug("Starting autologout")
# pour chaque ligne du w
for w in commands.getoutput("w -h").split('\n') :
if not w : continue
# on splite
w = w.split()
if w[0] in ['cohen','segaud']:
continue
# on verifie que c'est une connection du bde
hosts = ['bde.crans.org','cableur.crans.org','cableuse.crans.org','venus.crans.org']
if w[2] not in [ h[0:16] for h in hosts ] :
continue
# on verifie qu'on a depase le timeout
if re.match('^\d*\.\d*s$', w[4]) or re.match('^[0-4]:\d*m$', w[4]) :
continue
# on reccuperre les processus s le tty
ps = commands.getoutput('ps auwwx | grep "%s" | head -n 1' % w[1] ).split()
# on verrifie que c'est le bon user
if ps[0] != w[0] :
continue
# on verifie qu'on a pas de tty
if ps[6] != '?' :
continue
# on tue le process
commands.getoutput('kill %s' % ps[1] )
LOGGER.info("%s a ete deconnecte" % ps[0])
#print ps
if __name__ == "__main__":
run_autologout()
import logging
from crans.utils.logs import getFileLogger
#LOGGER = logging.getLogger("crans.scripts.test")
LOGGER = getFileLogger("helloworld")
LOGGER.setLevel(logging.INFO)
LOGGER.addHandler(logging.StreamHandler())
if __name__ == "__main__":
LOGGER.info(u"Hello World")
SAP_FILE_URL = "http://tv/sap.txt"
BASE_IMAGE_URL = "http://tv/images/"
IMAGE_SUFFIX = ".jpg"
SMALL_IMAGE_SUFFIX = "_petites.jpg"
class Channel:
pass
class ChannelGroup:
pass
# -*- coding: utf8 -*-
""" Cr@ns logging : logging utilities for cr@ns scripts
"""
import logging
import os
LOG_FOLDER = "/var/log/crans/"
__version__ = "0.1"
def getFileLogger(name):
LOGGER.warning("getFileLogger is deprecated, use CransFileHandler instead.")
logger = logging.getLogger(name)
hdlr = CransFileHandler(name)
logger.addHandler(hdlr)
logger.setLevel(logging.INFO)
return logger
class CransFileHandler(logging.FileHandler):
def __init__(self, name):
filepath = os.path.join(LOG_FOLDER, name + ".log")
logging.FileHandler.__init__(self, filepath)
formatter = logging.Formatter('%(asctime)s %(name)s %(levelname)s %(message)s')
self.setFormatter(formatter)
### Un peu de configuration
# On log systematiquement les warning, error, exception sous "crans"
# sur l'ecran.
CRANSLOGGER = logging.getLogger("crans")
CRANSLOGGER.setLevel(logging.WARNING)
streamhdlr = logging.StreamHandler()
streamhdlr.setLevel(logging.ERROR)
streamhdlr.setFormatter(logging.Formatter('%(levelname)s: %(message)s'))
CRANSLOGGER.addHandler(streamhdlr)
CRANSLOGGER.addHandler(CransFileHandler("crans"))
LOGGER = logging.getLogger("crans.logging")
# -*- coding: utf8 -*-
import os
LABELS = {
"/home":u"Dossier personnel",
"/var/mail":u"Boite de réception"
}
def getFloat( chose ):
chose = chose.replace(',', '.')
return float(chose)
def getUserQuota( userLogin ):
pipe = os.popen("sudo quota %s" % userLogin)
string_result = pipe.read()
pipe.close()
string_result = string_result.split("\n")
quotas = []
for a_line in string_result[2:3]:
usage, quota, limite, percentage = a_line.split("\t")
line_dict = {
"label": "Quota personnel",
"usage":getFloat(usage),
"quota":getFloat(quota),
"limite":getFloat(limite),
"%":getFloat(percentage),
"filesystem":"rda", # pourquoi pas ?
}
quotas.append(line_dict)
return quotas
def fake_getUserQuota( userLogin ):
return [
{'%': 33.9,
'quota': 390.62,
'label': u'Dossier personnel (fake)',
'limite': 585.94,
'filesystem': '/home',
'usage': 420.32},
{'%': 0.1,
'quota': 100.00,
'label': u'Boite de r\xe9ception (fake)',
'limite': 150.00,
'filesystem': '/var/mail',
'usage': 0.06}
]
\ No newline at end of file
# -*- coding: utf-8 -*-
class PagePerso:
"""Classe reprsentant la page perso d'une personne"""
home = "/home"
www = "/www"
def __init__(self, login):
"""Instanciation avec le login' de la personne"""
self.login = login
self.home = "%s/%s" % (self.home, login)
_info = {}
self._load_informations()
def _filename( self ):
return "%s/.info" % self.home
def _load_informations(self):
try:
lignes = file( self._filename() )
except IOError:
lignes = []
# self._info est un dictionnaire qui reprend le contenu du .info
self._info = dict( map( lambda z: (unicode(z[0].lower(),"iso-8859-15"),
unicode(z[1],"iso-8859-15")),
filter(lambda w: len(w) == 2 and len(w[1]),
map(lambda x: map(lambda y: y.strip(),
x.split(":")),
lignes))))
def _save_informations( self ):
myfile = file(self._filename(), "w")
for aKey in self._info.keys():
myfile.write("%s:%s\n" % (aKey, self.
_info[aKey]) )
myfile.write("\n")
def save( self ):
self._save_informations()
def chemin(self):
"""Chemin vers le www"""
return u"%s%s" % (self.home, self.www)
def url(self):
"""URL vers la page perso"""
return u"http://perso.crans.org/%s/" % self.login
def nom( self ):
return self._info.get("nom", "")
def setNom( self, nom ):
self._info["nom"] = nom
def slogan( self ):
return self._info.get("slogan", "")
def setSlogan( self, slogan ):
self._info["slogan"] = slogan
def logo(self):
"""URL du logo s'il y en a un"""
logo = self._info.get("logo", None)
if logo:
# Le logo peut tre en absolu ou en relatif
if logo.startswith(self.chemin()):
logo = logo.replace("%s/" % self.chemin(), "")
if os.path.isfile("%s/%s" % (self.chemin(), logo)):
return u"%s%s" % (self.url(), logo)
return u"http://perso.crans.org/pageperso.png"
def __str__(self):
"""Renvoie le code HTML correspondant au fichier .info"""
html = [ u'<div class="vignetteperso">',
u'<a href="%s">' % self.url(),
u'<img src="%s" alt="%s">' % (self.logo(), self.login),
u'</a><br>',
self.info("nom") and u'<b>%s</b><br>' % self.info("nom") or u'%s<br>' % self.login,
self.info("devise") and u'<i>%s</i>' % self.info("devise") or u'',
u'</div>' ]
return u'\n'.join(html)
Markdown is supported
0% or
You are about to add 0 people to the discussion. Proceed with caution.
Finish editing this message first!
Please register or to comment