# -*- coding: utf-8 -*- import ldap import subprocess import base64,random,hashlib,string import xml.etree import xml.etree.ElementTree import sys import unicodedata import syslog import os base_home_dir="/home/" def getLliurexVariables(): p1=subprocess.Popen(["llxcfg-listvars","--values"],stdout=subprocess.PIPE) output=p1.communicate()[0] output=output.replace("'","") tmp1=output.split(';\n') dic={} for item in tmp1: tmp2=item.split('=',1) if len(tmp2)>1: dic[tmp2[0]]=tmp2[1] return dic class GescenItem: def __init__(self): self.attributes={} #def init def print_me(self): print self.attributes #def print_me #class GescenItem class LdapUser: def __init__(self,properties): self.attributes=[] list=['top', 'posixAccount', 'shadowAccount', 'person', 'sabayonProfileNameObject','x-lliurex-user'] self.properties={} ''' for key in properties: self.properties[key]=properties[key] ''' self.properties=properties.copy() self.uid=self.properties["uid"] if not self.properties.has_key("description"): self.properties["description"]=self.properties["cn"] + " " + self.properties["sn"] self.properties["objectClass"]=list self.properties["loginShell"]="/bin/bash" self.properties["homeDirectory"]="/home/"+self.uid banned_list=['path','password','profile'] for key in self.properties: if key not in banned_list: self.attributes.append((key,self.properties[key])) def print_me(self): print self.properties #class LdapUSer def strip_accents(s): return ''.join((c for c in unicodedata.normalize('NFD', s) if unicodedata.category(c) != 'Mn')) class LdapGroup: def __init__(self,properties): self.attributes=[] list=['top', 'posixGroup', 'lisGroup','x-lliurex-group'] self.cn=properties["cn"] self.properties=properties if not self.properties.has_key("description"): self.properties["description"]=cn description=cn self.properties["objectClass"]=list for key in self.properties: self.attributes.append((key,self.properties[key])) self.attributes.append(('groupType','school_class')) #def __init__ def print_me(self): print self.properties #class LdapGroup class LdapManager: RANDOM_PASSWORDS=0 SAME_PASSWORD=1 PASS_EQUALS_USER=2 LDAP_SECRET1="/etc/lliurex-cap-secrets/ldap-master/ldap" LDAP_SECRET2="/etc/lliurex-secrets/passgen/ldap.secret" def __init__(self,llxvar): print "[LDAPMANAGER] INIT" self.llxvar=llxvar #self.getLliurexVariables() try: self.connect() except: self.connection=False #def init def getsalt(self,chars = string.letters + string.digits,length=16): salt = "" for i in range(int(length)): salt += random.choice(chars) return salt #def getsalt def generate_random_ssha_password(self): password="".join(random.sample(string.letters+string.digits, 4)) return self.generate_ssha_password(password),password #def generate_random_ssha_password def generate_ssha_password(self,password): salt=self.getsalt() return "{SSHA}" + base64.encodestring(hashlib.sha1(str(password) + salt).digest() + salt) #def generate_ssha_password def getLliurexVariables(self): p1=subprocess.Popen(["llxcfg-listvars","--values"],stdout=subprocess.PIPE) output=p1.communicate()[0] output=output.replace("'","") tmp1=output.split(';\n') for item in tmp1: tmp2=item.split('=',1) if len(tmp2)>1: self.llxvar[tmp2[0]]=tmp2[1] # getLliurexVariables def generate_uid(self,name,surname): name_list=name.split(" ") surname_list=surname.split(" ") uid="" for i in range(0,len(name_list[0])): uid=uid+name_list[0][i] if len(uid)==3: break last_surname=len(surname_list)-1 for i in range(0,len(surname_list[last_surname])): uid=uid+surname_list[last_surname][i] if len(uid)==6: break return uid #def generateUid def parseGescen(self,path): document=xml.etree.ElementTree.parse(path) root=document.getroot() alumnes=[] cursos=[] for node in root: if node.tag=="alumnes": alumnes=node.getchildren() if node.tag=="grups": cursos=node.getchildren() parsed_subjects=[] if len(cursos)>0: for curs in cursos: subject=GescenItem() items=curs.getchildren() for item in items: subject.attributes[item.tag]=item.text parsed_subjects.append(subject) parsed_students=[] if len(alumnes)>0: for alumne in alumnes: student=GescenItem() items=alumne.getchildren() for item in items: student.attributes[item.tag]=item.text parsed_students.append(student) if len(parsed_subjects)>0: for subject in parsed_subjects: codi=unicode(subject.attributes["codi"]).encode("ascii") nom=unicode(subject.attributes["nom"]).encode("utf-8") prop={} prop["cn"]=codi prop["description"]=nom prop["x-lliurex-grouptype"]="itaca" self.add_group(prop) if len(parsed_students)>0: for student in parsed_students: name_utf_encoded=False surname_utf_encoded=False name=strip_accents(unicode(student.attributes["nom"])).lower() name=unicode(name).encode("ascii") surname=strip_accents(unicode(student.attributes["cognoms"])).lower() surname=unicode(surname).encode("ascii") # // Generate uid uid=self.generate_uid(name,surname) ''' uid="" count=0 for char in name: if count<3: uid=uid+char count+=1 else: break count=0 for char in surname: if count<3: uid=uid+char count+=1 else: break ''' # // Generate uid group=unicode(student.attributes["grup"]).encode("ascii") if uid.find(" ")!=-1: uid=uid.replace(" ","") name=unicode(student.attributes["nom"]).encode("utf-8") surname=unicode(student.attributes["cognoms"]).encode("utf-8") properties={} properties["uid"]=uid properties["cn"]=name properties["sn"]=surname properties["password"]=uid generated_user=self.add_user(True,"Students",properties) self.add_to_group_type(group,generated_user["uid"]) #def parseGescen def connect(self): print "[LDAPMANAGER] Connecting to ldap..." url=self.llxvar["LDAP_URI"]+":"+self.llxvar["LDAP_REPLICATOR_PORT"] print url self.ldap=ldap.initialize(url) self.ldap.set_option(ldap.VERSION,ldap.VERSION3) if os.path.exists(LdapManager.LDAP_SECRET1): f=open(LdapManager.LDAP_SECRET1) lines=f.readlines() f.close() password=lines[0].replace("\n","") else: if os.path.exists(LdapManager.LDAP_SECRET2): f=open(LdapManager.LDAP_SECRET2) lines=f.readlines() f.close() password=lines[0].replace("\n","") #path="uid=lliurex," + self.llxvar["LDAP_ADMIN_PEOPLE_BASE_DN"] path="cn=admin,"+self.llxvar["LDAP_BASE_DN"] self.ldap.bind_s(path,password) #self.print_list() #def connect def print_list(self): a=self.ldap.search_s(self.llxvar["LDAP_BASE_DN"],ldap.SCOPE_SUBTREE,'sn='+'*') count=1 for item in a: print count count+=1 print item #def print_list def add_user(self,generic_mode,plantille,properties): print "creando ldapuser..." ''' self.properties["uid"]=uid self.properties["cn"]=givenname self.properties["sn"]=surname ''' uid=properties["uid"] user=LdapUser(properties) ''' if uid=="kha": print "mi amiguin nada mas entrar" print user.attributes ''' cn="" if (plantille=="Students"): user.attributes.append(("sabayonProfileName","student")) p1=subprocess.Popen(["lliurex-userfuncs","llx_get_group_gid","students"],stdout=subprocess.PIPE) output=p1.communicate()[0] gidNumber=output.replace("\n","") user.properties["profile"]="students" user.attributes.append(("gidNumber",str(gidNumber))) user.properties["gidNumber"]=str(gidNumber) cn="stuID" if not properties.has_key("userPassword"): password="".join(random.sample(string.letters+string.digits, 4)) user.attributes.append(("userPassword",password)) user.properties["userPassword"]=password if (plantille=="Teachers"): user.attributes.append(("sabayonProfileName","teacher")) p1=subprocess.Popen(["lliurex-userfuncs","llx_get_group_gid","teachers"],stdout=subprocess.PIPE) output=p1.communicate()[0] gidNumber=output.replace("\n","") user.attributes.append(("gidNumber",str(gidNumber))) user.properties["gidNumber"]=str(gidNumber) user.properties["profile"]="teachers" cn="teaID" if not properties.has_key("userPassword"): ssha_password,password=self.generate_random_ssha_password() user.attributes.append(("userPassword",ssha_password)) user.properties["userPassword"]=password if (plantille=="Other"): user.attributes.append(("sabayonProfileName","other")) p1=subprocess.Popen(["lliurex-userfuncs","llx_get_group_gid","others"],stdout=subprocess.PIPE) output=p1.communicate()[0] gidNumber=output.replace("\n","") user.attributes.append(("gidNumber",str(gidNumber))) user.properties["gidNumber"]=str(gidNumber) user.properties["profile"]="others" cn="otID" if not properties.has_key("userPassword"): ssha_password,password=self.generate_random_ssha_password() user.attributes.append(("userPassword",ssha_password)) user.properties["userPassword"]=password path="uid="+user.uid+","+ "ou="+plantille+",ou=People," + self.llxvar["LDAP_BASE_DN"] user.properties["path"]=path uidNumber=self.get_next_id(cn) user.attributes.append(("uidNumber",str(uidNumber))) user.properties["uidNumber"]=str(uidNumber) ''' if uid=="kha": print "mi amiguin al ir a añadir" print user.attributes ''' # ADD USER print "añadiendo ldapuser..." try: #print user.attributes if generic_mode: user_list=self.search_user(uid) if len(user_list)>0: print user.attributes raise ldap.ALREADY_EXISTS self.ldap.add_s(path,user.attributes) self.set_next_id(cn) group_list=self.add_to_generic_groups(plantille,user) if group_list!=None: user.properties["groups"]=group_list print "añadido ok" return user.properties except Exception as exc: print exc if type(exc)==ldap.ALREADY_EXISTS: if not generic_mode: return exc[0]["desc"] else: count=0 integer_found=False counter=len(uid)-1 for pos in range(-len(uid)+1,1): try: integer=int(uid[pos*-1]) counter-=1 except: break uid=uid[:counter+1] ''' for char in uid: try: integer=int(char) integer_found=True break except: count+=1 if integer_found: uid=uid[:count] ''' print "Finding out which is the last " + uid + " entry..." user_list=self.search_user(uid+"*") index_list=[] for item in user_list: list=item.uid.split(uid) if len(list)>1 and len(list[1])>0: try: lets_try=int(list[1]) index_list.append(list[1]) except: pass index_list.sort() if len(index_list)>0: id=int(index_list[len(index_list)-1]) id+=1 else: id=1 value=str(id) if id<10: value="0"+str(id) nonum_uid=uid uid=uid+value print "Calculated uid: " + uid new_uid=uid new_cn=uid new_sn=uid new_description=new_cn + " " + new_sn new_attributes=[] for attribute in user.attributes: x,y=attribute if x=="uid": new_uid=uid y=new_uid if x=="homeDirectory": y=base_home_dir+new_uid new_home=y if generic_mode: if x=="userPassword": pass if x=="cn": if y.find(nonum_uid)!=-1: y=new_uid if x=="sn": if y.find(nonum_uid)!=-1: y=new_uid if x=="description": if y.find(nonum_uid)!=-1: y=new_description #print x,y #print attribute new_attributes.append((x,y)) user.attributes=new_attributes user.uid=new_uid user.properties["uid"]=new_uid user.properties["homeDirectory"]=new_home path="uid="+user.uid+","+ "ou="+plantille+",ou=People," + self.llxvar["LDAP_BASE_DN"] user.properties["path"]=path try: print "Adding " + new_uid + " ..." self.ldap.add_s(path,user.attributes) print "Done" self.set_next_id(cn) group_list=self.add_to_generic_groups(plantille,user) if group_list!=None: user.properties["groups"]=group_list else: print "algo ha ido mal" return user.properties except Exception as inst: print inst return inst[0]["desc"] else: return exc[0]["desc"] #def add_user_def def set_next_id(self,cn,gidNumber=None): if gidNumber==None: mod=( ldap.MOD_REPLACE, 'gidNumber', str(self.get_next_id(cn)+1) ) else: mod=( ldap.MOD_REPLACE, 'gidNumber', str(gidNumber) ) mod_list=[] mod_list.append(mod) path="cn="+cn+",ou=Variables," + self.llxvar["LDAP_BASE_DN"] self.ldap.modify_s(path,mod_list) #def update_user_count_variable def get_next_id(self,cn): path="cn="+cn+",ou=Variables," + self.llxvar["LDAP_BASE_DN"] a=self.ldap.search_s(path,ldap.SCOPE_SUBTREE) for x,y in a: if y.has_key('gidNumber'): return int(y['gidNumber'][0]) #def get_next_id def modify_value(self,path,field,value): mod=( ldap.MOD_REPLACE, field, value ) mod_list=[] mod_list.append(mod) try: self.ldap.modify_s(path,mod_list) return "true" except Exception as e: return e[0]["desc"] #def modify_value def change_group_description(self,gid,description): mod=( ldap.MOD_REPLACE, "description", description ) mod_list=[] mod_list.append(mod) path="cn="+gid+",ou=Managed,ou=Group," + self.llxvar["LDAP_BASE_DN"] try: self.ldap.modify_s(path,mod_list) return "true" except Exception as e: #print e return e[0]["desc"] #def change_group_description def change_student_name(self,uid,name): print "change student name!!!!!!" mod=( ldap.MOD_REPLACE, "cn", name ) mod_list=[] mod_list.append(mod) path="uid="+uid+","+ "ou=Students,ou=People," + self.llxvar["LDAP_BASE_DN"] try: self.ldap.modify_s(path,mod_list) return "true" except Exception as e: #print e return e[0]["desc"] #def change_student_name def change_student_surname(self,uid,surname): #surname=unicode(surname).encode("utf-8") mod=( ldap.MOD_REPLACE, "sn", surname ) mod_list=[] mod_list.append(mod) path="uid="+uid+","+ "ou=Students,ou=People," + self.llxvar["LDAP_BASE_DN"] try: self.ldap.modify_s(path,mod_list) return "true" except Exception as e: return e[0]["desc"] #def change_student_name def change_password(self,path,password): try: password=unicode(password).encode("utf-8") if path.find("Students")!=-1: self.modify_value(path,"userPassword",password) else: self.modify_value(path,"userPassword",self.generate_ssha_password(password)) return "true" except Exception as e: return e[0]["desc"] #def modify_value def change_user_password(self,uid,password): students="ou=Students,ou=People," + self.llxvar["LDAP_BASE_DN"] path="uid="+uid+","+students return self.change_password(path,password) #def change_student_password def generic_student_to_itaca(self,uid,nia): print "si si, vamos a ver" students="ou=Students,ou=People," + self.llxvar["LDAP_BASE_DN"] path="uid="+uid+","+students try: mod_list=[] print "per que 0" mod=( ldap.MOD_REPLACE, "x-lliurex-usertype", "itaca" ) print "per que 1" mod_list.append(mod) print "per que" mod=( ldap.MOD_ADD, "x-lliurex-nia", str(nia) ) mod_list.append(mod) print "vamos a ver" self.ldap.modify_s(path,mod_list) print "okay makey" return "true" except Exception as e: return e[0]["desc"] #def generic_student_to_itaca def generic_teacher_to_itaca(self,uid,nif): teachers="ou=Teachers,ou=People," + self.llxvar["LDAP_BASE_DN"] path="uid="+uid+","+teachers try: mod_list=[] mod=( ldap.MOD_REPLACE, "x-lliurex-usertype", "itaca" ) mod_list.append(mod) mod=( ldap.MOD_ADD, "x-lliurex-nif",str(nif) ) mod_list.append(mod) self.ldap.modify_s(path,mod_list) return "true" except Exception as e: return e[0]["desc"] #def generic_student_to_itaca def add_generic_users(self,plantille,group_type,number,generic_name,pwd_generation_type,pwd=None): generated_users=[] for i in range(number): tmp_i=i+1 val=str(tmp_i) if tmp_i < 10: val="0"+str(tmp_i) user_name=generic_name+ val properties={} properties["uid"]=user_name properties["cn"]=user_name properties["sn"]=user_name properties["x-lliurex-usertype"]="generic" user=LdapUser(properties) generated_pwd="" if(pwd_generation_type==LdapManager.RANDOM_PASSWORDS): generated_pwd="".join(random.sample(string.letters+string.digits, 4)) password=generated_pwd ok=True if(pwd_generation_type==LdapManager.SAME_PASSWORD): if(pwd!=None): password=pwd generated_pwd=password else: print "No password was given" break if(pwd_generation_type==LdapManager.PASS_EQUALS_USER): password=user_name generated_pwd=password print "Adding user..." properties={} properties["uid"]=user_name properties["cn"]=user_name properties["sn"]=user_name properties["password"]=password generated_dic=self.add_user(True,plantille,properties) if type(generated_dic)==str: dic={} dic["ERROR"]=user_name + ":" + generated_dic generated_users.append(dic) else: if pwd_generation_type==LdapManager.PASS_EQUALS_USER: user_path=generated_dic["path"] generated_dic["userPassword"]=generated_dic["uid"] self.change_password(user_path,generated_dic["userPassword"]) generated_pwd=generated_dic["userPassword"] else: generated_dic["userPassword"]=generated_pwd if generated_dic!=None: if group_type!=None: self.add_to_group_type(group_type,generated_dic["uid"]) generated_dic["groups"].append(group_type) generated_users.append(generated_dic) return generated_users #def add_generic_users def add_to_generic_groups(self,plantille,user): teachers="cn=teachers,ou=Profiles,ou=Group," + self.llxvar["LDAP_BASE_DN"] students="cn=students,ou=Profiles,ou=Group," + self.llxvar["LDAP_BASE_DN"] others="cn=others,ou=Profiles,ou=Group," + self.llxvar["LDAP_BASE_DN"] user_path="uid="+user.uid+",ou="+plantille+",ou=People," + self.llxvar["LDAP_BASE_DN"] teachers_groups=["dialout","cdrom","floppy","audio","dip","video","plugdev","netdev","vboxusers","tcos","tcosmonitor-exclude","fuse"] students_groups=["dialout","cdrom","floppy","audio","dip","video","plugdev","netdev","vboxusers","fuse"] if(plantille=="Teachers"): mod=(ldap.MOD_ADD,'member',user_path) mod_list=[] mod_list.append(mod) mod2=(ldap.MOD_ADD,'memberUid',user.uid) mod_list.append(mod2) try: self.ldap.modify_s(teachers,mod_list) for group in teachers_groups: mod=(ldap.MOD_ADD,"memberUid",user.uid) mod_list=[] mod_list.append(mod) group_path="cn=" + group +",ou=System,ou=Group," + self.llxvar["LDAP_BASE_DN"] self.ldap.modify_s(group_path,mod_list) teachers_groups.append("teachers") return teachers_groups except Exception as e: print e return None if(plantille=="Students"): mod=(ldap.MOD_ADD,'member',user_path) mod_list=[] mod_list.append(mod) mod2=(ldap.MOD_ADD,'memberUid',user.uid) mod_list.append(mod2) try: self.ldap.modify_s(students,mod_list) for group in students_groups: mod=(ldap.MOD_ADD,"memberUid",user.uid) mod_list=[] mod_list.append(mod) group_path="cn=" + group +",ou=System,ou=Group," + self.llxvar["LDAP_BASE_DN"] self.ldap.modify_s(group_path,mod_list) students_groups.append("students") return students_groups except Exception as e: print e return None if(plantille=="Other"): mod=(ldap.MOD_ADD,'member',user_path) mod_list=[] mod_list.append(mod) try: self.ldap.modify_s(others,mod_list) for group in students_groups: mod=(ldap.MOD_ADD,"memberUid",user.uid) mod_list=[] mod_list.append(mod) group_path="cn=" + group +",ou=System,ou=Group," + self.llxvar["LDAP_BASE_DN"] self.ldap.modify_s(group_path,mod_list) students_groups.append("others") return students_groups except Exception as e: print e return None #def add_to_generic_groups def add_to_group_type(self,cn,uid): path="cn=" + cn + ",ou=Managed,ou=Group," + self.llxvar["LDAP_BASE_DN"] mod=(ldap.MOD_ADD,'memberUid',uid) mod_list=[] mod_list.append(mod) print "*** ADDING " + uid + " to " + path try: self.ldap.modify_s(path,mod_list) return "true" except Exception as e: return e[0]["desc"] #def add_to_group_type def add_teacher_to_admins(self,uid): path="cn=admins,ou=Profiles,ou=Group," + self.llxvar["LDAP_BASE_DN"] user_dn="uid="+uid+",ou=Teachers,ou=People," + self.llxvar["LDAP_BASE_DN"] mod=(ldap.MOD_ADD,"member",user_dn) mod_list=[] mod_list.append(mod) mod=(ldap.MOD_ADD,"memberUid",uid) mod_list.append(mod) print "*** ADDING " + uid + " to admins" try: self.ldap.modify_s(path,mod_list) return "true" except Exception as e: if type(e)==ldap.TYPE_OR_VALUE_EXISTS: return "true" else: return e[0]["desc"] #def add_teacher_to_admins def del_teacher_from_admins(self,uid): path="cn=admins,ou=Profiles,ou=Group," + self.llxvar["LDAP_BASE_DN"] user_dn="uid="+uid+",ou=Teachers,ou=People," + self.llxvar["LDAP_BASE_DN"] mod=(ldap.MOD_DELETE,"member",user_dn) mod_list=[] mod_list.append(mod) mod=(ldap.MOD_DELETE,"memberUid",uid) mod_list.append(mod) print "*** DELETING " + uid + " from admins" try: self.ldap.modify_s(path,mod_list) return "true" except Exception as e: if type(e)==ldap.NO_SUCH_ATTRIBUTE: return "true" else: return e[0]["desc"] #def del_teacher_from_admins def search_user(self,uid): #ou=Students,ou=People result=self.ldap.search_s("ou=People,"+self.llxvar["LDAP_BASE_DN"],ldap.SCOPE_SUBTREE,"uid="+uid) user_list=[] path="ou=Managed,ou=Group,"+self.llxvar["LDAP_BASE_DN"] group_result=self.ldap.search_s(path,ldap.SCOPE_SUBTREE) for item in result: path,properties_dic=item group_list=[] for group in group_result: g_path,dic=group if "memberUid" in dic: if properties_dic["uid"][0] in dic["memberUid"]: tmp=g_path.split(",") cn=tmp[0].split("=")[1] group_list.append(cn) prop={} prop["uid"]=properties_dic["uid"][0] prop["cn"]=properties_dic["cn"][0] prop["sn"]=properties_dic["sn"][0] user=LdapUser(prop) if path.find("Student")!=-1: user.properties["profile"]="students" if path.find("Teacher")!=-1: user.properties["profile"]="teachers" if path.find("Other")!=-1: user.properties["profile"]="others" if path.find("Admin")!=-1: user.properties["profile"]="admin" user.properties["uidNumber"]=properties_dic["uidNumber"][0] user.properties["gidNumber"]=properties_dic["gidNumber"][0] user.properties["path"]=path user.properties["groups"]=group_list if properties_dic.has_key("x-lliurex-usertype"): user.properties["x-lliurex-usertype"]=properties_dic["x-lliurex-usertype"][0] if properties_dic.has_key("x-lliurex-nia"): user.properties["x-lliurex-nia"]=properties_dic["x-lliurex-nia"][0] if properties_dic.has_key("x-lliurex-nif"): user.properties["x-lliurex-nif"]=properties_dic["x-lliurex-nif"][0] user_list.append(user) return user_list #def search_user def light_search(self): result=self.ldap.search_s("ou=People,"+self.llxvar["LDAP_BASE_DN"],ldap.SCOPE_SUBTREE,"uid=*") user_list=[] for item in result: path,properties_dic=item desc="" if "description" in properties_dic: desc=properties_dic["description"][0] profile="" if path.find("Student")!=-1: profile="students" if path.find("Teacher")!=-1: profile="teachers" if path.find("Other")!=-1: profile="others" if path.find("Admin")!=-1: profile="admin" #user_list.append((properties_dic["uid"][0],path,properties_dic["cn"][0],properties_dic["sn"][0],desc)) user_list.append((path,properties_dic["uid"][0],properties_dic["uidNumber"][0],properties_dic["cn"][0],properties_dic["sn"][0],profile)) return user_list #def light_search def search_user_with_filter(self,filter): listldapusers=self.ldap.search_s("ou=People,"+self.llxvar["LDAP_BASE_DN"],ldap.SCOPE_SUBTREE,filter) result = {} for x in listldapusers: upgradeuser = {} for key,value in x[1].items(): if len(value) == 1: upgradeuser[key] = value[0] else: upgradeuser[key] = value upgradeuser['profile'] = x[1]['sabayonProfileName'][0]+"s" result[upgradeuser['uid']] = upgradeuser return result def search_user_dic(self,uid): #ou=Students,ou=People result=self.ldap.search_s("ou=People,"+self.llxvar["LDAP_BASE_DN"],ldap.SCOPE_SUBTREE,"uid="+uid) user_list=[] for item in result: path,properties_dic=item prop={} prop["uid"]=properties_dic["uid"][0] prop["cn"]=properties_dic["cn"][0] prop["sn"]=properties_dic["sn"][0] user=LdapUser(prop) user.properties["path"]=path user_list.append(user.properties) return user_list def search_students(self,uid): #ou=Students,ou=People result=self.ldap.search_s("ou=Students,ou=People,"+self.llxvar["LDAP_BASE_DN"],ldap.SCOPE_SUBTREE,"uid="+uid) user_list=[] for item in result: path,properties_dic=item prop={} prop["uid"]=properties_dic["uid"][0] prop["cn"]=properties_dic["cn"][0] prop["sn"]=properties_dic["sn"][0] user=LdapUser(prop) user.properties["path"]=path user_list.append(user) return user_list #def search_user def search_teachers(self,uid): #ou=Students,ou=People result=self.ldap.search_s("ou=Teachers,ou=People,"+self.llxvar["LDAP_BASE_DN"],ldap.SCOPE_SUBTREE,"uid="+uid) user_list=[] for item in result: path,properties_dic=item prop={} prop["uid"]=properties_dic["uid"][0] prop["cn"]=properties_dic["cn"][0] prop["sn"]=properties_dic["sn"][0] user=LdapUser(prop) user.properties["path"]=path user_list.append(user) return user_list #def search_user def delete_user(self,uid): user=self.search_user(uid) if user[0].properties["path"].find("Students")!=-1: print "delete student" try: user[0].properties["groups"]=self.get_generic_groups(uid) user[0].properties["groups"].append("students") self.delete_student(uid) return user[0].properties except: return None if user[0].properties["path"].find("Teachers")!=-1: print "delete teacher" try: user[0].properties["groups"]=self.get_generic_groups(uid) user[0].properties["groups"].append("students") self.delete_teacher(uid) return user[0].properties except: return None #def delete_user def delete_student(self,uid): try: group_list=self.get_groups(uid) #print group_list for group in group_list: self.del_user_from_group(uid,group) path="uid="+uid+",ou=Students,ou=People,"+self.llxvar["LDAP_BASE_DN"] group_list=self.get_generic_groups(uid) #print group_list for group in group_list: self.del_user_from_generic_group(uid,group) self.del_student_from_student_group(uid) print "Deleting " + uid + " : " + path self.ldap.delete_s(path) return "true" except Exception as e: return e[0]['desc'] #def delete_user def delete_other(self,uid): try: group_list=self.get_groups(uid) #print group_list for group in group_list: self.del_user_from_group(uid,group) path="uid="+uid+",ou=Other,ou=People,"+self.llxvar["LDAP_BASE_DN"] group_list=self.get_generic_groups(uid) #print group_list for group in group_list: self.del_user_from_generic_group(uid,group) self.del_student_from_student_group(uid) print "Deleting " + uid + " : " + path self.ldap.delete_s(path) return "true" except Exception as e: return e[0]['desc'] #def delete_user def delete_teacher(self,uid): try: group_list=self.get_groups(uid) #print group_list for group in group_list: self.del_user_from_group(uid,group) path="uid="+uid+",ou=Teachers,ou=People,"+self.llxvar["LDAP_BASE_DN"] group_list=self.get_generic_groups(uid) #print group_list for group in group_list: self.del_user_from_generic_group(uid,group) self.del_teacher_from_teacher_group(uid) print "Deleting " + uid + " : " + path self.ldap.delete_s(path) return "true" except Exception as e: return e[0]['desc'] #def delete_user def get_groups(self,uid): path="ou=Managed,ou=Group,"+self.llxvar["LDAP_BASE_DN"] result=self.ldap.search_s(path,ldap.SCOPE_SUBTREE) group_list=[] for group in result: g_path,dic=group if "memberUid" in dic: if uid in dic["memberUid"]: tmp=g_path.split(",") cn=tmp[0].split("=")[1] group_list.append(cn) return group_list #def get_groups def get_available_groups(self): path="ou=Managed,ou=Group,"+self.llxvar["LDAP_BASE_DN"] result=self.ldap.search_s(path,ldap.SCOPE_SUBTREE) group_list=[] for group in result: g_path,dic=group dic["path"]=g_path if "posixGroup" in dic["objectClass"]: group_list.append(dic) return group_list #def get_available_groups def get_generic_groups(self,uid): path="ou=System,ou=Group,"+self.llxvar["LDAP_BASE_DN"] result=self.ldap.search_s(path,ldap.SCOPE_SUBTREE) group_list=[] for group in result: g_path,dic=group if "memberUid" in dic: if uid in dic["memberUid"]: tmp=g_path.split(",") cn=tmp[0].split("=")[1] group_list.append(cn) return group_list #def get_generic_groups def del_student_from_student_group(self,uid): path="cn=students,ou=Profiles,ou=Group," + self.llxvar["LDAP_BASE_DN"] user_dn="uid=" + uid + ",ou=Students,ou=People," + self.llxvar["LDAP_BASE_DN"] #print user_dn mod=(ldap.MOD_DELETE,"member",user_dn) mod_list=[] mod_list.append(mod) mod=(ldap.MOD_DELETE,"memberUid",uid) mod_list.append(mod) print "\tRemoving " + uid + " from " + path try: self.ldap.modify_s(path,mod_list) except Exception as e: return e[0]['desc'] #def del_student_from_student_group def del_teacher_from_teacher_group(self,uid): path="cn=teachers,ou=Profiles,ou=Group," + self.llxvar["LDAP_BASE_DN"] user_dn="uid=" + uid + ",ou=Teachers,ou=People," + self.llxvar["LDAP_BASE_DN"] #print user_dn mod=(ldap.MOD_DELETE,"member",user_dn) mod_list=[] mod_list.append(mod) mod=(ldap.MOD_DELETE,"memberUid",uid) mod_list.append(mod) print "\tRemoving " + uid + " from " + path try: self.ldap.modify_s(path,mod_list) except Exception as e: return e[0]["desc"] #def del_student_from_student_group def del_user_from_group(self,uid,group_cn): mod=(ldap.MOD_DELETE,"memberUid",uid) mod_list=[] mod_list.append(mod) path="cn="+group_cn+",ou=Managed,ou=Group,"+self.llxvar["LDAP_BASE_DN"] print "\tRemoving " +uid + " from " + path try: self.ldap.modify_s(path,mod_list) return "true" except Exception as e: #print e return e[0]["desc"] #def del_user_from_group def del_user_from_generic_group(self,uid,group_cn): mod=(ldap.MOD_DELETE,"memberUid",uid) mod_list=[] mod_list.append(mod) path="cn="+group_cn+",ou=System,ou=Group,"+self.llxvar["LDAP_BASE_DN"] print "\tRemoving " +uid + " from " + path try: self.ldap.modify_s(path,mod_list) except Exception as e: return e[0]["desc"] #def del_user_from_group def add_group(self,properties): path="cn="+str(properties["cn"])+",ou=Managed,ou=Group," + self.llxvar["LDAP_BASE_DN"] print path group=LdapGroup(properties) try: gidNumber=self.get_next_id("nextID") group.attributes.append(("gidNumber",str(self.get_next_id("nextID")))) self.set_next_id("nextID") print "Adding group : " + path self.ldap.add_s(path,group.attributes) return "true" except Exception as e: print "algo esta pasando" print e return e[0]["desc"] #def add_group def print_group_list(self,cn): a=self.ldap.search_s(self.llxvar["LDAP_BASE_DN"],ldap.SCOPE_SUBTREE,"cn="+cn) count=1 for item in a: #print count count+=1 print item #def print_list def search_group(self,cn): result=self.ldap.search_s("ou=Managed,ou=Group,"+self.llxvar["LDAP_BASE_DN"],ldap.SCOPE_SUBTREE,"cn="+cn) group_list=[] for item in result: path,properties_dic=item prop={} prop["cn"]=cn group=LdapGroup(prop) group.properties["path"]=path if "memberUid" in properties_dic: group.properties["memberUid"]=properties_dic["memberUid"] group_list.append(group) return group_list #def search_group def get_dn(self,uid): result=self.ldap.search_s("ou=People,"+self.llxvar["LDAP_BASE_DN"],ldap.SCOPE_SUBTREE,"uid="+uid) user_list=[] path="ou=Managed,ou=Group,"+self.llxvar["LDAP_BASE_DN"] group_result=self.ldap.search_s(path,ldap.SCOPE_SUBTREE) for item in result: path,properties_dic=item return path #def get_dn def get_students_passwords(self): result=self.ldap.search_s("ou=Students,ou=People,"+self.llxvar["LDAP_BASE_DN"],ldap.SCOPE_SUBTREE,"uid=*") ret_list = [] for item in result: path,dic=item user={} if dic.has_key("userPassword"): user['passwd']=dic["userPassword"][0] if dic.has_key("sn"): user['sn']=dic["sn"][0] if dic.has_key("userPassword"): user['cn']=dic["cn"][0] if dic.has_key("userPassword"): user['uid']=dic["uid"][0] ret_list.append(user) return ret_list #def get_students_passwords def delete_group(self,cn): path="cn=" + cn + ",ou=Managed,ou=Group," + self.llxvar["LDAP_BASE_DN"] print "Deleting group " + path try: self.ldap.delete_s(path) return "true" except Exception as e: return e[0]["desc"] #def delete_group ''' uid_list : list no_group_user : Boolean ''' def freeze_user(self,uid_list,no_group_user=True): path="cn=freeze," + self.llxvar["LDAP_PROFILES_GROUP_BASE_DN"] # list of users freeze correctly for latter add group calipro users_freeze = [] result = [] for uid in uid_list: if uid != None and len(uid) > 0 : try : mod_list=[] mod=(ldap.MOD_ADD,'memberUid',uid) mod_list.append(mod) print "*** ADDING " + uid + " to " + path self.ldap.modify_s(path,mod_list) users_freeze.append(uid) if not no_group_user: result.append({"uid" : uid,"success" : "True"}) except Exception as exc: print (exc[0]['desc']) if type(exc) != ldap.TYPE_OR_VALUE_EXISTS : result.append({"uid" : uid,"success" : exc[0]['desc']}) else: users_freeze.append(uid) if not no_group_user: result.append({"uid" : uid,"success" : "True"}) if no_group_user : path="cn=calipro," + self.llxvar["LDAP_PROFILES_GROUP_BASE_DN"] mod_list=[] for uid in users_freeze: try: mod_list=[] mod=(ldap.MOD_ADD,'memberUid',uid) mod_list.append(mod) print "*** ADDING " + uid + " to " + path self.ldap.modify_s(path,mod_list) result.append({"uid" : uid,"success":"True"}) except Exception as exc: print exc[0]['desc'] if type(exc) == ldap.TYPE_OR_VALUE_EXISTS : result.append({"uid" : uid,"success":"True"}) else: result.append({"uid" : uid,"success" :exc[0]['desc']}) # Correctly freeze users # result is list [ {uid : string , success : sting } , {...} ] return result #def freeze_user ''' cn : string ''' def freeze_group(self,cn): path="cn=flux," + self.llxvar["LDAP_PROFILES_GROUP_BASE_DN"] result = {} if cn != None and len(cn) > 0 : cn_group="cn=" + cn + "," + self.llxvar["LDAP_MANAGED_GROUP_BASE_DN"] try : mod=(ldap.MOD_ADD,'member',cn_group) mod_list=[] mod_list.append(mod) print "*** ADDING " + cn + " to " + path self.ldap.modify_s(path,mod_list) result["success"] = "True" except Exception as exc: print exc[0]['desc'] if type(exc) == ldap.TYPE_OR_VALUE_EXISTS : result["success"] = "True" else: result["success"] = exc[0]['desc'] result["success"] = [] return result group = self.search_group(cn) if len(group) > 0 : list_users = [] for uid in group[0].properties["memberUid"]: list_users.append(uid) result["users"] = self.freeze_user(list_users,False) else: result["success"] = "Group not exist" result["users"] = [] else: result["success"] = "Invalid cn" result["users"] = [] # # result is {success : string ,users : list [ { uid : string, success : sting } , {...} ] # return result #def freeze_group ''' uid_list : list no_group_user : Boolean ''' def unfreeze_user(self,uid_list,no_group_user=True): path="cn=freeze," + self.llxvar["LDAP_PROFILES_GROUP_BASE_DN"] # list of users freeze correctly for latter add group calipro users_freeze = [] result = [] for uid in uid_list: if uid != None and len(uid) > 0 : try: mod_list=[] mod=(ldap.MOD_DELETE,'memberUid',uid) mod_list.append(mod) print "*** DELETING " + uid + " to " + path self.ldap.modify_s(path,mod_list) users_freeze.append(uid) if not no_group_user: result.append({"uid" : uid,"success" : "True"}) except Exception as exc: print (exc[0]['desc']) if type(exc) != ldap.NO_SUCH_ATTRIBUTE : result.append({"uid" : uid, "success" :exc[0]['desc']}) else: users_freeze.append(uid) if not no_group_user: result.append({"uid" : uid,"success" : "True"}) if no_group_user : path="cn=calipro," + self.llxvar["LDAP_PROFILES_GROUP_BASE_DN"] for uid in users_freeze: try: mod_list=[] mod=(ldap.MOD_DELETE,'memberUid',uid) mod_list.append(mod) print "*** DELETING " + uid + " to " + path self.ldap.modify_s(path,mod_list) result.append({"uid" : uid,"success" : "True"}) except Exception as exc: print exc[0]['desc'] if type(exc) == ldap.NO_SUCH_ATTRIBUTE : result.append({"uid" : uid,"success" : "True"}) else: result.append( { "uid" : uid, "success" : exc[0]['desc']}) # result is list [ {uid : string , success : sting } , {...} ] return result #def unfreeze_user ''' cn : string ''' def unfreeze_group(self,cn): path="cn=flux," + self.llxvar["LDAP_PROFILES_GROUP_BASE_DN"] result = {} if cn != None and len(cn) > 0 : cn_group="cn=" + cn + "," + self.llxvar["LDAP_MANAGED_GROUP_BASE_DN"] try: mod=(ldap.MOD_DELETE,'member',cn_group) mod_list=[] mod_list.append(mod) print "*** DELETING " + cn + " from " + path self.ldap.modify_s(path,mod_list) result["success"] = "True" except Exception as exc: print exc[0]['desc'] if type(exc) == ldap.NO_SUCH_ATTRIBUTE : result["success"] = "True" else: result["success"] = exc[0]['desc'] result["users"] = [] return result group = self.search_group(cn) if len(group) > 0 : list_users = [] for uid in group[0].properties["memberUid"]: list_users.append(uid) result["users"] = self.unfreeze_user(list_users,False) else: result["success"] = "Group not exist" result["users"] = [] else: result["success"] = "Invalid cn" result["users"] = [] # # result is { success : string with success, users : list [ {uid user, sting with success} , {...} ]} # return result #def unfreeze_group def is_freeze_user(self,uid): path = "cn=freeze," + self.llxvar["LDAP_PROFILES_GROUP_BASE_DN"] users = self.ldap.search_s(path,ldap.SCOPE_SUBTREE) for x,y in users: if y.has_key("memberUid"): if uid in y["memberUid"]: return True else: return False # def is_freeze_user #class LdapManager if __name__=="__main__": ldapman=LdapManager(getLliurexVariables()) #ldapman.print_list() #add_generic_users(self,plantille,group_type,number,generic_name,pwd_generation_type,pwd=None) #RANDOM_PASSWORDS #SAME_PASSWORD #PASS_EQUALS_USER print ldapman.add_generic_users("Students",None,1,"kha",ldapman.PASS_EQUALS_USER) #print ldapman.add_teacher_to_admins("micomi") #ldapman.del_teacher_from_admins("profe01") #print ldapman.generate_uid("ana de iratxe","garcia de las torres") ''' list=ldapman.search_user("*") for item in list: print item.properties["uid"] print "" '''