develop
asamoukin 16 years ago
parent d4a2370987
commit b4a746df10

@ -25,7 +25,7 @@ import cl_utils
import ldap import ldap
Version = "calculate-client 0.0.1_alpha" Version = "calculate-client 0.0.1"
tr = cl_base.lang() tr = cl_base.lang()
tr.setLanguage(sys.modules[__name__]) tr.setLanguage(sys.modules[__name__])
@ -67,6 +67,7 @@ class cl_client(imp_cl_err, imp_cl_xml, imp_cl_help, imp_cl_smcon):
# имена используемых программ и их номера для доступа к переменным # имена используемых программ и их номера для доступа к переменным
# self.data # self.data
self.progName = { 'cl-client':0, self.progName = { 'cl-client':0,
'cl-createhome':1
} }
# Cвязь длинных опций помощи и выводимых разделов помощи с опциями # Cвязь длинных опций помощи и выводимых разделов помощи с опциями
@ -96,6 +97,11 @@ class cl_client(imp_cl_err, imp_cl_xml, imp_cl_help, imp_cl_smcon):
'helpChapter':_("Usage"), 'helpChapter':_("Usage"),
'help': cmdName + " [" + _("options") + "] " + _("user") 'help': cmdName + " [" + _("options") + "] " + _("user")
}, },
{
'progAccess':(1,),
'helpChapter':_("Usage"),
'help': cmdName + " " + _("user")
},
# Function # Function
{ {
'progAccess':(0,), 'progAccess':(0,),
@ -117,20 +123,20 @@ calculate-server"),
'helpChapter':_("Common options"), 'helpChapter':_("Common options"),
'help':_("display this help and exit") 'help':_("display this help and exit")
}, },
{ {'progAccess':(0,),
'shortOption':"m", 'shortOption':"m",
'longOption':"create-home", 'longOption':"create-home",
'helpChapter':_("Common options"), 'helpChapter':_("Common options"),
'help':_("create home directory for the new user account") 'help':_("create home directory for the new user account")
}, },
{ {'progAccess':(0,),
'shortOption':"s", 'shortOption':"s",
'longOption':"cl-server", 'longOption':"cl-server",
'optVal':_("CL_SERVER"), 'optVal':_("CL_SERVER"),
'helpChapter':_("Common options"), 'helpChapter':_("Common options"),
'help':_("name or ip calculate server") 'help':_("name or ip calculate server")
}, },
{ {'progAccess':(0,),
'shortOption':"p", 'shortOption':"p",
'longOption':"prvar", 'longOption':"prvar",
'optVal':_("TYPES_VAR"), 'optVal':_("TYPES_VAR"),
@ -189,7 +195,7 @@ calculate-server"),
def searchLdapDN(self, name, relDN, attr, retAttr=None): def searchLdapDN(self, name, relDN, attr, retAttr=None):
"""Находит DN в LDAP""" """Находит DN в LDAP"""
baseDN = self.clVars.Get("soft_ldap_base") baseDN = self.clVars.Get("ld_base_dn")
DN = self.addDN(relDN,baseDN) DN = self.addDN(relDN,baseDN)
#searchScope = ldap.SCOPE_SUBTREE #searchScope = ldap.SCOPE_SUBTREE
searchScope = ldap.SCOPE_ONELEVEL searchScope = ldap.SCOPE_ONELEVEL
@ -212,8 +218,8 @@ calculate-server"),
В выходном объекте есть соединение с LDAP сервером: self.conLdap В выходном объекте есть соединение с LDAP сервером: self.conLdap
""" """
self.createClVars(self.clVars) self.createClVars(self.clVars)
bindDn = self.clVars.Get("soft_ldap_bind") bindDn = self.clVars.Get("ld_bind_dn")
bindPw = self.clVars.Get("soft_ldap_bindpw") bindPw = self.clVars.Get("ld_bind_pw")
if not (bindDn or bindPw): if not (bindDn or bindPw):
self.printERROR(_("not found LDAP bind DN or password") + " ...") self.printERROR(_("not found LDAP bind DN or password") + " ...")
return False return False
@ -297,15 +303,38 @@ calculate-server"),
os.lchown(linkCh[1], uid, gid) os.lchown(linkCh[1], uid, gid)
return True return True
def createHome(self, server, userName=False): def execProg(self, cmdStrProg, inStr=False, retFull=True):
# Подсоединяемся к movie """Выполняет внешнюю программу
if not self.getLdapObjBind(server):
Параметры:
cmdStrProg внешняя программа
inStr данные передаваемые программе на страндартный вход.
Возвращаемые параметры:
строка которую выведет внешняя программа
"""
return cl_utils.runOsCommand(cmdStrProg, inStr, retFull)
def getUidAndGidUser(self, userName):
strRes = self.execProg("id %s" %userName)
reFind = re.compile("uid=(\d+)\(.+gid=(\d+)\(")
res = reFind.search(strRes)
if res:
return res.group(1), res.group(2)
else:
self.printERROR(_("User %s not found")\
%str(userName))
return False return False
def createHome(self, userName=False):
# Подсоединяемся к movie
#if not self.getLdapObjBind(server):
#return False
# Создаем объект переменных # Создаем объект переменных
self.createClVars() self.createClVars()
if userName: if userName:
self.userName = userName self.userName = userName
uidGid = self.getUserUidGid(self.userName) #uidGid = self.getUserUidGid(self.userName)
uidGid = self.getUidAndGidUser(self.userName)
if not uidGid: if not uidGid:
self.printERROR(_(" Not found user uid and gid")) self.printERROR(_(" Not found user uid and gid"))
return False return False
@ -313,11 +342,11 @@ calculate-server"),
gid = int(uidGid[1]) gid = int(uidGid[1])
# Создаем пользовательскую директорию # Создаем пользовательскую директорию
homeDir = os.path.join("/home",self.userName) homeDir = os.path.join("/home",self.userName)
self.clVars.Set('setup_path_install',homeDir,True) self.clVars.Set('cl_root_path',homeDir,True)
if not os.path.exists(homeDir): if not os.path.exists(homeDir):
self.createUserDir(uid, gid, homeDir) self.createUserDir(uid, gid, homeDir)
# Записываем переменную логин # Записываем переменную логин
self.clVars.Set('ur_login',self.userName) self.clVars.Set('ur_name',self.userName)
# Применяем профили для пользователя # Применяем профили для пользователя
if not self.applyProfilesFromUser(): if not self.applyProfilesFromUser():
self.printERROR(_(" Not apply user profile")) self.printERROR(_(" Not apply user profile"))

@ -16,11 +16,20 @@
import os import os
class fillVars(object): class fillVars(object):
def get_cl_profile_path(self): def get_cl_profile_path(self):
profPath = [] """список накладываемых профилей при установке, наложении профилей"""
paths = ['/usr/lib/calculate/calculate-client/profile/user', profpath = []
] profPaths = ['/usr/lib/calculate/calculate-client/profile',
for path in paths: '/var/calculate/remote/client-profile',
if os.path.exists(path): '/var/calculate/client-profile'
profPath.append(path) ]
return profPath for profPath in profPaths:
if os.path.exists(profPath):
paths = os.listdir(profPath)
for path in paths:
ph = os.path.join(profPath,path)
if os.path.exists(ph) and os.listdir(ph):
profpath.append(ph)
return profpath

@ -27,100 +27,33 @@
# списка значений переменных) # списка значений переменных)
class Data: class Data:
#базовый суффикс LDAP #базовый суффикс LDAP
soft_ldap_base= {'mode':"r", #Vl soft_ldap_base
'type':('param','soft') ld_base_dn = {'value':'dc=calculate'}
}
#bind суффикс LDAP #bind суффикс LDAP
soft_ldap_bind= {'mode':"r", #Vl soft_ldap_bind
'type':('param','soft'), ld_bind_dn = {'value':'cn=proxyuser,dc=calculate'}
}
#пользователь только для чтения
soft_ldap_bindname= {'mode':"r",
'type':('param','soft'),
}
#пароль для пользователя для чтения #пароль для пользователя для чтения
soft_ldap_bindpw= {'mode':"r", #Vl soft_ldap_bindpw
'type':('param','soft'), ld_bind_pw = {'value':'calculate'}
}
#путь к директории относительно которой происходит наложение профилей на
#файлы системы
#setup_path_install
cl_root_path = {}
#имя для базового суффикса LDAP ##список накладываемых профилей при установке, наложении профилей
soft_ldap_root= {'mode':"r", #setup_path_profinstall
'type':('param','soft')} cl_profile_path = {}
#запись для пользователя root
soft_ldap_admin= {'mode':"r",
'type':('param','soft')}
#имя пользователя root для LDAP
soft_ldap_adminname= {'mode':"r",
'type':('param','soft'),
}
#почта пользователя #Логин LDAP пользователя
soft_ldap_user_mail= {'mode':"w", #V soft_ldap_user_login
'type':('param','soft'), ur_name = {'mode':"w"}
}
#----------------------------------------------------- # Calculate плюс версия калкулэйта для записи в заголовок файла
#Все сервисы Unix # объединяемого с профилем
#----------------------------------------------------- #setup_name
#Имя для всех сервисов cl_ver = {'value':'Calculate 0.0.1'}
soft_ldap_sevices_dn_name = {'mode':"r",
'type':('param','soft'),
'value' : 'Services'
}
#DN всех сервисов
soft_ldap_sevices_dn= {'mode':"r",
'type':('param','soft'),
}
#-----------------------------------------------------
#Сервис Ldap
#-----------------------------------------------------
#Настроен или нет сервис LDAP
soft_ldap_setup= {'mode':"w",
'type':('param','soft'),
'value':'no'
}
#-----------------------------------------------------
#Сервис Unix
#-----------------------------------------------------
#DN админстратора сервиса Unix (он, же DN сервиса)
soft_ldap_admin_unix= {'mode':"r",
'type':('param','soft'),
}
#имя админстратора сервиса Unix
soft_ldap_admin_unix_name= {'mode':"r",
'type':('param','soft'),
}
#Настроен или нет сервис Unix
soft_unix_setup= {'mode':"w",
'type':('param','soft'),
'value':'no'
}
#-----------------------------------------------------
#Сервис Samba
#-----------------------------------------------------
# Настроен или нет сервис Samba
soft_samba_setup= {'mode':"w",
'type':('param','soft'),
'value':'no'
}
#-----------------------------------------------------
#Сервис Mail
#-----------------------------------------------------
#Настроен или нет сервис Mail
soft_mail_setup= {'mode':"w",
'type':('param','soft'),
'value':'no'
}
#-----------------------------------------------------
#Сервис Jabber
#-----------------------------------------------------
#Настроен или нет сервис Jabber
soft_jabber_setup= {'mode':"w",
'type':('param','soft'),
'value':'no'
}
#пути к файлам профилей (перечислены через запятую в порядке приоритета)
cl_profile_path = {'mode':"w"}
#логин пользователя
ur_login = {'mode':"w"}

@ -0,0 +1,40 @@
#!/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-client/pym'))
import cl_base
import cl_client
tr = cl_base.lang()
tr.setGlobalDomain('cl_client')
tr.setLanguage(sys.modules[__name__])
if __name__ == "__main__":
ldapObj = cl_client.cl_client("cl-createhome")
optObj = cl_client.tsOpt(ldapObj)
flagError = False
if not optObj.flagHelp and optObj.params.has_key('user'):
userName = optObj.params['user'].strip()
if not ldapObj.createHome(userName):
flagError = True
if flagError:
sys.exit(1)
else:
sys.exit(0)

@ -119,6 +119,7 @@ setup(
package_dir = {'calculate-client': "."}, package_dir = {'calculate-client': "."},
packages = ['calculate-client.pym'], packages = ['calculate-client.pym'],
data_files = data_files, data_files = data_files,
scripts=["./scripts/cl-client",], scripts=["./scripts/cl-client",
"./scripts/cl-createhome"],
ext_modules = [module1], ext_modules = [module1],
) )

Loading…
Cancel
Save