Proyecto

General

Perfil

« Anterior | Siguiente » 

Revisión 489

Proyecto movido

Ver diferencias:

controlies/scripts/employeenumber.py
##############################################################################
# -*- coding: utf-8 -*-
# Project: ControlIES
# Module: employeenumber.py
# Purpose: Añade el atributo employeenumber a los usuarios que no lo tienen
# Language: Python 2.5
# Date: 25-Mar-2011.
# Ver: 25-Mar-2011.
# Author: Manuel Mora Gordillo
# Copyright: 2011 - Manuel Mora Gordillo <manuito @no-spam@ gmail.com>
#
# ControlIES 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 3 of the License, or
# (at your option) any later version.
# ControlIES 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 ControlIES. If not, see <http://www.gnu.org/licenses/>.
#
##############################################################################
import ldap
#Aqui el password de tu ldap
passwd = ""
connection = ldap.open("ldap")
connection.simple_bind_s("cn=admin,ou=People,dc=instituto,dc=extremadura,dc=es",passwd)
ldap_result = connection.search("ou=People,dc=instituto,dc=extremadura,dc=es", ldap.SCOPE_SUBTREE, "uid=*", ["employeeNumber","uid","cn","sn","uidNumber","gidNumber","homeDirectory","jpegPhoto","userpassword"])
result_set = []
while 1:
result_type, result_data = connection.result(ldap_result, 0)
if (result_data == []):
break
else:
if result_type == ldap.RES_SEARCH_ENTRY:
result_set.append(result_data)
for p in result_set:
try:
employeeNumber = p[0][1]['employeeNumber']
except:
print p[0][1]['uid'][0]+" - no tiene employeeNumber"
try:
jpeg = p[0][1]['jpegPhoto'][0]
except:
jpeg = ""
attr = [
('objectclass', ['top','posixAccount','shadowAccount','person','inetOrgPerson']),
('uid', [p[0][1]['uid'][0]]),
('cn', [p[0][1]['cn'][0]] ),
('employeeNumber', [' '] ),
('sn', [p[0][1]['sn'][0]] ),
('uidnumber', [p[0][1]['uidNumber'][0]] ),
('gidnumber', [p[0][1]['gidNumber'][0]] ),
('loginshell', ['/bin/bash'] ),
('homeDirectory', [p[0][1]['homeDirectory'][0]] ),
('jpegPhoto', [jpeg] ),
('userpassword', [p[0][1]['userPassword'][0]])
]
connection.delete_s("uid="+p[0][1]['uid'][0]+",ou=People,dc=instituto,dc=extremadura,dc=es")
connection.add_s("uid="+p[0][1]['uid'][0]+",ou=People,dc=instituto,dc=extremadura,dc=es", attr)
controlies/branches/twisted/MainLoop.py
##############################################################################
# -*- coding: utf-8 -*-
# Project: ControlIES
# Module: MainLoop.py
# Purpose: ControlIES web response
# Language: Python 2.5
# Date: 7-Feb-2011.
# Ver: 7-Feb-2011.
# Author: Manuel Mora Gordillo
# Copyright: 2011 - Manuel Mora Gordillo <manuito @no-spam@ gmail.com>
#
# ControlIES 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 3 of the License, or
# (at your option) any later version.
# ControlIES 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 ControlIES. If not, see <http://www.gnu.org/licenses/>.
#
##############################################################################
from twisted.web import server,resource,static
import twisted
import os
import simplejson as json
from Plugins.LdapConnection import LdapConnection, ILdapConnection
from Utils import LdapUtils
class ControlIESProtocol(resource.Resource):
isLeaf = True # This is a resource end point.
def __init__ (self):
resource.Resource.__init__(self)
self.PageDir=""
def render_GET(self, request):
session = request.getSession()
l = ILdapConnection(session)
connection = l.connect()
pagename=request.path[1:].lower()
if pagename=='':
request.path='/index.html'
pagename='index.html'
if pagename=='main.html' and connection==False:
request.path='/index.html'
pagename='index.html'
requestedfile = os.path.join(self.PageDir,request.path[1:])
if not os.path.isfile(requestedfile):
# Didn't find it? Return an error.
request.setResponseCode(404)
return"""
<html><head><title>404 - No Such Resource</title></head>
<body><h1>No Such Resource</h1>
<p>File not found: %s - No such file.</p></body></html>
""" % requestedfile
# Look for the requested file.
f=static.File(requestedfile)
if f.type is None:
f.type, f.encoding = static.getTypeAndEncoding(requestedfile,
f.contentTypes,
f.contentEncodings,
f.defaultType)
if f.type:
ctype=f.type.split(":")[0]
# Send the headers.
request.setHeader('content-type', ctype)
if f.encoding:
request.setHeader('content-encoding', f.encoding)
# Send the page.
if twisted.version.major >= 9:
static.NoRangeStaticProducer(request,f.openForReading()).start()
else:
static.FileTransfer(f.openForReading(), f.getFileSize(), request)
return server.NOT_DONE_YET
def render_POST(self, request):
command = request.path[1:]
session = request.getSession()
l = ILdapConnection(session)
print command
if command == "authentication":
l.setCredentials(request.args['host'][0], request.args['user'][0], request.args['password'][0])
response = l.process()
return json.dumps({"connection" : response})
if command == "users":
from Plugins.Users import Users
if request.args['action'][0] == "list":
u = Users(l,"","","","","","","","","")
response = u.list(request.args)
return json.dumps(response)
elif request.args['action'][0] == "searchUsername":
u = Users(l,"",request.args['name'][0],request.args['surname'][0],"","","","","","")
response = u.searchNewUsername()
return json.dumps({"response" : response})
elif request.args['action'][0] == "getUserData":
u = Users(l,"","","","",request.args['user'][0],"","","","")
response = u.getUserData()
return json.dumps({"response" : response})
elif request.args['action'][0] == "getAllUsers":
response = LdapUtils.getAllUsers(l)
return json.dumps(response)
elif request.args['action'][0] == "delete":
u = Users(l,"","","","",request.args['user'][0],"","","","")
response = u.delete()
return json.dumps({"response" : response})
else:
departments=[]
classrooms=[]
try:
departments = request.args['multiselect_departments']
except:
pass
try:
classrooms = request.args['multiselect_classrooms']
except:
pass
u = Users(l,request.args['type'][0],request.args['name'][0],request.args['surname'][0],request.args['nif'][0],request.args['user'][0],request.args['password'][0],request.args['password2'][0],departments,classrooms)
response = u.process(request.args['action'][0])
return json.dumps({"response" : response})
# Gestion de Grupos
if command == "groups":
from Plugins.Groups import Groups
if request.args['action'][0] == "list":
g = Groups(l,"","","")
response = g.list(request.args)
return json.dumps(response)
elif request.args['action'][0] == "getAllGroups":
response = LdapUtils.getAllGroups(l)
return json.dumps(response)
elif request.args['action'][0] == "getGroupData":
g = Groups(l,"",request.args['name'][0],"")
response = g.getGroupData()
return json.dumps({"response" : response})
elif request.args['action'][0] == "delete":
g = Groups(l,"",request.args['name'][0],"")
response = g.delete()
return json.dumps({"response" : response})
else:
g = Groups(l,request.args['type'][0], request.args['name'][0], request.args['users'][0])
response = g.process(request.args['action'][0])
return json.dumps({"response" : response})
if command == "hosts":
from Plugins.Hosts import Hosts
if request.args['action'][0] == "list":
h = Hosts (l,"","","","","")
response = h.list(request.args)
print "hosts-list"
#prueba para encender un equipo
#h = Hosts ("a21-pro","172.23.36.47","00:22:15:6e:9c:ba")
#print "Encendiendo host "+h.getName()
#h.wakeup()
return json.dumps(response)
elif request.args['action'][0] == "getThinclientGroups":
h = Hosts (l,"","","","","")
response = h.getThinclientGroups ()
return json.dumps({"response" : response})
elif request.args['action'][0] == "getInternalGroups":
h = Hosts (l,"","","","","")
response = h.getInternalGroups ()
return json.dumps({"response" : response})
elif request.args['action'][0] == "getLTSPServers":
h = Hosts (l,"","","","","")
response = h.getLTSPServers ()
return json.dumps({"response" : response})
elif request.args['action'][0] == "getLTSPStatus":
f = open('/tmp/controlIES.ltpsSevers', 'r')
computers = f.read().split(" ")
computers.sort()
f = open('/tmp/controlIES.ltpsTeachers', 'r')
teachers = f.read().split(" ")
teachers.sort()
return json.dumps({ "computers":computers, "teachers":teachers })
elif request.args['action'][0] == "getClassroomDetails":
import xmlrpclib
from Plugins.Users import Users
objUser = Users(l,"","","","",request.args['teacher'][0],"","","","")
teacherData = objUser.getUserData()
s = xmlrpclib.Server("http://" + request.args['classroom'][0] + ":8900");
users = s.Users()
response = []
for u in users:
user = u.split("@")
objUser = Users(l,"","","","",user[0],"","","","")
photo = objUser.getUserPhoto()
response.append({ 'username': user[0], 'host': user[1], 'photo': photo })
return json.dumps({ "teacher" : teacherData, "classroom" : request.args['classroom'][0], "students" : response })
elif request.args['action'][0]=="delete":
h = Hosts(l,request.args['cn'][0],"","",request.args['group'][0],request.args['type'][0])
response = h.process(request.args['action'][0])
return json.dumps({"response" : response})
elif request.args['action'][0] == "getHostData":
h = Hosts(l,request.args['cn'][0],"","",request.args['group'][0],request.args['type'][0])
response = h.getHostData()
return json.dumps({"response" : response})
else: #add, modify
if request.args ['type'][0] == 'thinclient':
ip = ""
else:
ip = request.args ['ip'][0]
h = Hosts(l,request.args['name'][0],ip,request.args['mac'][0],request.args['group'][0],request.args['type'][0])
response = h.process(request.args['action'][0])
return json.dumps({"response" : response})
if command == "dhcp":
from Plugins.DHCP import DHCP
from Plugins.LdapConnection import LdapConnection
if request.args['action'][0] == "list":
#busqueda dhcp
search = l.search("cn=INTERNAL,cn=DHCP Config,dc=instituto,dc=extremadura,dc=es","dhcpOption=*",["dhcpOption"])
#obtengo valores de dhcpOPtion
#OJO: Hacer algo para que no haya desbordamiento de indices
dhcpOption = search[0][0][1]['dhcpOption']
subnet_mask = dhcpOption[0].replace('subnet-mask ','')
broadcast_address = dhcpOption[1].replace('broadcast-address ','')
routers = dhcpOption[2].replace('routers ','')
domain_name_servers = dhcpOption[3].replace('domain-name-servers ','')
domain_name = dhcpOption[4].replace('domain-name ','')
ntp_servers = dhcpOption[5].replace('ntp-servers ','')
log_servers = dhcpOption[6].replace('log-servers ','')
netbios_name_servers = dhcpOption[7].replace('netbios-name-servers ','')
netbios_node_type = dhcpOption[8].replace('netbios-node-type ','')
d = DHCP (self,subnet_mask,broadcast_address,routers,domain_name,ntp_servers,log_servers,netbios_name_servers,netbios_node_type)
print "Mascara de red: " + d.subnet_mask
print "Direccion de Broadcast: " + d.broadcast_address
#return json.dumps(response)
else:
h = Hosts(l,request.args['name'][0],request.args['ip'][0],request.args['mac'][0])
print request.args['name'][0]
response = h.process(request.args['action'][0])
return json.dumps({"response" : response})
if command == "logout":
request.getSession().expire()
return json.dumps({"response" : "logout"})
return
def response_fail(self, messages=None):
messages = messages or []
return json.dumps({
'status': 'fail',
'errors': messages,
'time': int(time())
})
def response_ok(self, **kwds):
kwds.update({'status': 'ok', 'time': int(time())})
return json.dumps(kwds)
controlies/branches/twisted/Server.py
##############################################################################
# -*- coding: utf-8 -*-
# Project: ControlIES
# Module: Server.py
# Purpose: ControlIES web server
# Language: Python 2.5
# Date: 7-Feb-2011.
# Ver: 7-Feb-2011.
# Author: Manuel Mora Gordillo
# Copyright: 2011 - Manuel Mora Gordillo <manuito @no-spam@ gmail.com>
#
# ControlIES 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 3 of the License, or
# (at your option) any later version.
# ControlIES 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 ControlIES. If not, see <http://www.gnu.org/licenses/>.
#
##############################################################################
from Utils.avahiClient import avahiClient
from Utils import Configs
from twisted.web import static, server
from twisted.web.server import Session
from twisted.python.components import registerAdapter
import logging,logging.handlers
import MainLoop
from zope.interface import Interface, Attribute, implements
from Plugins.LdapConnection import LdapConnection, ILdapConnection
import os.path
# Logging
log_handler = logging.handlers.RotatingFileHandler(Configs.LOG_FILENAME, maxBytes=100000, backupCount=5)
log_formatter = logging.Formatter(fmt='%(asctime)s %(levelname)-8s %(message)s',datefmt='%a, %d %b %Y %H:%M:%S')
log_handler.setFormatter(log_formatter)
root_logger=logging.getLogger()
root_logger.addHandler(log_handler)
root_logger.level=logging.DEBUG
registerAdapter(LdapConnection, Session, ILdapConnection)
# Start up the web service.
Root = MainLoop.ControlIESProtocol() #Resource object
Root.PageDir='/home/jose/servidores/controlies/trunk/www/'
#Root.PageDir='/home/chisco/Proyectos/controlies/trunk/www'
site = server.Site(Root)
fileNameServers = '/tmp/controlIES.ltpsSevers'
if os.path.isfile(fileNameServers):
os.remove(fileNameServers)
f = open(fileNameServers, 'w')
fileNameTeachers = '/tmp/controlIES.ltpsTeachers'
if os.path.isfile(fileNameTeachers):
os.remove(fileNameTeachers)
f = open(fileNameTeachers, 'w')
def _add_locationServers(self, name, address, port):
computerToAdd = name.split(" ")
f = open(fileNameServers, 'a')
f.write(computerToAdd[0]+" ")
f.close()
def _remove_locationServers(self, name, address, port):
computerToDelete = name.split(" ")
f = open(fileNameServers, 'r')
computersList = f.read()
f.close()
computersList = computersList.replace(computerToDelete[0]+" ","")
f = open(fileNameServers, 'w')
f.write(computersList)
f.close()
def _add_locationTeachers(self, name, address, port):
teacherToAdd = name.split(" ")
f = open(fileNameTeachers, 'a')
f.write(teacherToAdd[0]+" ")
f.close()
def _remove_locationTeachers(self, name, address, port):
teacherToDelete = name.split(" ")
f = open(fileNameTeachers, 'r')
teachersList = f.read()
f.close()
teachersList = teachersList.replace(teacherToDelete[0]+" ","")
f = open(fileNameTeachers, 'w')
f.write(teachersList)
f.close()
try:
_monitor = avahiClient('_workstation._tcp')
_monitor.add_callback('new-service', _add_locationServers)
_monitor.add_callback('remove-service', _remove_locationServers)
_monitor.start()
except Exception, ex:
logging.getLogger().debug("Couldn't initialize Avahi monitor: workstations")
try:
_monitor = avahiClient('_controlaula._tcp')
_monitor.add_callback('new-service', _add_locationTeachers)
_monitor.add_callback('remove-service', _remove_locationTeachers)
_monitor.start()
except Exception, ex:
logging.getLogger().debug("Couldn't initialize Avahi monitor: controlaula")
from twisted.internet import reactor
reactor.listenTCP(7778,site)
reactor.run()
controlies/branches/twisted/Utils/Utils.py
##############################################################################
# -*- coding: utf-8 -*-
# Project: ControlIES
# Module: Groups.py
# Purpose: Groups class
# Language: Python 2.5
# Date: 18-Feb-2011.
# Ver: 18-Feb-2011.
# Author: Manuel Mora Gordillo
# Francisco Mendez Palma
# Copyright: 2011 - Manuel Mora Gordillo <manuito @no-spam@ gmail.com>
# 2011 - Francisco Mendez Palma <fmendezpalma @no-spam@ gmail.com>
#
# ControlIES 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 3 of the License, or
# (at your option) any later version.
# ControlIES 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 ControlIES. If not, see <http://www.gnu.org/licenses/>.
#
##############################################################################
def cmpLists(list1, list2):
onlyInList1 = set(list1).difference(set(list2))
onlyInList2 = set(list2).difference(set(list1))
inTwoLists = set(list1) & set(list2)
return { 'onlyInList1':onlyInList1, 'onlyInList2':onlyInList2, 'inTwoLists':inTwoLists }
def parseToLdap(string):
string = string.replace(" ","_")
string = string.replace("á","a").replace("é","e").replace("í","o").replace("ó","o").replace("ú","u")
string = string.replace("Á","A").replace("É","E").replace("Í","I").replace("Ó","O").replace("Ú","U")
string = string.replace("ñ","n").replace("Ñ","N")
return string
def generate_salt():
# Salt can be any length, but not more than about 37 characters
# because of limitations of the binascii module.
# 7 is what Netscape's example used and should be enough.
# All 256 characters are available.
from random import randrange
salt = ''
for n in range(7):
salt += chr(randrange(256))
return salt
def encrypt(password):
import sha
from binascii import b2a_base64
password = str(password)
salt = generate_salt()
return b2a_base64(sha.new(password + salt).digest() + salt)[:-1]
controlies/branches/twisted/Utils/LdapUtils.py
##############################################################################
# -*- coding: utf-8 -*-
# Project: ControlIES
# Module: LdapUtils.py
# Purpose: Ldap utils
# Language: Python 2.5
# Date: 18-Feb-2011.
# Ver: 18-Feb-2011.
# Author: Manuel Mora Gordillo
# Francisco Mendez Palma
# Copyright: 2011 - Manuel Mora Gordillo <manuito @no-spam@ gmail.com>
# 2011 - Francisco Mendez Palma <fmendezpalma @no-spam@ gmail.com>
#
# ControlIES 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 3 of the License, or
# (at your option) any later version.
# ControlIES 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 ControlIES. If not, see <http://www.gnu.org/licenses/>.
#
##############################################################################
# Get all users
def getAllUsers(ldap):
result = ldap.search("ou=People","uid=*",["uid","cn"])
rows = []
for u in result:
rows.append([u[0][1]['uid'][0] , u[0][1]['cn'][0] ]);
return rows
# Get all groups classified by type
def getAllGroups(ldap):
result = ldap.search("ou=Group","(|(groupType=school_department)(groupType=school_class))",["cn","groupType"])
departments = []
classrooms = []
for g in result:
if g[0][1]["groupType"][0] == "school_department":
departments.append(g[0][1]["cn"][0])
elif g[0][1]["groupType"][0] == "school_class":
classrooms.append(g[0][1]["cn"][0])
departments.sort()
classrooms.sort()
return { "departments":departments, "classrooms":classrooms }
# Get the max ID of the groups and users
def getMaxID(ldap):
result = ldap.search("ou=Group","cn=*",["gidNumber"])
numbers = []
for i in result:
numbers.append(int(i[0][1]['gidNumber'][0]))
result = ldap.search("ou=People","uid=*",["gidNumber","uidNumber"])
for i in result:
numbers.append(int(i[0][1]['gidNumber'][0]))
numbers.append(int(i[0][1]['uidNumber'][0]))
numbers.sort()
maxID = 1
if len(numbers) > 0:
maxID = numbers[len(numbers)-1] + 1
return maxID
def whatHome(type):
if type == "teacher":
return "/home/profesor/"
else:
return "/home/alumnos/"
controlies/branches/twisted/Utils/avahiClient.py
##############################################################################
# -*- coding: utf-8 -*-
# Project: ControlIES
# Module: avahiClient.py
# Purpose: Avahi client to detect ltsp servers
# Language: Python 2.5
# Date: 27-Feb-2011.
# Ver: 27-Feb-2011.
# Author: José Luis Redrejo Rodriguez
# Copyright: 2011 - José Luis Redrejo Rodriguez <jredrejo @no-spam@ debian.org>
# Modified by: Manuel Mora Gordillo <manuito @no-spam@ gmail.com>
#
# ControlIES 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 3 of the License, or
# (at your option) any later version.
# ControlIES 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 ControlIES. If not, see <http://www.gnu.org/licenses/>.
#
##############################################################################
try:
import dbus
if getattr(dbus, 'version', (0,0,0)) >= (0,41,0):
import dbus.glib
except ImportError:
dbus = None
if dbus:
try:
import avahi
except ImportError:
avahi = None
else:
avahi = None
from twisted.internet import defer, threads
from twisted.internet import glib2reactor
import logging
glib2reactor.install()
class avahiClient():
def __init__(self, type):
self._callbacks = {'new-service': [], 'remove-service': [] }
# initialize dbus stuff needed for discovery
self.bus = dbus.SystemBus()
avahi_bus = self.bus.get_object(avahi.DBUS_NAME, avahi.DBUS_PATH_SERVER)
self.server = dbus.Interface(avahi_bus, avahi.DBUS_INTERFACE_SERVER)
#stype = '_workstation._tcp'
#stype = '_controlaula._tcp'
stype = type
domain = 'local'
self._plugged = {}
avahi_browser = self.server.ServiceBrowserNew(avahi.IF_UNSPEC, avahi.PROTO_UNSPEC, stype, domain, dbus.UInt32(0))
obj = self.bus.get_object(avahi.DBUS_NAME, avahi_browser)
self.browser = dbus.Interface(obj, avahi.DBUS_INTERFACE_SERVICE_BROWSER)
def start(self):
self.browser.connect_to_signal('ItemNew', self.new_service)
self.browser.connect_to_signal('ItemRemove', self.remove_service)
def stop(self):
self.bus.close()
def new_service(self, interface, protocol, name, type, domain, flags):
def resolve_service_reply(*service):
address, port = service[-4:-2]
name = unicode(service[2])
for cb in self._callbacks['new-service']:
self._plugged[name] = (address,port)
cb(self,name, address, port)
def resolve_service_error(exception):
logging.getLogger().debug('could not resolve daap service %s %s: %s' % (name, domain, exception))
#self.warning('could not resolve daap service %s %s: %s' % (name, domain, exception))
self.server.ResolveService(interface, protocol, name, type, domain,
avahi.PROTO_UNSPEC, dbus.UInt32(0),
reply_handler=resolve_service_reply,
error_handler=resolve_service_error)
def remove_service(self, interface, protocol, name, type, domain,server):
address, port = self._plugged[name]
for cb in self._callbacks['remove-service']:
cb(self,name, address, port)
def add_callback(self, sig_name, callback):
self._callbacks[sig_name].append(callback)
def remove_callback(self, sig_name, callback):
self._callback[sig_name].remove(callback)
controlies/branches/twisted/Utils/Configs.py
LOG_FILENAME= '/tmp/controlies.log'
controlies/branches/twisted/Plugins/Security.py
##############################################################################
# -*- coding: utf-8 -*-
# Project: ControlIES
# Module: Security.py
# Purpose: Authentication with ldap server
# Language: Python 2.5
# Date: 7-Feb-2011.
# Ver: 7-Feb-2011.
# Author: Manuel Mora Gordillo
# Copyright: 2011 - Manuel Mora Gordillo <manuito @no-spam@ gmail.com>
#
# ControlIES 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 3 of the License, or
# (at your option) any later version.
# ControlIES 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 ControlAula. If not, see <http://www.gnu.org/licenses/>.
#
##############################################################################
from Plugins.LdapConnection import LdapConnection
class Security(object):
def __init__(self,host,user,password):
self.host = host
self.user = user
self.password = password
def validation(self):
if self.host == "":
return "host"
if self.user == "":
return "user"
if self.password == "":
return "password"
return "OK"
def process(self):
val = self.validation()
if val != "OK":
return val
auth = self.authentication()
return auth
def authentication(self):
l = LdapConnection(self.host,'cn='+self.user+',ou=People,dc=instituto,dc=extremadura,dc=es',self.password)
ret = l.connect()
return ret
controlies/branches/twisted/Plugins/NetworkUtils.py
##############################################################################
# -*- coding: utf-8 -*-
# Project: Controlaula
# Module: NetworkUtils.py
# Purpose: Several network utilities to be used in Python
# Language: Python 2.5
# Date: 17-Jan-2010.
# Ver: 17-Jan-2010.
# Author: José L. Redrejo Rodríguez
# Copyright: 2009 - José L. Redrejo Rodríguez <jredrejo @nospam@ debian.org>
#
# ControlAula 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 3 of the License, or
# (at your option) any later version.
# ControlAula 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 ControlAula. If not, see <http://www.gnu.org/licenses/>.
#
##############################################################################
import array,fcntl,socket,struct,os,re
import logging,subprocess
gateway='0'
ltspGateway='0'
essid=''
bssid=''
IFNAMSIZE = 16
IW_ESSID_MAX_SIZE = 16
SIOCGIWESSID = 0x8B1B
SIOCGIWAP = 0x8B15
def get_ip_address(ifname):
"""Returns the ip address of the interface ifname"""
s = socket.socket(socket.AF_INET, socket.SOCK_DGRAM)
try:
ip= socket.inet_ntoa(fcntl.ioctl(
s.fileno(),
0x8915, # SIOCGIFADDR
struct.pack('256s', ifname[:15]) )[20:24]
)
except:
ip=''
return ip
def get_ip_inet_address(connection_ip='198.41.0.4'):
"""Returns the ip address of the interface used to connect to the given ip
198.41.0.4 is a DNS ROOT Server, so it's the default value to connect to Internet
"""
s = socket.socket(socket.AF_INET, socket.SOCK_DGRAM)
try:
s.connect((connection_ip, 0))
inet_address= s.getsockname()[0]
except:
inet_address=''
s.close()
logging.getLogger().debug("Inet Address:" + inet_address)
return inet_address
def get_inet_HwAddr(connection_ip='192.168.0.254'):
"""Returns the mac address of the interface used to connect to the given ip"""
interfaces=all_interfaces()
rightIP=get_ip_inet_address(connection_ip)
mac=''
ifname=''
for i in interfaces:
if rightIP== get_ip_address(i[0]):
ifname=i[0]
break
if ifname !='':
mac=get_HwAddr(ifname)
return mac
def get_HwAddr(ifname):
"""Returns the mac of the ifname network card"""
s = socket.socket(socket.AF_INET, socket.SOCK_DGRAM)
info = fcntl.ioctl(s.fileno(), 0x8927, struct.pack('256s', ifname[:15]))
try:
mac= ''.join(['%02x:' % ord(char) for char in info[18:24]])[:-1]
except:
mac=''
return mac
def getWirelessNICnames():
""" return list of wireless device names """
device = re.compile('[a-z]{3,4}[0-9]')
ifnames = []
f = open('/proc/net/wireless', 'r')
data = f.readlines()
for line in data:
try:
ifnames.append(device.search(line).group())
except AttributeError:
pass
return ifnames
def all_interfaces():
"""Returns all the available network interfaces in a linux machine"""
max_possible = 128 # arbitrary. raise if needed.
bytes = max_possible * 32
s = socket.socket(socket.AF_INET, socket.SOCK_DGRAM)
names = array.array('B', '\0' * bytes)
outbytes = struct.unpack('iL', fcntl.ioctl( s.fileno(), 0x8912, struct.pack('iL', bytes, names.buffer_info()[0]) ))[0]
namestr = names.tostring()
#return [namestr[i:i+32].split('\0', 1)[0] for i in range(0, outbytes, 32)]
lst = []
arch64=(os.uname()[4]=='x86_64')
if arch64:
totalStruct=40
else:
totalStruct=32
for i in range(0, outbytes, totalStruct):
if arch64:
name = namestr[i:i+16].split('\0', 1)[0]
else:
name = namestr[i:i+32].split('\0', 1)[0]
ip = namestr[i+20:i+24]
lst.append((name, socket.inet_ntoa(ip)))
return lst
def getESSID( ifname):
sockfd = socket.socket(socket.AF_INET, socket.SOCK_DGRAM)
essid = ""
buff = array.array('c', '\0'*32)
caddr_t, length = buff.buffer_info()
s = struct.pack('Pi', caddr_t, length)
buff2 = IFNAMSIZE-len(ifname)
ifreq = ifname + '\0'*buff2
ifreq = ifreq + s
try:
result = fcntl.ioctl(sockfd.fileno(), SIOCGIWESSID, ifreq)
i=0
result=result[16:]
except IOError, (i, e):
i=i
result=e
if i > 0:
return (i, result)
str = buff.tostring()
return (0,str.strip('\x00'))
def getHostName():
return socket.gethostname()
def getFreeTCPPort():
"""Returns a random free port provided by the Operative System"""
sock = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
sock.setsockopt(socket.SOL_SOCKET, socket.SO_REUSEADDR, 1)
sock.bind(('localhost', 0))
newPort= sock.getsockname()[1]
sock.close()
return newPort
def getWirelessData():
global essid
global bssid
wifiNICs=getWirelessNICnames()
if len(wifiNICs)>0:
for i in wifiNICs:
value,nessid=getESSID(i)
if value==0:
essid=nessid
value2,nbssid=getAPaddr(i)
if value2==0:
bssid=nbssid
def getAPaddr(ifname):
sockfd = socket.socket(socket.AF_INET, socket.SOCK_DGRAM)
buff = array.array('c', '\0'*32)
caddr_t, length = buff.buffer_info()
s = struct.pack('Pi', caddr_t, length)
buff2 = IFNAMSIZE-len(ifname)
ifreq = ifname + '\0'*buff2
ifreq = ifreq + s
try:
result = fcntl.ioctl(sockfd.fileno(), SIOCGIWAP, ifreq)
i=0
result=result[16:]
except IOError, (i, e):
i=i
result=e
if i > 0:
return (i, result)
else:
mac_addr = struct.unpack('xxBBBBBB',result[:8])
return (0,"%02X:%02X:%02X:%02X:%02X:%02X" % mac_addr)
def scan_server(address, port):
"""Returns true if a port is open at address, or false otherwise"""
s = socket.socket()
#print "Attempting to connect to %s on port %s." %(address, port)
try:
s.connect((address, port))
#print "Connected to server %s on port %s." %(address, port)
s.close()
return True
except socket.error, e:
logging.getLogger().debug("Connecting to %s on port %s failed with the following error: %s" %(address, port, e))
return False
def getUsableTCPPort(address,port):
"""Returns the first free port between port and port +10"""
freeport=port
for x in range(port,port+10):
check = scan_server(address, x)
if check==False :
freeport=x
break
return freeport
def startup(address):
addr_byte = address.split(':')
hw_addr = struct.pack('BBBBBB', int(addr_byte[0], 16),
int(addr_byte[1], 16),
int(addr_byte[2], 16),
int(addr_byte[3], 16),
int(addr_byte[4], 16),
int(addr_byte[5], 16))
msg = '\xff' * 6 + hw_addr * 16
s = socket.socket(socket.AF_INET, socket.SOCK_DGRAM)
s.setsockopt(socket.SOL_SOCKET, socket.SO_BROADCAST, 1)
try:
s.sendto(msg, ('<broadcast>', 9))
s.sendto(msg, ('<broadcast>', 7))
s.sendto(msg, ('192.168.0.255', 9))
s.sendto(msg, ('192.168.0.255', 7))
except:
s.sendto(msg, ('<broadcast>', 2000))
s.sendto(msg, ('192.168.0.255', 2000))
s.close()
def defaultGW():
global gateway
if gateway=='0':
try:
s=subprocess.Popen('/sbin/route -n|grep "0.0.0.0"|grep UG',shell=True,stdout=subprocess.PIPE).communicate()[0]
gateway=s.splitlines()[0].split()[1]
except:
gateway='0'
return gateway
def ltspGW():
global ltspGateway
if ltspGateway=='0':
try:
externalIP=get_ip_inet_address()
internalIP=get_ip_inet_address('192.168.0.2')
if externalIP==internalIP or externalIP=='':
ltspGateway=defaultGW()
else:
ltspGateway=internalIP
except:
ltspGateway='0'
return ltspGateway
def cleanRoutes():
s=subprocess.Popen(['route','-n'],stdout=subprocess.PIPE).communicate()[0]
l=s.splitlines()
for route in l:
target=route.split()[0]
if target[:4]=='239.':
subprocess.Popen(['route','del','-net',target + '/24'])
def addRoute(net,gw=''):
if gw=='':
newgw=defaultGW()
else:
newgw=gw
subprocess.Popen(['route','add','-net',net+ '/24','gw',newgw])
controlies/branches/twisted/Plugins/DHCP.py
##############################################################################
# -*- coding: utf-8 -*-
# Project: ControlIES
# Module: DHCP.py
# Purpose: DHCP class
# Language: Python 2.5
# Date: 7-Feb-2011.
# Ver: 7-Feb-2011.
# Author: Manuel Mora Gordillo
# Francisco Mendez Palma
# Copyright: 2011 - Manuel Mora Gordillo <manuito @no-spam@ gmail.com>
# 2011 - Francisco Mendez Palma <fmendezpalma @no-spam@ gmail.com>
#
# ControlIES 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 3 of the License, or
# (at your option) any later version.
# ControlIES 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 ControlAula. If not, see <http://www.gnu.org/licenses/>.
#
##############################################################################
import ldap
import logging
from math import ceil
class DHCP(object):
def __init__(self):
pass
def __init__(self,ldap,subnet_mask,broadcast_address,routers,domain_name_servers,domain_name,ntp_servers,log_servers,netbios_name_servers,netbios_node_type):
self.ldap = ldap
self.subnet_mask = subnet_mask
self.broadcast_address = broadcast_address
self.routers = routers
self.domain_name_servers = domain_name_servers
self.domain_name = domain_name
self.ntp_servers = ntp_servers
self.log_servers = log_servers
self.netbios_name_servers = netbios_name_servers
self.netbios_node_type = netbios_node_type
def validation(self):
if self.subnet_mask == "":
return "subnet_mask"
if self.broadcast_address == "broadcast_address":
return "broadcast_address"
if self.routers == "routers":
return "routers"
if self.domain-name == "domain-name":
return "domain-name"
if self.domain_name_servers == "domain_name_servers":
return "domain_name_servers"
if self.ntp_servers == "ntp_servers":
return "ntp_servers"
if self.log_servers == "log_servers":
return "log_servers"
if self.netbios_name_servers == "netbios_name_servers":
return "netbios_name_servers"
if self.netbios_node_type == "netbios_node_type":
return "netbios_node_type"
return "OK"
def process(self,action):
if action == "add":
val = self.validation()
if val != "OK":
return val
else:
response = self.add()
return response
if action == "modify":
val = self.validation()
if val != "OK":
return val
else:
response = self.modify()
return response
if action == "delete":
response = self.delete()
return response
if action == "list":
response = self.list();
return response
def list(self,args):
#busqueda dhcp
search = self.ldap.search("cn=INTERNAL,cn=DHCP Config,dc=instituto,dc=extremadura,dc=es","dhcpOption=*",["dhcpOption"])
limit = int(args['rows'][0])
page = int(args['page'][0])
start = limit * page - limit
finish = start + limit;
if len(search) > 0:
totalPages = ceil( len(search) / int(limit) )
else:
totalPages = 0
if page > totalPages:
page = totalPages
# print search[0][0][1]["uidNumber"][0]
rows = []
for i in search[start:finish]:
row = { "cn":i[0][0], "cell":[i[0][1]["cn"][0], i[0][1]["ipHostNumber"][0],i[0][1]["macAddress"]]}
rows.append(row)
return { "page":page, "total":totalPages, "records":len(search), "rows":rows }
def add(self):
record = [
('objectclass', ['person','organizationalperson','inetorgperson']),
('uid', ['francis']),
('cn', [self.name] ),
('sn', ['Bacon'] ),
('userpassword', [self.password]),
('ou', ['users'])
]
try:
self.ldap.add("cn=hosts", record)
except ldap.ALREADY_EXISTS:
return "fail"
return "OK"
def modify(self):
mod_attrs = [
(ldap.MOD_ADD, 'description', 'Author of New Organon'),
(ldap.MOD_ADD, 'description', 'British empiricist')
]
self.ldap.modify_s('uid='+ uid +',cn=hosts', mod_attrs)
def delete(self,uid):
self.ldap.delete('uid='+ uid +',cn=hosts')
def wakeup(self):
from twisted.internet.task import LoopingCall
from twisted.internet import defer
from Plugins import NetworkUtils
NetworkUtils.startup(self.mac)
# def wakeup(self):
# from twisted.internet.task import LoopingCall
# from twisted.internet import defer
# from Plugins import NetworkUtils
# NetworkUtils.startup(self.mac)
# Encender el equipo
#def wakeup(self):
# macs=[]
# for i in self.targets:
# mac=Configs.MonitorConfigs.GetMAC(i)
# if mac !='':
# macs.append(mac)
# Actions.sendWOLBurst(macs, 2)
#Apagar el equipo
# def sleep(self):
# self.usersCommand(Desktop.sleep)
#def sendWOLBurst(macs,throttle):
# from twisted.internet.task import LoopingCall
# from twisted.internet import defer
# if not macs:
# return defer.succeed(None)
# d = defer.Deferred()
# work = list(macs)
# def sendNext():
# if not work:
# loop.stop()
# d.callback(None)
# return defer.succeed(None)
# next = work.pop(0)
#
# #subprocess.Popen(['wakeonlan',next ])
# #subprocess.Popen(['wakeonlan','-i','192.168.0.255',next ])
# NetworkUtils.startup(next)
#
# return None
# loop = LoopingCall(sendNext)
# loop.start(throttle)
# return d
controlies/branches/twisted/Plugins/Groups.py
##############################################################################
# -*- coding: utf-8 -*-
# Project: ControlIES
# Module: Groups.py
# Purpose: Groups class
# Language: Python 2.5
# Date: 7-Feb-2011.
# Ver: 7-Feb-2011.
# Author: Manuel Mora Gordillo
# Francisco Mendez Palma
# Copyright: 2011 - Manuel Mora Gordillo <manuito @no-spam@ gmail.com>
# 2011 - Francisco Mendez Palma <fmendezpalma @no-spam@ gmail.com>
#
# ControlIES 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 3 of the License, or
# (at your option) any later version.
# ControlIES 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 ControlIES. If not, see <http://www.gnu.org/licenses/>.
#
##############################################################################
import ldap
import logging
from math import ceil
from operator import itemgetter
from Utils import Utils, LdapUtils
class Groups(object):
def __init__(self):
pass
def __init__(self,ldap,type,name,users):
self.ldap = ldap
self.type = type
self.name = Utils.parseToLdap(name)
self.users = users
def validation(self,action):
if self.type == "none":
return "type"
if self.name == "":
return "name"
if self.users == "":
return "users"
return "OK"
def process(self,action):
if action == "add":
val = self.validation(action)
if val != "OK":
return val
else:
response = self.add()
return response
if action == "modify":
val = self.validation(action)
if val != "OK":
return val
else:
response = self.modify()
return response
... Diferencia truncada por exceder el máximo tamaño visualizable.

Exportar a: Unified diff