develop
asamoukin 16 years ago
parent c22fbbc5eb
commit 540a7bf4a6

@ -6,6 +6,7 @@ INSTALL
calculate-server needs the following library version installed, in order to run:
Python >= 2.3
python-ldap >= 2.0.0
pyxml >= 0.8
calculate-lib >= 0.0.1
To install calculate-server , just execute the install script 'setup.py'.

@ -143,6 +143,8 @@ class cl_ldap(imp_cl_err, imp_cl_xml, imp_cl_par, imp_cl_con):
"""Основной класс для работы с LDAP"""
def __init__(self, cmdName):
self.column_width = 32
# Алгоритм шифрования пароля для LDAP пользователя
self.userCrypt = "{SSHA}"
# ini файл
self.iniFile = "/etc/calculate2/calculate.ini"
@ -202,6 +204,20 @@ class cl_ldap(imp_cl_err, imp_cl_xml, imp_cl_par, imp_cl_con):
'helpChapter':_("Options"),
'help':_("print the gidNumber to stdout")
},
{'progAccess':(2,),
'shortOption':"m",
'longOption':"member",
'optVal':"ADD_USERS",
'helpChapter':_("Options"),
'help':_("add members (comma delimited)")
},
{'progAccess':(2,),
'shortOption':"x",
'longOption':"member",
'optVal':"DEL_USERS",
'helpChapter':_("Options"),
'help':_("delete members (comma delimted)")
},
{'progAccess':(3,),
'shortOption':"b",
'longOption':"base-dir",
@ -275,20 +291,20 @@ class cl_ldap(imp_cl_err, imp_cl_xml, imp_cl_par, imp_cl_con):
'helpChapter':_("Options"),
'help':_("new value of the GECOS field")
},
{'progAccess':(5,),
'shortOption':"d",
'longOption':"home",
'optVal':"HOME_DIR",
'helpChapter':_("Options"),
'help':_("new home directory for the user account")
},
{'progAccess':(5,),
'shortOption':"g",
'longOption':"gid",
'optVal':"GROUP",
'helpChapter':_("Options"),
'help':_("force use GROUP as new primary group")
},
#{'progAccess':(5,),
#'shortOption':"d",
#'longOption':"home",
#'optVal':"HOME_DIR",
#'helpChapter':_("Options"),
#'help':_("new home directory for the user account")
#},
#{'progAccess':(5,),
#'shortOption':"g",
#'longOption':"gid",
#'optVal':"GROUP",
#'helpChapter':_("Options"),
#'help':_("force use GROUP as new primary group")
#},
{'progAccess':(5,),
'shortOption':"G",
'longOption':"groups",
@ -303,19 +319,30 @@ class cl_ldap(imp_cl_err, imp_cl_xml, imp_cl_par, imp_cl_con):
'helpChapter':_("Options"),
'help':_("append the user to the supplemental GROUPS")
},
#{'progAccess':(5,),
#'shortOption':"l",
#'longOption':"login",
#'optVal':"NEW_LOGIN",
#'helpChapter':_("Options"),
#'help':_("new value of the login name")
#},
#{'progAccess':(5,),
#'shortOption':"m",
#'longOption':"move-home",
#'helpChapter':_("Options"),
#'help':_("move contents of the home directory to the new location\
#(use only with -d)")
#},
{'progAccess':(5,),
'shortOption':"l",
'longOption':"login",
'optVal':"NEW_LOGIN",
'shortOption':"p",
'longOption':"password",
'helpChapter':_("Options"),
'help':_("new value of the login name")
'help':_("new password for the user account (from dialog)")
},
{'progAccess':(5,),
'shortOption':"m",
'longOption':"move-home",
'shortOption':"P",
'helpChapter':_("Options"),
'help':_("move contents of the home directory to the new location\
(use only with -d)")
'help':_("new password for the user account (from standart input)")
},
{'progAccess':(5,),
'shortOption':"s",
@ -324,13 +351,14 @@ class cl_ldap(imp_cl_err, imp_cl_xml, imp_cl_par, imp_cl_con):
'helpChapter':_("Options"),
'help':_("new login shell for the user account")
},
{'progAccess':(5,),
'shortOption':"u",
'longOption':"uid",
'optVal':"UID",
'helpChapter':_("Options"),
'help':_("new UID for the user account")
},
#{'progAccess':(5,),
#'shortOption':"u",
#'longOption':"uid",
#'optVal':"UID",
#'helpChapter':_("Options"),
#'help':_("new UID for the user account")
#},
{'progAccess':(6,),
'shortOption':"f",
'longOption':"force",
@ -404,6 +432,12 @@ class cl_ldap(imp_cl_err, imp_cl_xml, imp_cl_par, imp_cl_con):
'help': cmdName + " " + " [" + _("options") + "] " +\
_("group") + " " + _("service")
},
{
'progAccess':(2,),
'helpChapter':_("Usage"),
'help': cmdName + " " + " [" + _("options") + "] " +\
_("group") + " " + _("service")
},
{
'progAccess':(3,),
'helpChapter':_("Usage"),
@ -462,7 +496,14 @@ class cl_ldap(imp_cl_err, imp_cl_xml, imp_cl_par, imp_cl_con):
'progAccess':(0,),
'helpChapter':_("Examples"),
'help':pcs( " cl-groupadd guest ldap", self.column_width,
"# " + _("add group guest in service")+":\n# ldap",
"# " + _("add group guest in service")+":\n# LDAP",
CONWIDTH-self.column_width )
},
{
'progAccess':(2,),
'helpChapter':_("Examples"),
'help':pcs( " cl-groupmod -m guest test ldap", self.column_width,
"# " + _("add user test to a group guest in service")+":\n# LDAP",
CONWIDTH-self.column_width )
},
{
@ -494,9 +535,10 @@ class cl_ldap(imp_cl_err, imp_cl_xml, imp_cl_par, imp_cl_con):
{
'progAccess':(5,),
'helpChapter':_("Examples"),
'help':pcs(" cl-usermod -u 1000 guest samba",
self.column_width,
"# " + _("new UID 1000 for the user account guest") + ".",
'help':pcs(" cl-usermod -a test guest samba",
self.column_width,
"# " + _("append user guest to the supplemental group test") +\
".",
CONWIDTH-self.column_width)
},
{
@ -870,7 +912,7 @@ Samba in backup directory")
return True
def delUserInGroup(self, userName, ldapObj, clVars):
"""Удаление групп в которые входит пользователь"""
"""Удаление из групп в которые входит пользователь"""
userInGroups = self.searchLdapMemberGid(userName, ldapObj, clVars)
for group in userInGroups:
groupName = group[0][1]['cn'][0]
@ -1046,7 +1088,6 @@ Samba in backup directory")
return False
#userPwd = "crypt{xxx}"
userCrypt = "{SSHA}"
# Пароль пользователя зашифрованный
if options.has_key('p'):
userPwd = options['p']
@ -1064,7 +1105,7 @@ Samba in backup directory")
userPwd = pwdA
userPwdHash =\
self.execProg("slappasswd -s %s -h %s" %(userPwd,userCrypt))
self.execProg("slappasswd -s %s -h %s" %(userPwd,self.userCrypt))
if userPwdHash:
userPwd = userPwdHash
else:
@ -1118,7 +1159,7 @@ Samba in backup directory")
return True
def addUserGroupLdap(self, users, groupName, ldapObj, clVars):
"""Добавляет пользлователей из списка в LDAP группу"""
"""Добавляет пользователей из списка в LDAP группу"""
if not self.searchLdapGroupName(groupName, ldapObj, clVars):
self.printERROR(_("group name not found in LDAP ..."))
return False
@ -1571,6 +1612,25 @@ Samba in backup directory")
break
return uidMin
def chownR(self, directory, uid, gid):
"""изменяет владельца и группу
для всех файлов и директорий внутри directory
"""
scanObjs = fileObj.scanDirs([directory])
# меняем владельца домашней директории
os.chown(directory, uid,gid)
# Меняем владельца директорий
for dirCh in scanObjs[0].dirs:
os.chown(dirCh, uid,gid)
# Меняем владельца файлов
for fileCh in scanObjs[0].files:
os.chown(fileCh, uid,gid)
# Меняем владельца ссылок
for linkCh in scanObjs[0].links:
os.lchown(linkCh[1], uid, gid)
return True
def createHomeDir(self, userName, homeDir, ldapObj, clVars):
"""Создаем домашнюю директорию пользователя
@ -1590,6 +1650,8 @@ Samba in backup directory")
fileObj = cl_profile._file()
# Сканируем скелетную директорию
scanObjs = fileObj.scanDirs([skelDir])
if not scanObjs:
return True
for dirCreate in scanObjs[0].dirs:
#создаем в домашней директории директории из /etc/skel
fileObj.createDir(skelDir, dirCreate, homeDir)
@ -1604,6 +1666,7 @@ Samba in backup directory")
fileObj.closeFiles()
os.chown(oldFile, uid,gid)
for linkCreate in scanObjs[0].links:
#копируем ссылки
dst = homeDir + linkCreate[1].split(skelDir)[1]
srcHomeList = linkCreate[0].split(skelDir)
if len(srcHomeList)>1:
@ -1766,8 +1829,79 @@ Samba in backup directory")
else:
return gidMax+1
def modUserLdapServer(self, userName, options, clVars=False):
"""Модифицирует настройки пользователя LDAP"""
def delUserGroupLdap(self, users, groupName, ldapObj, clVars):
"""Удаление пользователей из списка из группы LDAP"""
res = self.searchLdapGroupName(groupName, ldapObj, clVars)
if not res :
self.printERROR(_("group name not found in LDAP") + " ...")
return False
if not res[0][0][1].has_key("memberUid"):
self.printERROR(_("Member list empty in group") + " " +\
str(groupName) + " ...")
return False
memberUsers = res[0][0][1]["memberUid"]
flagError =False
for user in users:
if not user in memberUsers:
flagError = True
break
if flagError:
self.printERROR(_("User") + " " +str(user)+ " " +\
_("not found in group") +" "+ str(groupName) + " ...")
return False
modAttrs = []
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")),
modAttrs)
except ldap.LDAPError, e:
self.printERROR(e[0]['desc'])
return False
return True
def modGroupLdapServer(self, groupName, options, clVars=False):
"""Модифицирует настройки группы пользователей LDAP"""
if not clVars:
clVars = cl_base.DataVars()
clVars.flServer()
clVars.flIniFile()
ldapParser = iniLdapParser()
adminDn = ldapParser.getVar("admin","DN")
adminPw = ldapParser.getVar("admin","PASS")
ldapObj = ldapFunction(adminDn, adminPw)
if not self.searchLdapGroupName(groupName, ldapObj, clVars):
self.printERROR(_("group name not found in LDAP ..."))
return False
# Добавляем список пользователей в группу
if options.has_key('m'):
# добавляемые пользователи в группу
users = options['m'].split(',')
res = self.addUserGroupLdap(users, groupName, ldapObj, clVars)
if res:
self.printSUCCESS(_("Append list users to a group") + " " +\
str(groupName) + " ...")
else:
self.printERROR(_("Not append list users to a group") +\
" " + str(groupName) + " ...")
return False
# Удаляем список пользователей из группы
if options.has_key('x'):
# удаляемые пользователи из группы
users = options['x'].split(',')
res = self.delUserGroupLdap(users, groupName, ldapObj, clVars)
if res:
self.printSUCCESS(_("Deleted list users to a group") + " " +\
str(groupName) + " ...")
else:
self.printERROR(_("Not delete list users to a group") +\
" " + str(groupName) + " ...")
return False
return True
def modUserSambaServer(self, userName, options, clVars=False):
"""Модифицирует настройки пользователя samba в LDAP"""
if not clVars:
clVars = cl_base.DataVars()
clVars.flServer()
@ -1776,6 +1910,48 @@ Samba in backup directory")
adminDn = ldapParser.getVar("admin","DN")
adminPw = ldapParser.getVar("admin","PASS")
ldapObj = ldapFunction(adminDn, adminPw)
res = self.searchLdapUser(userName, ldapObj, clVars)
if not res:
self.printERROR(_("User") + " " + str(userName) + " " +\
_("not found in LDAP") + " ...")
return False
if options.has_key('P') or options.has_key('p'):
pwDialog = [_("New SMB password"),
_("Retype new SMB password")]
userPwd = self.modUserLdapServer(userName, options, clVars,
'passwd',pwDialog)
if not userPwd:
return False
textLine = self.execProg("smbpasswd -s %s" %(userName),
"%s\n%s\n" %(userPwd,userPwd))
if not ("" in str(textLine)):
self.printERROR(_("Not modify samba user password") + " ...")
return False
self.printSUCCESS(_("Modify samba user password") + " ...")
else:
if not self.modUserLdapServer(userName, options, clVars):
return False
return True
def modUserLdapServer(self, userName, options, clVars=False ,optOut=False,
pwDialog=False):
"""Модифицирует настройки пользователя LDAP в LDAP"""
if not clVars:
clVars = cl_base.DataVars()
clVars.flServer()
clVars.flIniFile()
ldapParser = iniLdapParser()
adminDn = ldapParser.getVar("admin","DN")
adminPw = ldapParser.getVar("admin","PASS")
ldapObj = ldapFunction(adminDn, adminPw)
res = self.searchLdapUser(userName, ldapObj, clVars)
if not res:
self.printERROR(_("User") + " " + str(userName) + " " +\
_("not found in LDAP") + " ...")
return False
#uid = res[0][0][1]['uidNumber'][0]
#gid = res[0][0][1]['gidNumber'][0]
#homeDir = res[0][0][1]['homeDirectory']
# Новые группы в которые входит пользователь
if options.has_key('G'):
userGroups = options['G'].split(',')
@ -1795,8 +1971,9 @@ Samba in backup directory")
break
if flagError:
return False
self.printSUCCESS(_("Create new list of supplementary group") +\
self.printSUCCESS(_("Replace list of supplementary group") +\
" ...")
# Добавляем группы в которые входит пользователь
if options.has_key('a'):
userGroups = options['a'].split(',')
#список имен добавляемых групп
@ -1812,8 +1989,64 @@ Samba in backup directory")
break
if flagError:
return False
self.printSUCCESS(_("Append new list of supplementary group") +\
self.printSUCCESS(_("Append list of supplementary group") +\
" ...")
# Изменяемые аттрибуты пользователя
modAttrs = []
# Изменяем коментарий к пользователю
if options.has_key('c'):
comment = options['c']
if res[0][0][1].has_key('displayName'):
modAttr += [(ldap.MOD_REPLACE, 'displayName', comment),
(ldap.MOD_REPLACE, 'gecos', comment),
(ldap.MOD_REPLACE, 'cn', comment)]
else:
modAttrs += [(ldap.MOD_REPLACE, 'gecos', comment),
(ldap.MOD_REPLACE, 'cn', comment)]
# Изменяем оболочку пользователя
if options.has_key('s'):
shell = options['s']
modAttrs.append((ldap.MOD_REPLACE, 'loginShell', shell))
# Изменяем пароль пользователя
if options.has_key('P'):
pwdA = sys.stdin.readline().rstrip()
pwdB = sys.stdin.readline().rstrip()
elif options.has_key('p'):
if not pwDialog:
pwDialog = [_("New password"),
_("Retype new password")]
pwdA = getpass.getpass(pwDialog[0]+":")
pwdB = getpass.getpass(pwDialog[1]+":")
if options.has_key('P') or options.has_key('p'):
if not (pwdA == pwdB):
self.printERROR (_("ERROR") + ": " +\
_("password incorrect")+ ": " + _("try again"))
return False
userPwd = pwdA
if res[0][0][1].has_key('userPassword'):
userPwdHash =\
self.execProg("slappasswd -s %s -h %s"\
%(userPwd, self.userCrypt))
modAttrs.append((ldap.MOD_REPLACE, 'userPassword',
userPwdHash))
if modAttrs:
try:
ldapObj.conLdap.modify_s("uid=%s,%s,%s"\
%(userName,"ou=Users",clVars.Get("soft_ldap_base")),
modAttrs)
except ldap.LDAPError, e:
self.printERROR(e[0]['desc'])
return False
if options.has_key('c'):
self.printSUCCESS(_("Modify comment") + " ...")
if options.has_key('s'):
self.printSUCCESS(_("Modify shell") + " ...")
if options.has_key('P') or options.has_key('p'):
self.printSUCCESS(_("Modify LDAP user password") + " ...")
if optOut and optOut =='passwd':
return userPwd
return True
def addUserSambaServer(self, userName, options, clVars=False):

@ -148,7 +148,7 @@ class Data:
'type':('param','soft'),
'value':'20000'
}
#GID LDAP компьютера (номер группы компьютера)
#GID LDAP компьютера (номер первичной группы компьютера)
soft_ldap_machine_gid= {'mode':"w",
'type':('param','soft'),
'value':'20000',

@ -0,0 +1,96 @@
#!/usr/bin/python
#-*- coding: utf-8 -*-
#Copyright 2008 Calculate Pack, http://www.calculate-linux.ru
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, software
# distributed under the License is distributed on an "AS IS" BASIS,
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
# See the License for the specific language governing permissions and
# limitations under the License.
import sys
import os
sys.path.insert(0,os.path.abspath('/usr/lib/calculate/calculate-lib/pym'))
sys.path.insert(0,os.path.abspath('/usr/lib/calculate/calculate-server/pym'))
import cl_base
tr = cl_base.lang()
tr.setGlobalDomain('cl_server')
tr.setLanguage(sys.modules[__name__])
import cl_ldap
class tsOpt(cl_base.opt):
def __init__(self, obj):
self.obj =obj
self.shortOpt = self.obj.getAllOpt('short')
self.longOpt = self.obj.getAllOpt('long')
self.opt = {}
self.sysArgv = sys.argv[1:]
self.__iter = 0
self.params = {}
cl_base.opt.__init__(self, self.shortOpt, self.longOpt)
if "h" in self.opt or (not (self.params.has_key('group') and\
self.params.has_key('service')) and\
not self.opt):
print self.obj.getHelp()
else:
if self.params.has_key('service'):
if not (self.params['service'] in self.obj.allServ):
self.handlerErrOpt()
else:
self.handlerErrOpt()
def handlerOpt(self,option,value):
# Обработчик (опция значение)
#print option, value
shortOpt = self.obj.getShortOpt(option)
if not self.opt.has_key(shortOpt):
self.opt[shortOpt] = value
def handlerErrOpt(self):
# Обработчик ошибок
argv = " ".join(sys.argv[1:])
print _("Unrecognized option") + ' "' + argv + '"\n' + \
_("Try") + ' "' + sys.argv[0].split("/")[-1] + ' --help" ' +\
_("for more information.")
def handlerParam(self,param):
# Обработчик хвостов (значение)
self.__iter += 1
# Достаем название пользователя
if self.__iter == 1:
self.params['group'] = param
# Достаем название сервиса
if self.__iter == 2:
self.params['service'] = param
if __name__ == "__main__":
ldapObj = cl_ldap.cl_ldap("cl-groupmod")
optObj = tsOpt(ldapObj)
flagError = False
if optObj.params.has_key('service') and\
optObj.params.has_key('group'):
if optObj.params['service'] == "ldap":
# Добавляем группу
if not ldapObj.modGroupLdapServer(optObj.params['group'],
optObj.opt):
flagError = True
elif optObj.params['service'] == "samba":
# Добавляем группу
if not ldapObj.modGroupLdapServer(optObj.params['group'],
optObj.opt):
flagError = True
if flagError:
sys.exit(1)
else:
sys.exit(0)

@ -124,6 +124,7 @@ setup(
"./scripts/cl-userdel",
"./scripts/cl-usermod",
"./scripts/cl-groupadd",
"./scripts/cl-groupmod",
"./scripts/cl-groupdel",
"./scripts/cl-setup",
],

Loading…
Cancel
Save