root/wifi-ltsp/trunk/configura_hostapd.py @ 462
50 | jredrejo | #!/usr/bin/python
|
|
49 | elisa_apar | # -*- coding: utf-8 -*-
|
|
# Project: wifi-ltsp
|
|||
50 | jredrejo | # Module: configura_hostapd.py
|
|
49 | elisa_apar | # Purpose: genera un archivo hostapc.accept para dar acceso a internet a los alumnos.
|
|
# Language: Python 2.5
|
|||
# Date: 07-Feb-2011.
|
|||
# Ver: 07-Feb-2011.
|
|||
# Author: Isabel Aparicio Pérez
|
|||
# Copyright: 2011 - Isabel Aparicio Pérez <prog5pe@edu.juntaextremadura.net>
|
|||
#
|
|||
50 | jredrejo | # wifi-ltsp is free software: you can redistribute it and/or modify
|
|
49 | elisa_apar | # it under the terms of the GNU General Public License as published by
|
|
# the Free Software Foundation, either version 3 of the License, or
|
|||
# (at your option) any later version.
|
|||
# Script2 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
|
|||
50 | jredrejo | # along with wifi-ltsp. If not, see <http://www.gnu.org/licenses/>.
|
|
49 | elisa_apar | ||
""" Este programa genera el archivo hostapd.access necesario para que en el momento del logueo del
|
|||
profesor se de acceso a internet a los alumnos que tienen clase en esa hora con ese profesor. Para ello
|
|||
tenemos que recoger el dia de la semana y la hora actual que tiene el servidor de aula y con el dia actual
|
|||
buscar en el servidor nfs el fichero del dia de la semana que corresponde con el dia concreto. El fichero
|
|||
descargado del servidor nfs se almacena en el servidor de aula en la ruta /wifi con el nombre horario.txt.
|
|||
Tambien controlamos el usuario que esta logueado en ese preciso momento en el servidor. A partir del usuario
|
|||
logueado, de la hora del sistema y del fichero descargado del servidor nfs se genera el fichero hostapd.access
|
|||
con las mac de los alumnos correspondientes.
|
|||
Isabel Aparicio Pérez
|
|||
Consejería de Educacion.
|
|||
prog5pe@edu.juntaextremadura.net
|
|||
"""
|
|||
import time
|
|||
import urllib
|
|||
import os
|
|||
import sys
|
|||
51 | jredrejo | from parsehostapd import parsehostapd
|
|
import socket
|
|||
import logging
|
|||
55 | jredrejo | import subprocess
|
|
56 | jredrejo | from shutil import copy
|
|
49 | elisa_apar | ||
51 | jredrejo | LOG_FILENAME= "/var/log/configura-hostapd.log"
|
|
49 | elisa_apar | fecha=[]
|
|
ip=[]
|
|||
dia_semana={"Mon":"lunes.txt","Tue":"martes.txt","Wed":"miercoles.txt","Thu":"jueves.txt","Fri":"viernes.txt"}
|
|||
def dia_actual():
|
|||
58 | jredrejo | """con esta funcion se obtiene la fecha actual que tiene el servidor de aula"""
|
|
hoy = time.asctime()
|
|||
return hoy
|
|||
49 | elisa_apar | ||
58 | jredrejo | def fichero_semana(fecha1):
|
|
"""Con esta funcion se obtiene la parte de la fecha actual que corresponde con el dia de la semana"""
|
|||
dia= fecha1[0:3]
|
|||
if dia not in ["Mon","Tue","Wed","Thu","Fri"]:
|
|||
51 | jredrejo | logging.getLogger().error("El formato de la fecha del sistema no es el esperado")
|
|
return ""
|
|||
58 | jredrejo | else:
|
|
fichero=dia_semana[dia]
|
|||
return fichero
|
|||
49 | elisa_apar | ||
58 | jredrejo | def hora_actual(fecha1):
|
|
"""Con esta funcion se obtiene la hora actual del sistema sin los : de forma que la 08:45 se representaran
|
|||
como la 0845"""
|
|||
hora= fecha1[11:13]+fecha1[14:16]
|
|||
h=int(hora)
|
|||
if (h<int(0000) or h>int(2500)):
|
|||
51 | jredrejo | logging.getLogger().error("El formato de la hora del sistema no es el esperado")
|
|
return "9999"
|
|||
58 | jredrejo | else:
|
|
return hora
|
|||
49 | elisa_apar | ||
def descargar_fichero(fichero):
|
|||
58 | jredrejo | """funcion que se encarga de descargar el fichero del dia de la semana correspondiente al dia actual del
|
|
servidor nfs y colocarlo en la ubicacion correcta en el servidor de terminales con el nombre de horario.txt"""
|
|||
archivo="http://servidor/wifi/"+fichero
|
|||
print archivo
|
|||
destino="/wifi/horario.txt"
|
|||
destino2="/wifi"
|
|||
if not os.path.exists(destino2):
|
|||
51 | jredrejo | logging.getLogger().debug("La ruta destino no existe y hay que crearla")
|
|
58 | jredrejo | try:
|
|
os.makedirs(destino2)
|
|||
except OSError:
|
|||
51 | jredrejo | logging.getLogger().error("Hay algun error a la hora de crear el directorio /wifi en el servidor de aula")
|
|
try:
|
|||
58 | jredrejo | urllib.urlretrieve(archivo, destino)
|
|
51 | jredrejo | except:
|
|
logging.getLogger().error("No hay acceso al servidor para encontrar el fichero de horario")
|
|||
return ""
|
|||
58 | jredrejo | return destino
|
|
49 | elisa_apar | ||
def devuelve_usuario():
|
|||
58 | jredrejo | """con esta funcion recogemos el usuario que esta logueado en ese momento en el ordenador, seguira intentandolo
|
|
hasta que se loguee antes"""
|
|||
resultado = sys.argv[1]
|
|||
return resultado
|
|||
49 | elisa_apar | ||
def crea_hostapd(destino,resultado,hora):
|
|||
58 | jredrejo | """con esta funcion generamos el fichero hostapd con las mac correspondientes a los alumnos a los que se
|
|
les va a dar acceso a internet y lo colocamos en la ruta correcta."""
|
|||
if not os.path.exists(destino):
|
|||
51 | jredrejo | logging.getLogger().error("Hay un error el el fichero horario.txt en el servidor de aula")
|
|
return ""
|
|||
58 | jredrejo | else:
|
|
66 | jredrejo | try:
|
|
copy("/etc/hostapd/hostapd.accept","/etc/hostapd/hostapd.accept.bak")
|
|||
except:
|
|||
pass
|
|||
58 | jredrejo | f=open(destino,"r")
|
|
if not os.path.exists("/etc/hostapd"):
|
|||
try:
|
|||
os.makedirs("/etc/hostapd")
|
|||
except IOError:
|
|||
51 | jredrejo | logging.getLogger().error("Ha habido algun error a la hora de crear el directorio /etc/hostapd")
|
|
58 | jredrejo | return ""
|
|
if not os.access("/etc/hostapd", os.W_OK):
|
|||
51 | jredrejo | logging.getLogger().error("No tiene permisos de escritura sobre el directorio /etc/hostapd")
|
|
return ""
|
|||
58 | jredrejo | else:
|
|
g=open("/etc/hostapd/hostapd.accept","w")
|
|||
56 | jredrejo | ||
esta_en_horario=False
|
|||
58 | jredrejo | while True:
|
|
dato=f.readline()
|
|||
if not dato:
|
|||
break
|
|||
else:
|
|||
lin=dato.split("|")
|
|||
if lin[0]==resultado:
|
|||
if hora>lin[2] and hora<lin[3]:
|
|||
g.write(lin[1])
|
|||
g.write("\n")
|
|||
56 | jredrejo | esta_en_horario=True
|
|
58 | jredrejo | f.close()
|
|
g.close()
|
|||
56 | jredrejo | #si un profesor de guardia hace login, se autorizan automáticamente los
|
|
#alumnos que hubiera autorizado el profesor anterior:
|
|||
if not esta_en_horario:
|
|||
66 | jredrejo | try:
|
|
copy("/etc/hostapd/hostapd.accept.bak","/etc/hostapd/hostapd.accept")
|
|||
except:
|
|||
pass
|
|||
58 | jredrejo | ||
56 | jredrejo | return g
|
|
49 | elisa_apar | ||
58 | jredrejo | def inicia_hostapd():
|
|
68 | jredrejo | subprocess.Popen(["ifconfig","wlan0","up"])
|
|
subprocess.Popen(["invoke-rc.d","hostapd","restart"])
|
|||
49 | elisa_apar | ||
55 | jredrejo | def userIsTeacher(user_name):
|
|
p1 = subprocess.Popen(["id", "-Gn",user_name], stdout=subprocess.PIPE)
|
|||
p2 = subprocess.Popen(["grep", 'teachers'], stdin=p1.stdout, stdout=subprocess.PIPE)
|
|||
output = p2.communicate()[0]
|
|||
return (output != '')
|
|||
49 | elisa_apar | ||
if __name__ == '__main__':
|
|||
51 | jredrejo | logging.basicConfig(level=logging.DEBUG,
|
|
format='%(asctime)s %(levelname)-8s %(message)s',
|
|||
datefmt='%a, %d %b %Y %H:%M:%S',
|
|||
filename=LOG_FILENAME)
|
|||
270 | jredrejo | ||
if len(sys.argv)>1:
|
|||
dia_hoy=""
|
|||
hora=""
|
|||
user=""
|
|||
fich=""
|
|||
hos=""
|
|||
res=""
|
|||
f=""
|
|||
51 | jredrejo | ||
270 | jredrejo | dia_hoy=dia_actual()
|
|
hora=hora_actual(dia_hoy)
|
|||
fich=fichero_semana(dia_hoy)
|
|||
f=descargar_fichero(fich)
|
|||
if f!="":
|
|||
user=devuelve_usuario()
|
|||
if userIsTeacher(user):
|
|||
hos=crea_hostapd(f,user,hora)
|
|||
else: #login de un alumno
|
|||
subprocess.Popen(["invoke-rc.d","hostapd","stop"]).wait()
|
|||
sys.exit(0)
|
|||
if hos=="":
|
|||
logging.getLogger().error("Error al generar las mac autorizadas")
|
|||
51 | jredrejo | ||
#Aquí metemos ahora la reconfiguración de hostapd.conf con la parte
|
|||
#hecha por Francisco Mora
|
|||
hostapdconf="/etc/hostapd/hostapd.conf"
|
|||
58 | jredrejo | ||
51 | jredrejo | canaloptimo = parsehostapd.selectbestchannel(True)
|
|
ssid = socket.gethostname()
|
|||
pos = ssid.find(".")
|
|||
if pos > -1:
|
|||
ssid = ssid[:pos]
|
|||
pos = ssid.find("-pro")
|
|||
if pos > -1:
|
|||
ssid = ssid[:pos]
|
|||
try:
|
|||
#Abre el archivo para lectura de datos
|
|||
archivoLectura = open(hostapdconf,"r")
|
|||
lineas = archivoLectura.readlines()
|
|||
archivoLectura.close()
|
|||
except (RuntimeError, TypeError, NameError, IOError):
|
|||
logging.getLogger().error("Error en la ubicacion o nombre del archivo")
|
|||
sys.exit(0) #salimos con 0 para no fastidiar gdm
|
|||
#Modifica la cadena del channel y ssid
|
|||
encontradoChannel = False
|
|||
encontradoSsid = False
|
|||
for numlinea in range(0, len(lineas)):
|
|||
linea = lineas[numlinea]
|
|||
66 | jredrejo | #comprobamos si estamos en channel o en ssid
|
|
if linea[:7] == "channel":
|
|||
encontradoChannel = True
|
|||
lineas[numlinea] = "channel="+str(canaloptimo)+"\n"
|
|||
if linea[:4] == "ssid":
|
|||
encontradoSsid = True
|
|||
lineas[numlinea] = "ssid="+ssid+"\n"
|
|||
51 | jredrejo | if not encontradoChannel:
|
|
lineas.append("channel="+str(canaloptimo)+"\n")
|
|||
if not encontradoSsid:
|
|||
lineas.append("ssid="+ssid+"\n")
|
|||
58 | jredrejo | ||
51 | jredrejo | #Abre el archivo para escritura de datos
|
|
archivoEscritura = open(hostapdconf,"w")
|
|||
archivoEscritura.writelines(lineas)
|
|||
archivoEscritura.close()
|
|||
58 | jredrejo | logging.getLogger().debug('Establecido el canal %s con ESSID %s' % (canaloptimo,ssid))
|
|
51 | jredrejo | ||
58 | jredrejo | res=inicia_hostapd()
|