develop
asamoukin 16 years ago
parent 2c9e2cba05
commit daf39f3f3e

@ -144,15 +144,22 @@ imp_cl_smcon = cl_utils2.cl_smartcon
class cl_ldap(imp_cl_err, imp_cl_xml, imp_cl_help, imp_cl_smcon):
"""Основной класс для работы с LDAP"""
def __init__(self, cmdName):
# минимальное и максимальное значение gid-ов системных групп
#(Computers, и.т. д)
self.maxSysGid = 999
self.minSysGid = 900
# объект для форматированного вывода
imp_cl_help.__init__(self, cmdName)
# Базовый DN всех сервисов относительно базового DN
self.servicesRelDN = "ou=Services"
# Базовый DN Samba сервиса относительно DN сервисов
self.sambaDN = "ou=Samba"
# Базовый DN Unix сервиса относительно DN сервисов
self.unixDN = "ou=Unix"
# Базовый DN Samba сервиса относительно базового DN
self.sambaRelDN = "%s,%s" %(self.sambaDN, self.servicesRelDN)
# Базовый DN Samba сервиса относительно базового DN
self.unixRelDN = "%s,%s" %(self.unixDN, self.servicesRelDN)
# Основная группа пользователей LDAP
self.nameBaseGroup = "Services"
# Алгоритм шифрования пароля для LDAP пользователя
@ -225,7 +232,8 @@ class cl_ldap(imp_cl_err, imp_cl_xml, imp_cl_help, imp_cl_smcon):
'helpChapter':_("Common options"),
'help':_("display this help and exit")
},
{'longOption':"help-ldap",
{'progAccess':(6,),
'longOption':"help-ldap",
'helpChapter':_("Common options"),
'help':_("display help options service LDAP")
},
@ -288,6 +296,13 @@ class cl_ldap(imp_cl_err, imp_cl_xml, imp_cl_help, imp_cl_smcon):
'helpChapter':_("Service Unix options"),
'help':_("set the GECOS field for the new user account")
},
{'progAccess':(3,),
'shortOption':"g",
'longOption':"gid",
'optVal':"GROUP",
'helpChapter':_("Service Samba options"),
'help':_("force use GROUP for the new user Unix service account")
},
{'progAccess':(3,),
'shortOption':"w",
'helpChapter':_("Service Samba options"),
@ -485,7 +500,8 @@ class cl_ldap(imp_cl_err, imp_cl_xml, imp_cl_help, imp_cl_smcon):
#'help':_("show enviroment values (filter for type, all - no filter)")
#},
# Services
{'helpChapter':_("Services"),
{'progAccess':(6,),
'helpChapter':_("Services"),
'help':pcs(" ldap", self.column_width,
"ldap " + servName, self.consolewidth-self.column_width)
},
@ -878,6 +894,74 @@ LDAP in backup directory")
clVars.Write("soft_ldap_setup","yes")
return True
def setupUnixServer(self, options):
"""Начальная настройка LDAP сервиса"""
# Принудительная установка
forceOptions = False
if options.has_key("f"):
forceOptions = True
clVars = self.createClVars()
# прервать если была неудачная попытка установить новые параметры
# или были опция вывода на печать
#if not self.processOptionsForDatavars(options,clVars):
#return ""
# В случае если сервер установлен
if clVars.Get("soft_unix_setup") == "yes" and\
not forceOptions:
self.printWARNING (_("WARNING") + ": " +\
_("Unix service is configured")+ ".")
return True
if not clVars.Get("soft_ldap_setup") == "yes":
self.printERROR(_("Service LDAP not setup ..."))
return False
# Проверим запущен ли ldap
if not self.getRunService("ldap"):
self.printWARNING (_("WARNING") + ": " +\
_("The LDAP service is not running") + ".")
print "1. " +_("Start the LDAP service")
print " /etc/init.d/slapd start"
return True
#self.setParamIniFile("setup_LDAP","no")
clVars.Write("soft_unix_setup","no")
# Для тестовых целей устанавливаем директорию инсталяции
#clVars.Set("setup_path_install","/tmp/test1/")
# Cоздаем объект профиль устанавливая директорию ldap для
# файлов профилей
clProf = cl_profile.profile(clVars,"unix")
# Объединяем профили
clProf.applyProfiles()
# Удаляем предыдущую ветку сервиса Unix
ldapObj = self.getLdapObjInFile()
if not ldapObj:
return False
servicesDN = "%s,%s" % (self.servicesRelDN,\
clVars.Get("soft_ldap_base"))
resSearch = ldapObj.ldapSearch(servicesDN, ldap.SCOPE_ONELEVEL,
self.unixDN, [''])
ret = True
if resSearch:
delDN = "%s,%s" %(self.unixDN, servicesDN)
ret = self.deleteDN(delDN, ldapObj)
if ret:
self.printOK(_("Remove Unix DN in LDAP Database ..."))
else:
self.printERROR(_("Not remove Unix DN in LDAP Database ..."))
if not ret:
return False
ldifFile = "/usr/lib/calculate/calculate-server/ldif/unix_base.ldif"
baseLdif = self.createLdif(ldifFile, clVars)
#print baseLdif
#clVars.printVars()
if not ldapObj.getError():
ldapObj.ldapAdd(baseLdif)
if ldapObj.getError():
print _("LDAP Error") + ": " + ldapObj.getError()
return False
self.printOK(_("Add ldif file ..."))
clVars.Write("soft_unix_setup","yes")
self.printOK(_("Unix service configured ..."))
return True
def setupSambaServer(self, options):
"""Начальная настройка Samba сервиса"""
# Принудительная установка
@ -889,9 +973,10 @@ LDAP in backup directory")
# или были опция вывода на печать
#if not self.processOptionsForDatavars(options,clVars):
#return ""
if clVars.Get("soft_ldap_setup") != "yes":
if clVars.Get("soft_unix_setup") != "yes":
self.printERROR (_("ERROR") + ": " +\
_("LDAP server is not configured")+ ".")
self.printWARNING(_("Not setup service Unix"))
return False
# В случае если сервер установлен
if clVars.Get("soft_samba_setup") == "yes" and\
@ -959,7 +1044,7 @@ Samba in backup directory")
if ret:
self.printOK(_("Remove Samba DN in LDAP Database ..."))
else:
self.printERROR(_("Remove Samba DN in LDAP Database ..."))
self.printERROR(_("Not remove Samba DN in LDAP Database ..."))
if not ret:
return False
@ -1032,7 +1117,8 @@ Samba in backup directory")
return False
machineLogin = machineName.replace('$','') + "$"
groupName = clVars.Get('soft_ldap_machine_group_name')
groupId = clVars.Get('soft_ldap_machine_gid')
# Находим следующий номер в диапазоне системных групп
groupId = str(self.getMaxGidSystem(ldapObj, clVars))
if not self.searchLdapGroupName(groupName, ldapObj, clVars):
res = self.searchLdapGid(groupId, ldapObj, clVars)
maxGid = self.getUidMax()
@ -1050,19 +1136,13 @@ Samba in backup directory")
_("not foung free GID in ldap") + userGid)
return False
groupId = str(numberGid)
clVars.Write('soft_ldap_machine_gid', groupId)
options = {'g':groupId,'c':'Computer group'}
if not self.addGroupLdapServer(groupName, options, clVars):
return False
clVars.Set('soft_ldap_machine_login',machineLogin)
# Находим последний добавленный id компьютера
maxIdMachine = self.getMaxUidLdap(ldapObj, clVars, "ou=Computers")
idMachineStart = int(clVars.Get('soft_ldap_machine_id'))
if maxIdMachine:
userIdNumber = maxIdMachine + 1
else:
userIdNumber = idMachineStart
clVars.Set('soft_ldap_machine_id',str(userIdNumber))
# Находим последний добавленный id
userIdNumber = str(self.getMaxUid(ldapObj, clVars))
clVars.Set('soft_ldap_machine_id',userIdNumber)
clVars.Set('soft_ldap_machine_gid',groupId)
ldifFile="/usr/lib/calculate/calculate-server/ldif/samba_machine.ldif"
userLdif = self.createLdif(ldifFile, clVars)
@ -1084,7 +1164,8 @@ Samba in backup directory")
modAttrs = [(ldap.MOD_DELETE, 'memberUid', userName)]
try:
ldapObj.conLdap.modify_s("cn=%s,%s,%s"\
%(groupName,"ou=Groups",clVars.Get("soft_ldap_base")),
%(groupName,"ou=Groups",
self.unixRelDN,clVars.Get("soft_ldap_base")),
modAttrs)
except ldap.LDAPError, e:
self.printERROR(e[0]['desc'])
@ -1142,7 +1223,7 @@ Samba in backup directory")
def delUserLdapServer(self, userName, options, clVars=False,
orgUnit="ou=Users"):
orgUnit="ou=Users,ou=Unix,ou=Services"):
"""Удаляем LDAP пользователя"""
clVars = self.createClVars(clVars)
ldapObj = self.getLdapObjInFile()
@ -1350,11 +1431,11 @@ Samba in backup directory")
if resLdap:
userGid = resLdap[0][0][1]['gidNumber'][0]
else:
if not self.addGroupLdapServer(self.nameBaseGroup,{},clVars):
if not self.addGroupLdapServer(userName,{},clVars):
return False
clVars.Set("soft_ldap_user_gid",userGid)
ldifFile = "/usr/lib/calculate/calculate-server/ldif/ldap_user.ldif"
ldifFile = "/usr/lib/calculate/calculate-server/ldif/unix_user.ldif"
userLdif = self.createLdif(ldifFile, clVars)
#ldifFile1 = \
#"/usr/lib/calculate/calculate-server/ldif/ldap_account.ldif"
@ -1422,8 +1503,10 @@ Samba in backup directory")
modAttrs.append((ldap.MOD_ADD, 'memberUid', userName))
if modAttrs:
try:
ldapObj.conLdap.modify_s("cn=%s,ou=Groups,%s"\
%(groupName,clVars.Get("soft_ldap_base")), modAttrs)
ldapObj.conLdap.modify_s("cn=%s,ou=Groups,%s,%s"\
%(groupName,
self.unixRelDN,
clVars.Get("soft_ldap_base")), modAttrs)
except ldap.LDAPError, e:
self.printERROR(e[0]['desc'])
return False
@ -1478,7 +1561,7 @@ Samba in backup directory")
gecos = options['c']
clVars.Set("soft_ldap_group_desc",gecos)
ldifFile = "/usr/lib/calculate/calculate-server/ldif/ldap_group.ldif"
ldifFile = "/usr/lib/calculate/calculate-server/ldif/unix_group.ldif"
userLdif = self.createLdif(ldifFile, clVars)
if not userLdif:
print self.getError()
@ -1495,7 +1578,7 @@ Samba in backup directory")
return True
def delGroupLdapServer(self, groupName, options, clVars=False,
orgUnit="ou=Groups"):
orgUnit="ou=Groups,ou=Unix,ou=Services"):
"""Удаляет группу пользователей LDAP"""
clVars = self.createClVars(clVars)
@ -1510,8 +1593,8 @@ Samba in backup directory")
return False
groupId = res[0][0][1]['gidNumber'][0]
if self.searchLdapUserPrimGroup(groupId, ldapObj, clVars):
self.printERROR(_("cannot remove user's primary group") + ".")
return False
self.printWARNING(_("cannot remove user's primary group") + ".")
return True
deleteDN = "cn=%s,%s,%s"\
%(groupName,orgUnit,clVars.Get("soft_ldap_base"))
# Удаление группы
@ -1525,7 +1608,8 @@ Samba in backup directory")
return True
def searchLdapUser(self, userName, ldapObj, clVars, orgUnit="ou=Users"):
def searchLdapUser(self, userName, ldapObj, clVars,
orgUnit="ou=Users,ou=Unix,ou=Services"):
"""Находит пользователя сервиса LDAP"""
baseDN = "%s,%s"%(orgUnit,clVars.Get("soft_ldap_base"))
#searchScope = ldap.SCOPE_SUBTREE
@ -1538,7 +1622,8 @@ Samba in backup directory")
def searchLdapUserPrimGroup(self, groupId, ldapObj, clVars):
"""Находит пользователей с первичной группой groupId"""
baseDN = "%s,%s"%("ou=Users",clVars.Get("soft_ldap_base"))
baseDN = "%s,%s,%s"%("ou=Users",self.unixRelDN,
clVars.Get("soft_ldap_base"))
#searchScope = ldap.SCOPE_SUBTREE
searchScope = ldap.SCOPE_ONELEVEL
searchFilter = "gidNumber=%s" %(groupId)
@ -1582,8 +1667,8 @@ Samba in backup directory")
def searchUidLdap(self, userId, ldapObj, clVars):
"""Находит пользователя по его идентефикатору из LDAP"""
baseDN = "ou=Users,%s"\
% clVars.Get("soft_ldap_base")
baseDN = "ou=Users,%s,%s"\
% (self.unixRelDN,clVars.Get("soft_ldap_base"))
#searchScope = ldap.SCOPE_SUBTREE
searchScope = ldap.SCOPE_ONELEVEL
searchFilter = "uid=*"
@ -1603,8 +1688,8 @@ Samba in backup directory")
def searchLdapGroupName(self, groupName, ldapObj, clVars):
"""Находит группу сервиса LDAP по её имени"""
baseDN = "ou=Groups,%s"\
% clVars.Get("soft_ldap_base")
baseDN = "ou=Groups,%s,%s"\
% (self.unixRelDN,clVars.Get("soft_ldap_base"))
#searchScope = ldap.SCOPE_SUBTREE
searchScope = ldap.SCOPE_ONELEVEL
searchFilter = "cn=%s" %(groupName)
@ -1656,8 +1741,8 @@ Samba in backup directory")
def searchLdapGid(self, groupId, ldapObj, clVars):
"""Находит группу сервиса LDAP по ёе id"""
baseDN = "ou=Groups,%s"\
% clVars.Get("soft_ldap_base")
baseDN = "ou=Groups,%s,%s"\
%(self.unixRelDN,clVars.Get("soft_ldap_base"))
#searchScope = ldap.SCOPE_SUBTREE
searchScope = ldap.SCOPE_ONELEVEL
searchFilter = "gidNumber=%s" %(str(groupId))
@ -1668,8 +1753,8 @@ Samba in backup directory")
def searchLdapMemberGid(self, userName, ldapObj, clVars):
"""Находит группу сервиса LDAP по ёе id"""
baseDN = "ou=Groups,%s"\
% clVars.Get("soft_ldap_base")
baseDN = "ou=Groups,%s,%s"\
% (self.unixRelDN,clVars.Get("soft_ldap_base"))
#searchScope = ldap.SCOPE_SUBTREE
searchScope = ldap.SCOPE_ONELEVEL
searchFilter = "memberUid=%s" %(userName)
@ -1970,10 +2055,59 @@ Samba in backup directory")
return max(gids)
return False
def getMaxGidGroupSystem(self):
"""Получаем максимальный добавленный gid из /etc/group
системной группы
"""
fileGroup = "/etc/group"
gidMax = self.maxSysGid
gidMin = self.minSysGid
gids = []
gids.append(0)
if os.path.exists(fileGroup):
FD = open(fileGroup)
lines = FD.readlines()
FD.close()
for line in lines:
gid = int(line.split(":")[2])
if gid<=gidMax and gid>=gidMin:
gids.append(gid)
return max(gids)
return False
def getMaxGidLdapSystem(self, ldapObj, clVars):
"""Находит максимальный добавленный gid в LDAP системной группы"""
baseDN = "ou=Groups,%s,%s"\
%(self.unixRelDN,clVars.Get("soft_ldap_base"))
#searchScope = ldap.SCOPE_SUBTREE
searchScope = ldap.SCOPE_ONELEVEL
searchFilter = "cn=*"
retrieveAttributes = None
resSearch = ldapObj.ldapSearch(baseDN, searchScope,
searchFilter, retrieveAttributes)
gidMax = self.maxSysGid
gidMin = self.minSysGid
gids = []
gids.append(0)
if resSearch:
for scope in resSearch:
if scope[0][1].has_key('gidNumber'):
# Пропускаем группы компьютеров
if scope[0][1].has_key('description') and\
scope[0][1]['description'][0] == "Computer group" and\
scope[0][1]['description'][0] == "Service group":
continue
gid = int(scope[0][1]['gidNumber'][0])
if gid<=gidMax and gid>=gidMin:
gids.append(gid)
return max(gids)
return False
def getMaxGidLdap(self, ldapObj, clVars):
"""Находит максимальный добавленный gid в LDAP"""
baseDN = "ou=Groups,%s"\
% clVars.Get("soft_ldap_base")
baseDN = "ou=Groups,%s,%s"\
%(self.unixRelDN,clVars.Get("soft_ldap_base"))
#searchScope = ldap.SCOPE_SUBTREE
searchScope = ldap.SCOPE_ONELEVEL
searchFilter = "cn=*"
@ -2013,7 +2147,8 @@ Samba in backup directory")
return False
return ldapObj
def getMaxUidLdap(self, ldapObj, clVars, orgUnit="ou=Users"):
def getMaxUidLdap(self, ldapObj, clVars,
orgUnit="ou=Users,ou=Unix,ou=Services"):
"""Находит максимальный добавленный id в LDAP"""
baseDN = "%s,%s"\
% (orgUnit,clVars.Get("soft_ldap_base"))
@ -2041,12 +2176,13 @@ Samba in backup directory")
"""Находит максимальный id +1"""
uidMax = self.getUidMax()
uidMin = self.getUidMin()
# Ветка компьютеры
uidMaxLdapComp = self.getMaxUidLdap(ldapObj, clVars,
"ou=Computers,%s" %self.sambaRelDN)
uidMaxLdap = self.getMaxUidLdap(ldapObj, clVars)
uidMaxPasswd = self.getMaxUidPasswd()
if uidMaxLdap > uidMaxPasswd:
uidMax = uidMaxLdap
else:
uidMax = uidMaxPasswd
listUid = [uidMaxLdapComp, uidMaxLdap, uidMaxPasswd]
uidMax = max(listUid)
if uidMax == 0:
return uidMin
else:
@ -2067,6 +2203,21 @@ Samba in backup directory")
else:
return gidMax+1
def getMaxGidSystem(self, ldapObj, clVars):
"""Находит максимальный gid +1 системной группы"""
gidMax = self.maxSysGid
gidMin = self.minSysGid
gidMaxLdap = self.getMaxGidLdapSystem(ldapObj, clVars)
gidMaxGroup = self.getMaxGidGroupSystem()
if gidMaxLdap > gidMaxGroup:
gidMax = gidMaxLdap
else:
gidMax = gidMaxGroup
if gidMax == 0:
return gidMin
else:
return gidMax+1
def delUserGroupLdap(self, users, groupName, ldapObj, clVars):
"""Удаление пользователей из списка из группы LDAP"""
res = self.searchLdapGroupName(groupName, ldapObj, clVars)
@ -2091,8 +2242,10 @@ Samba in backup directory")
for userName in users:
modAttrs.append((ldap.MOD_DELETE, 'memberUid', userName))
try:
ldapObj.conLdap.modify_s("cn=%s,%s,%s"\
%(groupName,"ou=Groups",clVars.Get("soft_ldap_base")),
ldapObj.conLdap.modify_s("cn=%s,%s,%s,%s"\
%(groupName,"ou=Groups",
self.unixRelDN,
clVars.Get("soft_ldap_base")),
modAttrs)
except ldap.LDAPError, e:
self.printERROR(e[0]['desc'])
@ -2105,8 +2258,10 @@ Samba in backup directory")
date = int(time.time()/86400)
modAttrs = [(ldap.MOD_REPLACE, 'shadowLastChange', str(date))]
try:
ldapObj.conLdap.modify_s("uid=%s,%s,%s"\
%(userName,"ou=Users",clVars.Get("soft_ldap_base")),
ldapObj.conLdap.modify_s("uid=%s,%s,%s,%s"\
%(userName,"ou=Users",
self.unixRelDN,
clVars.Get("soft_ldap_base")),
modAttrs)
except ldap.LDAPError, e:
self.printERROR(_("Not modify shadowLastChange attribute"))
@ -2299,8 +2454,10 @@ Samba in backup directory")
userPwdHash))
if modAttrs:
try:
ldapObj.conLdap.modify_s("uid=%s,%s,%s"\
%(userName,"ou=Users",clVars.Get("soft_ldap_base")),
ldapObj.conLdap.modify_s("uid=%s,%s,%s,%s"\
%(userName,"ou=Users",
self.unixRelDN,
clVars.Get("soft_ldap_base")),
modAttrs)
except ldap.LDAPError, e:
self.printERROR(e[0]['desc'])
@ -2382,8 +2539,10 @@ Samba in backup directory")
if modAttrs:
try:
ldapObj.conLdap.modify_s("uid=%s,%s,%s"\
%(userName,"ou=Users",clVars.Get("soft_ldap_base")),
ldapObj.conLdap.modify_s("uid=%s,%s,%s,%s"\
%(userName,"ou=Users",
self.unixRelDN,
clVars.Get("soft_ldap_base")),
modAttrs)
except ldap.LDAPError, e:
self.printERROR(e[0]['desc'])
@ -2445,16 +2604,16 @@ Samba in backup directory")
# Добавим пользователя LDAP
userPwd = self.addUserLdapServer(userName, options,
clVars, 'passwd', pwDialog)
if not userPwd:
return False
else:
pwdA = getpass.getpass(pwDialog[0]+":")
pwdB = getpass.getpass(pwDialog[1]+":")
if not (pwdA == pwdB):
self.printERROR (_("ERROR") + ": " +\
_("password incorrect")+ ": " + _("try again"))
return False
userPwd = pwdA
#if not userPwd:
#return False
#else:
pwdA = getpass.getpass(pwDialog[0]+":")
pwdB = getpass.getpass(pwDialog[1]+":")
if not (pwdA == pwdB):
self.printERROR (_("ERROR") + ": " +\
_("password incorrect")+ ": " + _("try again"))
return False
userPwd = pwdA
textLine = self.execProg("smbpasswd -a -s %s" %(userName),
"%s\n%s\n" %(userPwd,userPwd))
if "Added" in str(textLine):
@ -2471,14 +2630,9 @@ class tsOpt:
shortOpt = obj.getAllOpt('short', obj.relOptions['h'])
longOpt = obj.getAllOpt('long', obj.relOptions['h'])
if service in obj.allServ:
if service == "ldap":
obj.clearAllOpt()
shortOpt = obj.getAllOpt('short', obj.relServices['ldap'])
longOpt = obj.getAllOpt('long', obj.relServices['ldap'])
elif service == "samba":
obj.clearAllOpt()
shortOpt = obj.getAllOpt('short', obj.relServices['samba'])
longOpt = obj.getAllOpt('long', obj.relServices['samba'])
obj.clearAllOpt()
shortOpt = obj.getAllOpt('short',obj.relServices[service])
longOpt = obj.getAllOpt('long', obj.relServices[service])
optObj = cl_base.opt(shortOpt, longOpt)
optObj.sysArgv = sys.argv[1:]
optObj.obj = obj

@ -95,6 +95,10 @@ class Data:
soft_ldap_setup= {'mode':"w",
'type':('param','soft'),
}
#Настроен или нет сервис Unix
soft_unix_setup= {'mode':"w",
'type':('param','soft'),
}
#Настроен или нет сервис Samba
soft_samba_setup= {'mode':"w",
'type':('param','soft'),
@ -146,7 +150,6 @@ class Data:
#ID LDAP компьютера (номер компьютера)
soft_ldap_machine_id= {'mode':"w",
'type':('param','soft'),
'value':'20000'
}
#GID LDAP компьютера (номер первичной группы компьютера)
soft_ldap_machine_gid= {'mode':"w",

Loading…
Cancel
Save