Proyecto

General

Perfil

« Anterior | Siguiente » 

Revisión 177

Añadido por jredrejo hace casi 14 años

pasada versión de twisted a una rama

Ver diferencias:

controlies/trunk/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/manu/proyectos/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/trunk/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/trunk/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/trunk/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/trunk/Utils/Configs.py
LOG_FILENAME= '/tmp/controlies.log'
controlies/trunk/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/trunk/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/trunk/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/trunk/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
def list(self,args):
filter = self.buildFilter(args)
search = self.ldap.search("ou=Group",filter,["cn","gidNumber","groupType","memberUid"])
# grid parameters
limit = int(args['rows'][0])
page = int(args['page'][0])
start = limit * page - limit
finish = start + limit;
# sort by field
sortBy = args['sidx'][0]
if sortBy == "cn":
sortBy = "id"
# reverse Sort
reverseSort = False
if args['sord'][0] == "asc":
reverseSort = True
# type of group (Classroom/Department)
try:
searchType = args['type'][0]
except LookupError:
searchType = "none"
rows = []
for i in search:
typeRow="Aula"
if i[0][1]["groupType"][0]=="school_department":
typeRow="Departamento"
if searchType == typeRow or searchType=="none":
try:
usersNumber = len(i[0][1]["memberUid"])
except:
usersNumber = 0
row = {
"id":i[0][1]["cn"][0],
"cell":[typeRow, i[0][1]["cn"][0], i[0][1]["gidNumber"][0], usersNumber],
"type": typeRow,
"cn": i[0][1]["cn"][0],
"gidNumber": i[0][1]["gidNumber"][0],
"usersNumber": usersNumber
}
rows.append(row)
if len(search) > 0:
totalPages = ceil( len(search) / int(limit) )
else:
totalPages = 0
if page > totalPages:
page = totalPages
# sort rows
result = sorted(rows, key=itemgetter(sortBy), reverse=reverseSort)
return { "page":page, "total":totalPages, "records":len(search), "rows":result[start:finish] }
def buildFilter(self, args):
filter = "(&(cn=*)(|(groupType=school_class)(groupType=school_department))"
try:
filter = filter + "(cn=*" + args['cn'][0] + "*)"
except LookupError:
pass
try:
filter = filter + "(gidNumber=" + args['gidNumber'][0] + ")"
except LookupError:
pass
filter = filter + ")"
return filter
def add(self):
maxID = str(LdapUtils.getMaxID(self.ldap))
members = []
for m in self.users.split(','):
members.append("uid=" + m + ",ou=People,dc=instituto,dc=extremadura,dc=es")
attr = [
('objectclass', ['top','posixGroup','lisGroup','lisAclGroup']),
('grouptype', [self.type] ),
('gidnumber', [maxID] ),
('cn', [self.name] ),
('description', [self.name+' department group']),
('memberuid', self.users.split(',')),
('member', members)
]
self.ldap.add("cn="+self.name+",ou=Group", attr)
return "OK"
def modify(self):
members = []
for m in self.users.split(','):
members.append("uid=" + m + ",ou=People,dc=instituto,dc=extremadura,dc=es")
mod_attrs = [
(ldap.MOD_REPLACE, 'memberuid', self.users.split(',')),
(ldap.MOD_REPLACE, 'member', members)
]
self.ldap.modify('cn='+ self.name +',ou=Group', mod_attrs)
return "OK"
def delete(self):
self.ldap.delete('cn='+ self.name +',ou=Group')
return "OK"
def getGroupData(self):
result = self.ldap.search("ou=Group","cn="+self.name,["cn","grouptype","memberuid"])
members = result[0][0][1]["memberUid"]
members.sort()
dataGroup = {
"name":result[0][0][1]["cn"][0],
"type":result[0][0][1]["groupType"][0],
"memberuid":members
}
return dataGroup
def getGroupUsers(self):
result = self.ldap.search("ou=Group","cn="+self.name,["cn","memberUid"])
members = []
for m in result:
members.append(m[0][1]["memberUid"][0])
members.sort()
return members
controlies/trunk/Plugins/LdapConnection.py
##############################################################################
# -*- coding: utf-8 -*-
# Project: ControlIES
# Module: LdapConnection.py
# Purpose: Connection 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/>.
#
##############################################################################
import ldap
import logging
from zope.interface import Interface, Attribute, implements
class ILdapConnection(Interface):
connection=Attribute("a ldap connection")
class LdapConnection(object):
implements(ILdapConnection)
def __init__(self,session):
self.host = ""
self.user = ""
self.passwd = ""
pass
def setCredentials(self,host,user,passwd):
self.host = host
self.user = user
self.passwd = passwd
def validation(self):
if self.host == "":
return "host"
if self.user == "":
return "user"
if self.passwd == "":
return "password"
return "OK"
def process(self):
val = self.validation()
if val != "OK":
return val
auth = self.connect()
return auth
def connect(self):
self.connection=ldap.open(self.host)
try:
self.connection.simple_bind_s("cn="+self.user+",ou=People,dc=instituto,dc=extremadura,dc=es",self.passwd)
except ldap.INVALID_CREDENTIALS:
logging.getLogger().debug('LDAP user or password incorrect')
return False
except ldap.CONFIDENTIALITY_REQUIRED:
try:
#self.connection.set_option(ldap.OPT_X_TLS_DEMAND, True)
self.connection=ldap.initialize("ldaps://" +self.host)
self.connection.simple_bind_s("cn="+self.user+",ou=People,dc=instituto,dc=extremadura,dc=es",self.passwd)
return True
except ldap.LDAPError,e:
logging.getLogger().debug('A secure connection with the ldap server could not be established')
return False
except ldap.LDAPError,e:
logging.getLogger().debug('LDAP error %s' % e.message["desc"])
return False
return True
def getConnect(self):
return self.connection
def search(self,baseDN,filter,retrieveAttributes):
try:
ldap_result_id = self.connection.search(baseDN+",dc=instituto,dc=extremadura,dc=es", ldap.SCOPE_SUBTREE, filter, retrieveAttributes)
result_set = []
while 1:
result_type, result_data = self.connection.result(ldap_result_id, 0)
if (result_data == []):
break
else:
if result_type == ldap.RES_SEARCH_ENTRY:
result_set.append(result_data)
return result_set
except ldap.LDAPError, e:
logging.getLogger().debug('LDAP error search')
"""result = con.search_s( base_dn, ldap.SCOPE_SUBTREE, filter, attrs )
return result"""
def add(self,baseDN,attr):
try:
self.connection.add_s(baseDN+",dc=instituto,dc=extremadura,dc=es", attr)
except ldap.ALREADY_EXISTS:
logging.getLogger().debug("LDAP already exists %s" % (baseDN))
except ldap.OPERATIONS_ERROR:
logging.getLogger().debug("LDAP operation error %s" % (baseDN))
except ldap.NO_SUCH_OBJECT:
logging.getLogger().debug("LDAP no such object %s" % (baseDN))
return True
def modify(self,baseDN,attr):
try:
self.connection.modify_s(baseDN+",dc=instituto,dc=extremadura,dc=es", attr)
except ldap.OPERATIONS_ERROR:
print "error"
except ldap.NO_SUCH_OBJECT:
print "no_such_object"
return True
def delete(self,baseDN):
try:
self.connection.delete_s(baseDN+",dc=instituto,dc=extremadura,dc=es")
except ldap.OPERATIONS_ERROR:
print "error"
except ldap.NO_SUCH_OBJECT:
print "no_such_object"
return True
"""def searchClassroomComputers(self,classroom):
''' How many groups? '''
base_dn = 'cn=THINCLIENTS,cn=DHCP Config,dc=instituto,dc=extremadura,dc=es'
filter = '(cn=group*)'
attrs = ['cn']
groups = self.search(self,base_dn,filter,attrs)
numberDesktops=0;
for i in range(0,len(groups)):
''' search computers of different groups '''
base_dn = 'cn='+groups[i][0]['cn'][0]+',cn=THINCLIENTS,cn=DHCP Config,dc=instituto,dc=extremadura,dc=es'
filter = '(cn='+classroom+'-o*)'
attrs = ['cn','dhcpHWAddress']
computers = self.search(self,base_dn,filter,attrs)
for j in range(0,len(computers)):
self.Desktops[numberDesktops] = {'desktop':computers[j][1]['cn'][0] , 'mac':computers[j][1]['dhcpHWAddress'][0]}
numberDesktops = numberDesktops + 1"""
controlies/trunk/Plugins/Hosts.py
##############################################################################
# -*- coding: utf-8 -*-
# Project: ControlIES
# Module: Hosts.py
# Purpose: Hosts 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
import time
from math import ceil
from operator import itemgetter
class Hosts(object):
def __init__(self):
pass
def __init__(self,ldap,name,ip,mac,group,type):
self.ldap = ldap
self.name = name
self.ip = ip
self.mac = mac
self.group = group
self.type = type
def getName (self):
return self.mac
def validation(self,action):
if action == "add":
if self.type == "none":
return "type"
if self.name == "":
return "name"
if self.type <> 'thinclient':
if self.ip == "":
return "ip"
if self.mac == "":
return "mac"
if self.type =="thinclient":
if self.group == "":
return "group"
if self.type == "":
return "type"
... Diferencia truncada por exceder el máximo tamaño visualizable.

Exportar a: Unified diff