Commit b7899d2d authored by Gabriel Detraz's avatar Gabriel Detraz
Browse files

Adherent.py utilisant lc_ldap, affichage

parent 964e8e18
#!/bin/bash /usr/scripts/python.sh
# -*- coding: utf-8 -*-
# Copyright (C) Frédéric Pauget
# Licence : GPLv2
import smtplib, socket, sys, commands, shutil, os, traceback,grp
from time import strftime
import gestion.config as config
import config.mails as config_mails
import gestion.mail as mail_module
import gestion.affichage as affichage
from lc_ldap import shortcuts
try:
sys.path.append('/usr/lib/mailman')
from Mailman.MailList import MailList
from Mailman.UserDesc import UserDesc
from Mailman.Errors import MMAlreadyAMember
except:
# Machine sans mailman, les ML ne seront pas reconfigurées
pass
# Connexion lc_ldap ro
ldap = shortcuts.lc_ldap_readonly()
# Hostname
hostname = socket.gethostname()
class del_user:
""" Suppression des fichiers d'un compte utilisateur """
debug = True
def __init__(self, args):
self.args = args
def delete_directory(self, caption, pattern):
animation = affichage.Animation(texte=caption, nb_cycles=len(self.args), couleur=True, kikoo=True)
for args in self.args:
animation.new_step()
print('\n' + args)
try:
login = args.split(',')[0]
d = pattern % login
if os.path.isdir(d):
shutil.rmtree(d)
print affichage.OK
except:
print affichage.ERREUR
if self.debug:
import traceback
traceback.print_exc()
def delete_zbee(self):
animation = affichage.Animation(texte="Archivage fichiers utilisateur", nb_cycles=len(self.args), couleur=True, kikoo=True)
for args in self.args:
animation.new_step()
print("\n" + self.args)
try:
login, home = args.split(',')
homesplit = home.split("/")
symlink = "/home-adh/%s" % (homesplit[-1],)
if not login or not home:
raise ValueError('Argument invalide')
if home.startswith('/home/') and hostname == "zbee":
home = "/home-adh/" + home[6:]
warn = ''
f = '%s/files/%s_%s.tar.bz2' % ('/home-adh/cimetiere',
strftime('%Y-%m-%d-%Hh%Mm'),
login)
status, output = commands.getstatusoutput("tar cjf '%s' '%s' /home-adh/mail/%s" % (f, home, login))
if (status != 512 and status != 0) or not os.path.isfile(f):
# La 512 est si un des paths n'exite pas.
raise OSError(output)
if os.path.isdir(home) and os.stat(home)[4] >= 500:
if homesplit[-2] != "club":
if os.path.exists(symlink) and os.path.islink(symlink):
os.unlink(symlink)
shutil.rmtree(home)
else:
warn += '%s incorrect\n' % home
if os.path.isdir('/home-adh/mail/' + login):
shutil.rmtree('/home-adh/mail/' + login)
else:
warn += '/home-adh/mail/%s incorrect\n' % login
if warn:
print affichage.WARNING
if self.debug:
sys.stderr.write(warn)
else:
print affichage.OK
except:
print affichage.ERREUR
if self.debug:
import traceback
traceback.print_exc()
def reconfigure(self):
if hostname == "zbee":
self.delete_zbee()
elif hostname == "owl":
self.delete_directory(u"Suppression des fichiers index de dovecot",
"/var/dovecot-indexes/%s")
elif hostname == "zamok":
self.delete_directory(u"Suppression des fichiers d'impression",
"/var/spool/impression/%s")
class home:
debug = True
def __init__(self, args):
self.args = args
def reconfigure(self):
animation = affichage.Animation(texte=u"Création du home", nb_cycles=len(self.args), couleur=True, kikoo=True)
for args in self.args:
animation.new_step()
print('\n' + args)
try:
login, oldLogin, oldHome = args.split(",")
if login:
res = ldap.search(u"uid=%s" % (login,))[0]
if res.ldap_name == u'adherent':
adh = res
gid = config.gid
elif res['club']:
adh = res
gid = config.club_gid
home = unicode(adh['homeDirectory'][0])
uid = int(adh['uidNumber'][0])
if adh['mailExt'] != []:
mail_redirect = unicode(adh['mailExt'][0])
if oldHome and hostname == "zbee":
home_service = del_user(["%s,%s" % (oldLogin, oldHome)])
home_service.delete_zbee()
homesplit = home.split("/")
symlink = "/home-adh/%s" % (homesplit[-1],)
### Home
if not os.path.exists(home):
# Le home n'existe pas
os.mkdir(home, 0755)
os.chown(home, int(uid), gid)
if homesplit[-2] != "club":
if os.path.exists(symlink) and os.path.islink(symlink):
os.unlink(symlink)
elif os.path.exists(symlink):
raise OSError("Impossible de créer le lien %s : un fichier ou un dossier existe déjà." % (symlink,))
os.symlink(home, symlink)
elif os.path.isdir(home):
# Il y un répertoire existant
# Bon UID ?
stat = os.stat(home)
if stat[4] != int(uid) or stat[5] != gid:
# Le home n'est pas pas à la bonne personne
raise OSError('home existant')
if homesplit[-2] != "club":
if os.path.exists(symlink) and os.path.islink(symlink):
os.unlink(symlink)
elif os.path.exists(symlink):
raise OSError("Impossible de créer le lien %s : un fichier ou un dossier existe déjà." % (symlink,))
os.symlink(home, symlink)
### Quota
status, output = commands.getstatusoutput('/usr/sbin/setquota -u %s %s %s %s %s -a' % (uid, config.quota_soft, config.quota_hard, config.fquota_soft, config.fquota_hard) )
if status:
print affichage.WARNING
if self.debug:
sys.stderr.write(output+'\n')
else:
print affichage.OK
### Mail
if not os.path.exists(home + '/Mail'):
os.mkdir(home + '/Mail', 0700)
os.chown(home + '/Mail', int(uid), gid)
if not os.path.exists('/home-adh/mail/' + login):
os.mkdir('/home-adh/mail/' + login, 0700)
os.chown('/home-adh/mail/' + login, int(uid), 8)
### Redirection
if mail_redirect:
write_in_forward = True
# On vérifie s'il y a déjà un .forward
if os.path.exists(os.path.join(home, ".forward")):
write_in_forward = False
if write_in_forward:
with open(os.path.join(home, '.forward'), 'w') as forward_file:
forward_file.write(mail_redirect + '\n')
os.chown(home + '/.forward', int(uid), gid)
os.chmod(home + '/.forward', 0600)
### Owncloud dans le home
if not os.path.exists(home + '/OwnCloud'):
os.mkdir(home + '/OwnCloud')
os.chown(home + '/OwnCloud', int(uid), grp.getgrnam('www-data').gr_gid)
os.chmod(home + '/OwnCloud', 0770)
except:
print affichage.ERREUR
if self.debug:
import traceback
traceback.print_exc()
class mail_bienvenue:
debug = True
def __init__(self, mails):
self.mails = mails
def reconfigure(self):
animation = affichage.Animation(texte=u"Mail de bienvenue", nb_cycles=len(self.mails), couleur=True, kikoo=True)
for mail in self.mails:
animation.new_step()
print('\n' + mail)
try:
From = "respbats@crans.org"
To = mail
if '@crans.org' in To:
if not os.path.exists("/home/" + To.replace('@crans.org','')):
print affichage.ERREUR
continue
conn=smtplib.SMTP('localhost')
#conn.sendmail(From, To, mail_module.generate('bienvenue', { 'From': From, 'To': To, 'lang_info': 'English version below' }).as_string())
conn.quit()
print affichage.OK
except Exception, c:
print affichage.ERREUR
if True: #self.debug:
import traceback
traceback.print_exc()
class mail_ajout_droits:
debug = True
def __init__(self, args):
self.args = args
def reconfigure(self):
animation = affichage.Animation(texte=u"Mail ajout de droits", nb_cycles=len(self.args), couleur=True, kikoo=True)
for arg in self.args:
login = arg.split(":")[0]
Droit = arg.split(":")[1]
animation.new_step()
print('\n' + login)
try:
From = "root@crans.org"
To = login
if To.find('@') == -1: To += '@crans.org'
print Droit +"\n"
if Droit in config_mails.pages_infos_droits:
print "envoi du mail"
Page = config_mails.pages_infos_droits[Droit.encode('utf-8')]
conn=smtplib.SMTP('localhost')
conn.sendmail(From, To, config_mails.txt_ajout_droits.encode('utf-8') % { 'From': From, 'To': To , 'Droit': Droit, 'Page': Page})
conn.quit()
print affichage.OK
else:
print("Pas de mail pour ce droit")
except Exception, c:
print affichage.ERREUR
if self.debug:
import traceback
traceback.print_exc()
Supports Markdown
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