vieux: ajoute_chambre,arp
This commit is contained in:
parent
29d7bc0fb6
commit
e8700aa131
2 changed files with 0 additions and 0 deletions
194
archive/gestion/ajoute_chambre.py
Executable file
194
archive/gestion/ajoute_chambre.py
Executable file
|
@ -0,0 +1,194 @@
|
|||
#! /usr/bin/env python
|
||||
# -*- coding: utf-8 -*-
|
||||
#
|
||||
# $Id: ajoute_chambre.py,v 1.2 2007-02-24 01:08:45 dimino Exp $
|
||||
#
|
||||
# ajoute_chambre.py
|
||||
# -----------------
|
||||
#
|
||||
# Copyright (C) February 23, 2007 Jeremie Dimino
|
||||
# Email: <dimino@crans.org>
|
||||
#
|
||||
# This file is free software; you can redistribute it and/or modify
|
||||
# it under the terms of the GNU General Public License as published by
|
||||
# the Free Software Foundation; either version 2 of the License, or
|
||||
# (at your option) any later version.
|
||||
#
|
||||
# This file is distributed in the hope that it will be useful,
|
||||
# but WITHOUT ANY WARRANTY; without even the implied warranty of
|
||||
# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
|
||||
# GNU General Public License for more details.
|
||||
#
|
||||
# You should have received a copy of the GNU General Public License
|
||||
# along with this program; if not, write to the Free Software
|
||||
# Foundation, Inc., 59 Temple Street #330, Boston, MA 02111-1307, USA.
|
||||
#
|
||||
#
|
||||
# Description:
|
||||
# Ajoute une chambre sur une prise libre (fait pour le batiment g à la base)
|
||||
#
|
||||
|
||||
import sys, os
|
||||
|
||||
sys.path.append('/usr/scripts/gestion')
|
||||
|
||||
raise EnvironmentError("Ce script est *vieux*")
|
||||
|
||||
from annuaires import chbre_prises, reverse, bat_switchs
|
||||
from affich_tools import cprint
|
||||
|
||||
# C'est juste pour le déboggage
|
||||
__fichier_annuaire = "/usr/scripts/gestion/annuaires.py"
|
||||
|
||||
|
||||
def assigne_chambre(prise, chbre):
|
||||
""" Assigne une chambre à une prise.
|
||||
|
||||
prise doit être de la forme bnnn[g/d], ou nnn[g/d], dans ce dernier cas le bâtiment est le g.
|
||||
"""
|
||||
|
||||
if len(chbre) != 3 or not chbre.isdigit():
|
||||
return 'argument_invalide'
|
||||
|
||||
bat = prise[0]
|
||||
|
||||
if bat.isdigit():
|
||||
bat = 'g'
|
||||
else:
|
||||
bat = bat.lower()
|
||||
|
||||
if bat not in bat_switchs:
|
||||
return 'batiment_inconnu'
|
||||
|
||||
prise = prise[1:]
|
||||
|
||||
if chbre_prises(bat).get(chbre):
|
||||
return 'chambre_deja_cablee'
|
||||
|
||||
# dico = reverse(bat)
|
||||
# chambre = dico.get(prise)
|
||||
# if not chambre:
|
||||
# prise += '-'
|
||||
# chambre = dico.get(prise)
|
||||
|
||||
# if not chambre:
|
||||
# return 'prise_inconnue'
|
||||
|
||||
# if chambre != 'XXX':
|
||||
# return 'prise_utilisee'
|
||||
|
||||
# Ajout effectif de la chambre sur la prise donnée
|
||||
|
||||
annuaire = open(__fichier_annuaire, 'r')
|
||||
tampon = annuaire.read()
|
||||
annuaire.close()
|
||||
|
||||
# Du parsing chiant...
|
||||
index = tampon.find('\nchbre_prises')
|
||||
if index == -1 or tampon[index + 13] not in [ ' ', '=' ]:
|
||||
return 'fichier_annuaire_invalide'
|
||||
|
||||
index = tampon.find("'%s'" % (bat), index + 13)
|
||||
if index == -1:
|
||||
return 'fichier_annuaire_invalide'
|
||||
|
||||
index = tampon.find("'XXX':'%s'" % (prise), index + 3)
|
||||
if index == -1:
|
||||
prise += '-'
|
||||
index = tampon.find("'XXX':'%s'" % (prise), index + 3)
|
||||
if index == -1:
|
||||
return 'prise_introuvable'
|
||||
|
||||
annuaire = open(__fichier_annuaire, 'w')
|
||||
|
||||
annuaire.write(tampon[:index])
|
||||
annuaire.write("'%s':'%s'" % (chbre, prise))
|
||||
annuaire.write(tampon[(index+8+len(prise)):])
|
||||
|
||||
annuaire.close()
|
||||
|
||||
user = os.getenv('SUDO_USER')
|
||||
if not user:
|
||||
user = os.getenv('USER') or "inconnu"
|
||||
|
||||
# Vu que ça va être mis dans la ligne de commande éxécuter après,
|
||||
# autant être parano.
|
||||
for c in user:
|
||||
if not (c.isalnum or c in [ '-', '_' ]):
|
||||
user = "(uid=%d)" % (os.getuid())
|
||||
break
|
||||
|
||||
os.system('cd /usr/scripts/gestion && /usr/bin/cvs commit %s \
|
||||
-m "ajoute_chambre.py: chambre %s%s ajouté sur la prise %s%s par %s"' %
|
||||
(__fichier_annuaire, bat, chbre, bat, prise, user))
|
||||
|
||||
|
||||
def __usage(err=''):
|
||||
""" Message d'erreur """
|
||||
|
||||
if err : cprint(err, 'rouge')
|
||||
cprint(u"Tapez %s -h pour plus d'informations" % sys.argv[0].split('/')[-1].split('.')[0])
|
||||
sys.exit(2)
|
||||
|
||||
|
||||
def __aide():
|
||||
""" Aide """
|
||||
|
||||
cprint(u"""Usage: %s [OPTIONS] <prise> <chambre>
|
||||
Ajoute une chambre sur une prise qui n'était pas encore utilisé.
|
||||
|
||||
Options:
|
||||
-h, --help affiche cette aide
|
||||
|
||||
<prise> doit être de la forme bnnn ou nnn où:
|
||||
- B est le batiment (g si non spécifié)
|
||||
- nnn est le numéro de la prise
|
||||
|
||||
<chambre> doit être de la forme nnn
|
||||
|
||||
Rapporter toutes anomalies à <dimino@crans.org>.""" % sys.argv[0].split('/')[-1].split('.')[0])
|
||||
sys.exit(0)
|
||||
|
||||
|
||||
if __name__ == '__main__':
|
||||
|
||||
import getopt
|
||||
|
||||
try:
|
||||
options, arg = getopt.getopt(sys.argv[1:], 'h', [ 'help' ])
|
||||
except getopt.error, msg:
|
||||
__usage(unicode(msg))
|
||||
|
||||
for opt, val in options:
|
||||
if opt in [ '-h', '--help' ]:
|
||||
__aide()
|
||||
else:
|
||||
cprint(u'Option inconnue: %s' % opt, 'rouge')
|
||||
__usage()
|
||||
|
||||
if len(arg) != 2:
|
||||
__usage()
|
||||
|
||||
resultat = assigne_chambre(arg[0], arg[1])
|
||||
|
||||
if resultat == 'argument_invalide':
|
||||
__usage(u"Format de la chambre invalide")
|
||||
|
||||
elif resultat == 'chambre_deja_cablee':
|
||||
__usage(u"La chambre est déjà cablée")
|
||||
|
||||
elif resultat == 'batiment_inconnu':
|
||||
__usage(u"Le batiment n'existe pas")
|
||||
|
||||
elif resultat == 'prise_inconnue':
|
||||
__usage(u"La prise n'existe pas")
|
||||
|
||||
elif resultat == 'prise_utilisee':
|
||||
__usage(u"La prise est déjà utilisée")
|
||||
|
||||
elif resultat == 'prise_introuvable':
|
||||
cprint(u"""La prise n'a pas été trouvé dans l'annuaire.
|
||||
Vérifiez que vous avez bien mis le numéro de prise et de chambre.""")
|
||||
|
||||
elif resultat == 'fichier_annuaire_invalide':
|
||||
cprint(u"Le fichier d'annuaire n'est pas reconnu, envoyer un mail à dimino@crans.org")
|
97
archive/gestion/arp.py
Executable file
97
archive/gestion/arp.py
Executable file
|
@ -0,0 +1,97 @@
|
|||
#! /usr/bin/env python
|
||||
# -*- coding: utf-8 -*-
|
||||
|
||||
# Serveur SSL qui renvoie la MAC correspondant à une IP
|
||||
# Ce serveur est utilisé sur Nectaris par les bornes wifi pour faire
|
||||
# les requêtes ARP.
|
||||
|
||||
# Lancement : twistd -n -y arp.py --pidfile=/var/run/arp.pid
|
||||
# Pas de -n pour qu'il passe en fond
|
||||
|
||||
# On utilise twisted
|
||||
# http://twistedmatrix.com/documents/current/howto/tutorial/intro
|
||||
from twisted.internet import protocol, reactor, defer, utils
|
||||
from twisted.internet.ssl import ContextFactory
|
||||
from twisted.protocols import basic
|
||||
from twisted.application import internet, service
|
||||
|
||||
import sys
|
||||
sys.path.append('/usr/scripts/gestion')
|
||||
|
||||
# LDAP
|
||||
from ldap_crans import crans_ldap
|
||||
|
||||
# Divers
|
||||
from iptools import AddrInNet
|
||||
from OpenSSL import SSL
|
||||
import re
|
||||
|
||||
class ServerContextFactory(ContextFactory):
|
||||
|
||||
def getContext(self):
|
||||
"""Création d'un contexte SSL côté serveur."""
|
||||
ctx = SSL.Context(SSL.SSLv23_METHOD)
|
||||
ctx.use_certificate_file('/etc/ssl/certs/nectaris.pem')
|
||||
ctx.use_privatekey_file('/etc/ssl/private/nectaris.pem')
|
||||
return ctx
|
||||
|
||||
class ARPProtocol(basic.LineReceiver):
|
||||
"""Protocole de communication pour récupérer une adresse MAC.
|
||||
|
||||
Chaque lignee reçue contient une adresse IP et le serveur répond
|
||||
avec l'adresse MAC correspondante ou avec `unknown' si celle-ci
|
||||
est inconnue (ou non autorisée).
|
||||
"""
|
||||
def lineReceived(self, IP):
|
||||
self.factory.getMac(IP
|
||||
).addErrback(lambda _: "Internal error in server"
|
||||
).addCallback(lambda m:
|
||||
(self.answerMac(m)))
|
||||
|
||||
def answerMac(self, m):
|
||||
"""Renvoie au client la bonne adresse MAC.
|
||||
|
||||
`m' peut être None.
|
||||
"""
|
||||
if m:
|
||||
return self.transport.write(str(m) + "\r\n")
|
||||
else:
|
||||
return self.transport.write("unknown\r\n")
|
||||
|
||||
class ARPFactory(protocol.ServerFactory):
|
||||
"""Backend du serveur. Effectue la résolution IP/MAC."""
|
||||
protocol = ARPProtocol
|
||||
|
||||
def __init__(self, network='0.0.0.0/0'):
|
||||
self.ldap = crans_ldap()
|
||||
self.network = network
|
||||
|
||||
def getMac(self, IP):
|
||||
return defer.succeed(self._getMac(IP))
|
||||
|
||||
def _getMac(self, IP):
|
||||
"""Fonction réelle, synchrone, qui obtient l'adresse MAC."""
|
||||
try:
|
||||
if AddrInNet(IP, self.network):
|
||||
results = self.ldap.search('ip=%s' % IP)['machine']
|
||||
if results:
|
||||
# On a au moins un résultat, on retourne le premier
|
||||
return results[0].mac().strip()
|
||||
else:
|
||||
# On a rien
|
||||
return None
|
||||
else:
|
||||
# L'IP n'est pas autorisée
|
||||
return None
|
||||
except ValueError:
|
||||
# A priori, ce n'était pas une IP
|
||||
return None
|
||||
|
||||
# Corps du programme
|
||||
# On écoute sur le port 5243 et on ne répond qu'aux requêtes concernant le
|
||||
# sous-réseau wifi
|
||||
application = service.Application('arp')
|
||||
factory = ARPFactory('138.231.148.0/21')
|
||||
# Remplacer SSL par TCP pour ne pas utiliser SSL et virer ServerContextFactory
|
||||
internet.SSLServer(5243, factory,
|
||||
ServerContextFactory()).setServiceParent(service.IServiceCollection(application))
|
Loading…
Add table
Add a link
Reference in a new issue