scripts/gestion/gen_confs/generate.py
Valentin Samir c71900a5ba [firewall_new,generate,ldap_crans] Prise en compte des déco chambre invalide et carte étudiant
Ignore-this: 16f86d33fe0e98057fd9533abc25aa88
TOujours effectué sur squid, elles était alors simplement ignoré
puisque la connection au web est maintemant directe.
On ajoute donc des blacklistes soft "virtuelle" pour carte et
chambre invalide dans ldap_crans, ce qui a pour effet de faire
que le pare-feu redirige vers sable (et squid) les machines consernées.
On dit à générate de recharger les blackliste du pare-feu lorsque l'on coche
une carte étudiant dans gest_crans ou quand le status chambre invalide change.
btw, on reporte aussi les modifications de crans_ldap dans lc_ldap.

darcs-hash:20121104020449-3a55a-78f73e677e75e8eaa087fd9bd6f8c1aec2b593ea.gz
2012-11-04 03:04:49 +01:00

456 lines
14 KiB
Python

#! /usr/bin/env python
# -*- coding: iso-8859-15 -*-
# Copyright (C) Frédéric Pauget
# Licence : GPLv2
"""Ce script permet de lancer la reconfiguration des divers services
Usage: %(prog)s options
Les options possibles sont :
\t%(options)s
Les options avec = doivent être suivies d'un argument. Plusieurs
arguments peuvent être founis pour une même option, les séparer par &
"""
import sys, signal, os, getopt
sys.path.append('/usr/scripts/gestion')
from ldap_crans import crans_ldap, hostname
from lock import *
from affich_tools import anim, cprint, OK
from time import localtime, strftime, time, sleep
import config
import midtools
from inspect import getargspec
from syslog import *
import platform
openlog("generate")
# On vérifie que l'on est root
if os.getuid() != 0:
sys.stderr.write("Il faut être root\n")
sys.exit(1)
signal.signal(signal.SIGINT, signal.SIG_IGN) # Pas de Ctrl-C
db = crans_ldap()
make_lock('auto_generate', 'Big lock', nowait=1)
class base_reconfigure:
__service_develop = {
'macip': [ 'redisdead-macip', 'zamok-macip', 'sable-macip', 'komaz-macip', 'gordon-macip',
'sable-blacklist_check' ],
# 'droits': [ 'rouge-droits', 'ragnarok-droits' ],
'blacklist_upload': [ 'sable-blacklist_upload', 'komaz-blacklist', 'zamok-blacklist' ],
'blacklist_p2p': [ 'sable-blacklist_p2p', 'komaz-blacklist', 'zamok-blacklist' ],
'blacklist_autodisc_upload': [ 'sable-blacklist_autodisc_upload', 'komaz-blacklist', 'zamok-blacklist'],
'blacklist_autodisc_p2p': [ 'sable-blacklist_autodisc_p2p', 'komaz-blacklist', 'zamok-blacklist'],
'blacklist_bloq': [ 'komaz-blacklist', 'sable-blacklist_bloq', 'zamok-blacklist', 'dns' ],
'del_user': [ 'daath-del_user', 'owl-del_user', 'zamok-del_user' ]
}
def __init__(self, to_do=None):
if not to_do:
if debug:
print 'Lecture des services à redémarrer dans la base LDAP...'
auto = True
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
db.services_to_restart('-' + serv.nom)
else:
for t in serv.start:
if time() > t:
to_do[serv.nom] = serv.args
break
else:
auto = False
if debug:
print 'Services à redémarrer imposés (non lecture de la base LDAP)'
for serv, args in to_do.items():
# Au cas où le service porte sur plusieurs machines
service = serv.replace('%s-' % hostname, '')
if hasattr(self, service):
# Le service est à reconfigurer sur cette machine
db.services_to_restart('-%s' % serv)
try:
m = getattr(self, service)
if len(getargspec(m)[0]) > 1:
m(args)
else:
m()
except:
if auto:
db.services_to_restart(serv, args)
sys.stderr.write('%s :' % serv)
import traceback
traceback.print_exc()
else:
# Le service n'existe pas
if debug:
print "Le service %s n'est pas disponible sur %s" % (service, hostname)
if debug:
reste = db.services_to_restart()
if reste:
print "Reste à faire :"
for s in reste:
try:
print '\t%s' % s
except UnicodeDecodeError:
print '\t%s: non imprimable' % s.nom
else:
print "Plus rien à faire"
def _machines(self):
""" Retourne les machines de la base étant 'à jour' """
return db.all_machines(graphic=True)
def _do(self, service, machines=None):
# Reconfiguration des services
service.debug = debug
if machines:
service.machines = machines
service.reconfigure()
def macip(self, ips):
if platform.dist()[1] >= '6':
import firewall_new
firewall = firewall_new
else:
import firewall
cprint(u"Mise a jour correspondance MAC-IP", 'gras')
eval("firewall.firewall_%s()" % hostname).mac_ip_maj(ips)
class redisdead(base_reconfigure):
def droits(self):
from gen_confs.droits import droits_ldap
self._do(droits_ldap())
def desabonner_ml(self, args):
from gen_confs.droits import desabonner_ml
d = desabonner_ml()
d.args = args
self._do(d)
def ML_ens(self, mails):
from adherents import ML_ens
self._do(ML_ens(mails))
def mail_ajout_droits(self, args):
from adherents import mail_ajout_droits
self._do(mail_ajout_droits(args))
def mail_modif(self, trucs):
"""
trucs est une liste de recherches à effectuer dans la base
l'affichage des résultats formera le corps du mail
"""
from supervison import mail
self._do(mail(trucs))
def mail_solde(self, modifs):
from gen_confs.supervison import mail_solde
self._do(mail_solde(modifs))
class owl(base_reconfigure):
def del_user(self, args):
# Suppression des fichiers index de dovecot
from adherents import del_user
self._do(del_user(args))
class pgsql(base_reconfigure):
def surveillance_exemptions(self):
from gen_confs.surveillance import exemptions
self._do(exemptions())
def surveillance_machines(self):
from gen_confs.surveillance import machines
self._do(machines(), self._machines())
class zamok(base_reconfigure):
def del_user(self, args):
# Suppression des fichies d'impression
from adherents import del_user
self._do(del_user(args))
def blacklist(self):
from firewall import firewall_zamok
firewall_zamok().blacklist()
class daath(base_reconfigure):
def home(self, args):
from adherents import home
self._do(home(args))
def del_user(self, args):
# Suppression du home et des mails
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))
class komaz(base_reconfigure):
def __fw(self):
if not hasattr(self, '__real_fw'):
from firewall_new import firewall_komaz
self.__real_fw = firewall_komaz()
return self.__real_fw
# Mimétisme de ma part -- xhub
def __fw6(self):
if not hasattr(self, '__real_fw6'):
from firewall6 import Update
self.__real_fw6 = Update()
return self.__real_fw6
def macip(self, ips):
cprint(u"Mise a jour correspondance MAC-IP", 'gras')
self.__fw().mac_ip_maj(ips)
self.__fw6().macs([], 6)
def ports(self, ips):
self.__fw().port_maj(ips)
#self.__fw6().ports(map(self.midt.from_ipv4, ips), 6)
def blacklist(self):
self.__fw().blacklist()
self.__fw6().blacklist(6)
def bl_carte_etudiant(self):
self.blacklist()
def bl_chbre_invalide(self):
self.blacklist()
def classify(self, ips):
self.__fw().classes_p2p_maj(ips)
class dyson(base_reconfigure):
def autostatus(self):
from autostatus import autostatus
self._do(autostatus())
def dhcp(self):
from gen_confs.dhcpd_new import dhcp
self._do(dhcp(), self._machines())
class dhcp(base_reconfigure):
def dhcp(self):
from gen_confs.dhcpd_new import dhcp
self._do(dhcp(), self._machines())
class sable(base_reconfigure):
def dhcp(self):
from gen_confs.dhcpd_new import dhcp
self._do(dhcp(), self._machines())
def dns(self):
from gen_confs.bind import dns
self._do(dns(), self._machines())
def blacklist_check(self, ips):
from gen_confs.squid import squid_check
self._do(squid_check(ips))
def bl_carte_etudiant(self):
from gen_confs.squid import squid_carte
self._do(squid_carte())
def bl_chbre_invalide(self):
from gen_confs.squid import squid_chbre
self._do(squid_chbre())
def blacklist_mail_invalide(self):
from gen_confs.squid import squid_mail
self._do(squid_mail())
def blacklist_virus(self):
from gen_confs.squid import squid_virus
self._do(squid_virus())
def blacklist_warez(self):
from gen_confs.squid import squid_warez
self._do(squid_warez())
def blacklist_upload(self):
from gen_confs.squid import squid_upload
self._do(squid_upload())
def blacklist_p2p(self):
from gen_confs.squid import squid_p2p
self._do(squid_p2p())
def blacklist_autodisc_virus(self):
from gen_confs.squid import squid_autodisc_virus
self._do(squid_autodisc_virus())
def blacklist_autodisc_upload(self):
from gen_confs.squid import squid_autodisc_upload
self._do(squid_autodisc_upload())
def blacklist_autodisc_p2p(self):
from gen_confs.squid import squid_autodisc_p2p
self._do(squid_autodisc_p2p())
def blacklist_bloq(self):
from gen_confs.squid import squid_bloq
self._do(squid_bloq())
def macip(self, ips):
from firewall_new import firewall_sable
firewall_sable().mac_ip_maj(ips)
class ovh(base_reconfigure):
def dns(self):
from gen_confs.bind import dns
self._do(dns(), self._machines())
class charybde(base_reconfigure):
def dns(self):
from gen_confs.bind import dns
self._do(dns(), self._machines())
class ragnarok(base_reconfigure):
__restart_wifi_update = False
def macip(self):
# Surcharge car rien à faire ici
pass
def conf_wifi_ng(self):
from gen_confs.wifi_ng import conf_wifi_ng
bornes = None
if os.getenv("BORNE"):
bornes = os.getenv("BORNE").split(",")
self._do(conf_wifi_ng(bornes))
def dhcp(self):
from gen_confs.dhcpd import dhcp
self._do(dhcp(), self._machines())
def droits(self):
from gen_confs.droits import droits_openbsd
self._do(droits_openbsd())
class gordon(base_reconfigure) :
def dhcp(self):
from gen_confs.dhcpd_new import dhcp
self._do(dhcp(), self._machines())
class titanic(base_reconfigure):
def dhcp(self):
from gen_confs.dhcpd_new import dhcp
self._do(dhcp(), self._machines())
signal.signal(signal.SIGINT, signal.SIG_DFL) # Comportement normal de Ctrl-C
remove_lock('auto_generate')
if __name__ == '__main__':
openlog('generate', LOG_PID)
for x in db.services_to_restart():
try:
syslog(str(x))
except UnicodeDecodeError:
syslog("%s: non imprimable" % x.nom)
classe = eval(hostname)
args_autorises = ['quiet', 'remove=', 'add=', 'list', 'help', 'reconnect']
# Ajout aussi des arguments spécifiques à la machine
for nom in dir(classe):
if nom[0] != '_':
if len(getargspec(getattr(classe, nom))[0]) > 1:
nom += '='
args_autorises.append(nom)
##### Options fournies ?
try:
if len(sys.argv) > 1:
options, arg = getopt.getopt(sys.argv[1:], 'h', args_autorises)
else:
options, arg = ([], '')
except getopt.error, msg:
sys.stderr.write('%s\n' % msg)
sys.exit(255)
debug = 1 # défaut
to_do = {}
for opt, val in options:
if opt == '--quiet':
debug = 0
elif opt == '--remove':
for serv in val.split('&'):
print 'Supression de %s' % serv
db.services_to_restart('--%s' % serv)
sys.exit(0)
elif opt == '--list':
print 'Services à redémarrer :'
for s in db.services_to_restart():
try:
print '\t%s' % s
except UnicodeDecodeError:
print '\t%s: non imprimable' % s.nom
sys.exit(0)
elif opt == '--reconnect':
# Personnes à reconnecter
print 'Recherche des personnes en fin de sanction...'
c = db.search('blacklist=*')
services = []
hier = time() - 24*3600
for a_reco in c['adherent'] + c['machine'] + c['club']:
for bl in a_reco.blacklist():
fin, sanction = bl.split('$')[1:3]
if fin > hier and sanction not in services:
services.append(sanction)
for s in services:
print "Ajout de blacklist_%s pour reconfiguration" % s
db.services_to_restart('blacklist_%s' % s)
sys.exit(0)
elif opt == '--add':
# Ajout d'un item dans les services à redémarrer
for serv in val.split('&'):
if serv.find(',') != -1:
serv, arg = serv.split(',', 1)
arg = arg.split(',')
else:
arg = []
print 'Ajout de %s (%s)' % (serv, arg)
db.services_to_restart(serv, arg)
sys.exit(0)
elif opt == '-h' or opt == '--help':
print __doc__ % { 'prog': sys.argv[0].split('/')[-1],
'options': '--' + '\n\t--'.join(args_autorises) }
sys.exit(0)
elif len(opt) > 2 and opt[:2] == '--':
to_do[opt[2:]] = val.split('&')
# On fait ce qu'il y a à faire
classe(to_do)