develop
asamoukin 16 years ago
parent c0c6f9ab6a
commit 51d88bf678

@ -26,6 +26,7 @@ import cl_utils
import ldap
import types
import getpass
import _cl_keys
Version = "calculate-client 0.0.1"
@ -69,7 +70,8 @@ class cl_client(imp_cl_err, imp_cl_xml, imp_cl_help, imp_cl_smcon):
# имена используемых программ и их номера для доступа к переменным
# self.data
self.progName = { 'cl-client':0,
'cl-createhome':1
'cl-createhome':1,
'cl-sync':2
}
# Cвязь длинных опций помощи и выводимых разделов помощи с опциями
@ -104,6 +106,11 @@ class cl_client(imp_cl_err, imp_cl_xml, imp_cl_help, imp_cl_smcon):
'helpChapter':_("Usage"),
'help': cmdName + " " + _("user")
},
{
'progAccess':(2,),
'helpChapter':_("Usage"),
'help': cmdName + " [" + _("options") + "] " + _("user")
},
# Function
{
'progAccess':(0,),
@ -111,6 +118,16 @@ class cl_client(imp_cl_err, imp_cl_xml, imp_cl_help, imp_cl_smcon):
'help':_("Changes settings for connecting to domain \
(calculate-server)")
},
{
'progAccess':(1,),
'helpChapter':"Function",
'help':_("Create home directory for the new user account")
},
{
'progAccess':(2,),
'helpChapter':"Function",
'help':_("Mounting directories and synchronize the user preferences")
},
# Examples
{
'progAccess':(0,),
@ -131,7 +148,7 @@ class cl_client(imp_cl_err, imp_cl_xml, imp_cl_help, imp_cl_smcon):
'helpChapter':_("Common options"),
'help':_("Removes the settings for connecting to a domain")
},
{'progAccess':(0,1,),
{'progAccess':(0,1,2),
'longOption':"vars",
'optVal':_("TYPE_VAR"),
'helpChapter':_("Common options"),
@ -142,6 +159,18 @@ class cl_client(imp_cl_err, imp_cl_xml, imp_cl_help, imp_cl_smcon):
'helpChapter':_("Common options"),
'help':_("mount [remote] resource for Samba (calculate-server)")
},
{'progAccess':(2,),
'longOption':"login",
'helpChapter':_("Common options"),
'help':_("mount user resources")+ " " +\
_("and synchronize the user preferences")
},
{'progAccess':(2,),
'longOption':"logout",
'helpChapter':_("Common options"),
'help':_("Synchronize the user preferences") + " " +\
_("and umount user resources")
},
#{'progAccess':(0,),
#'shortOption':"p",
#'longOption':"prvar",
@ -239,18 +268,6 @@ class cl_client(imp_cl_err, imp_cl_xml, imp_cl_help, imp_cl_smcon):
self.conLdap = ldapObj.conLdap
return True
def getUserMail(self, userName):
"""Выдаем основной почтовый адрес"""
searchUser = self.searchUnixUser(userName)
if not searchUser:
self.printERROR(_("User %s not found in Unix service")\
%str(userName))
return False
if searchUser[0][0][1].has_key('mail'):
return searchUser[0][0][1]['mail'][0]
else:
return ""
def searchLineInFile(self, name, fileName, numEl=0):
"""Ищет строку в которой есть название разделенное ':'
@ -294,8 +311,10 @@ class cl_client(imp_cl_err, imp_cl_xml, imp_cl_help, imp_cl_smcon):
fullName = searchUser[0][0][1]['cn'][0]
if searchUser[0][0][1].has_key('mail'):
mail = searchUser[0][0][1]['mail'][0]
if searchUser[0][0][1].has_key('homeDirectory'):
home = searchUser[0][0][1]['homeDirectory'][0]
if uid and gid:
return (uid,gid,fullName,mail)
return (uid,gid,fullName,mail,home)
else:
return ()
@ -345,10 +364,12 @@ class cl_client(imp_cl_err, imp_cl_xml, imp_cl_help, imp_cl_smcon):
os.chown(directory, uid,gid)
# Меняем владельца директорий
for dirCh in dirs:
os.chown(dirCh, uid,gid)
if os.path.exists(dirCh):
os.chown(dirCh, uid,gid)
# Меняем владельца файлов
for fileCh in files:
os.chown(fileCh, uid,gid)
if os.path.exists(fileCh):
os.chown(fileCh, uid,gid)
return True
else:
fileObj = cl_profile._file()
@ -424,7 +445,7 @@ class cl_client(imp_cl_err, imp_cl_xml, imp_cl_help, imp_cl_smcon):
if connectLdap:
# uid и gid и mail из Ldap
uidGid = self.getUserLdapInfo(userName,False)
if not uidGid:
if not domain:
# uid и gid и mail из passwd
uidGid = self.getUserPasswdInfo(userName)
if not uidGid:
@ -461,66 +482,106 @@ class cl_client(imp_cl_err, imp_cl_xml, imp_cl_help, imp_cl_smcon):
self.printSUCCESS(_("created home dir %s")%homeDir + " ...")
return True
def mountRemote(self):
self.createClVars()
foudMountRemote = False
reFoundMount = re.compile("on\s+/var/calculate/remote\s+type\s+cifs")
def isDomain(self):
"""Находится ли компьютер в домене"""
self.createClVars(self.clVars)
foundMountRemote =self.isMount("/var/calculate/remote" ,"cifs")
foundMountHome =self.isMount("/var/calculate/home" ,"none", False)
if not self.clVars.Get("cl_remote_host") and not foundMountRemote and\
not foundMountHome:
self.printERROR("The computer is not in domain")
return False
return (foundMountRemote,foundMountHome)
def isMount(self,path ,typeMount, secondPath=True):
"""Примонтирована ли директория"""
foundMount = False
if secondPath:
reFoundMount = re.compile("on\s+%s\s+type\s+%s"%(path,typeMount))
else:
reFoundMount = re.compile("%s\s+.+type\s+%s"%(path,typeMount))
resMount = self.execProg("mount",False,False)
if resMount and type(resMount) == types.ListType:
for string in resMount:
if reFoundMount.search(string):
foudMountRemote = True
foundMount = True
break
if not foudMountRemote and not self.clVars.Get("cl_remote_host"):
self.printERROR("The computer is not in domain")
return foundMount
def mountRemote(self):
self.createClVars(self.clVars)
foundMountRemote = self.isDomain()
if not foundMountRemote:
return False
if foudMountRemote:
foundMountRemote = foundMountRemote[0]
foundMountHome = foundMountRemote[1]
pathHome = "/var/calculate/home"
if foundMountRemote:
self.printWARNING(_("Samba resource [remote] is mount") + \
" ...")
if foundMountHome:
self.printWARNING(str(pathHome) + " " +_("is mount")+
" ...")
if foundMountHome and foundMountRemote:
return True
pathRemote = "/var/calculate/remote"
domain = self.clVars.Get("cl_remote_host")
pwdRemote = self.clVars.Get("cl_remote_pw")
if not (domain and pwdRemote):
self.printERROR(_("Not found vaiables:cl_remote_host or \
if not foundMountRemote:
pathRemote = "/var/calculate/remote"
domain = self.clVars.Get("cl_remote_host")
pwdRemote = self.clVars.Get("cl_remote_pw")
if not (domain and pwdRemote):
self.printERROR(_("Not found vaiables: cl_remote_host or \
cl_remote_pw") + " ...")
return False
if not os.path.exists(pathRemote):
os.makedirs(pathRemote)
mountStr = "mount -t cifs -o user=client,password=%s \
return False
if not os.path.exists(pathRemote):
os.makedirs(pathRemote)
mountStr = "mount -t cifs -o user=client,password=%s \
//%s/remote %s" %(pwdRemote,domain,pathRemote)
textLine = self.execProg(mountStr)
if not (textLine == None):
self.printERROR(_("Can not mount Samba resource [remote]") + \
" ...")
return False
else:
self.printSUCCESS(_("Mount Samba resource [remote]") + \
textLine = self.execProg(mountStr)
if not (textLine == None):
self.printERROR(_("Can not mount Samba resource [remote]") +\
" ...")
return True
return False
self.printSUCCESS(_("Mount Samba resource [remote]") +\
" ...")
if not foundMountHome:
if not os.path.exists(pathHome):
os.makedirs(pathHome)
mountStr = "mount -o bind %s /home" %pathHome
textLine = self.execProg(mountStr)
if not (textLine == None):
self.printERROR(_("Can not mount") + " " + str(pathHome) +\
" ...")
return False
self.printSUCCESS(_("Mount") + " " + str(pathHome) + " " +\
" ...")
return True
def delDomain(self):
"""выводим из домена"""
self.createClVars()
foudMountRemote = False
reFoundMount = re.compile("on\s+/var/calculate/remote\s+type\s+cifs")
resMount = self.execProg("mount",False,False)
if resMount and type(resMount) == types.ListType:
for string in resMount:
if reFoundMount.search(string):
foudMountRemote = True
break
if not foudMountRemote and not self.clVars.Get("cl_remote_host"):
pathRemote = "/var/calculate/remote"
pathHome = "/var/calculate/home"
foundMountRemote =self.isMount(pathRemote ,"cifs")
foundMountHome =self.isMount(pathHome ,"none",False)
if not self.clVars.Get("cl_remote_host"):
self.printWARNING("The computer is not in domain")
return True
if foundMountRemote:
umountStr = "umount %s"%(pathRemote)
textLine = self.execProg(umountStr)
if not (textLine == None):
self.printERROR(_("Can not umount Samba resource [remote]") + \
" ...")
return False
if foundMountHome:
umountStr = "umount %s"%(pathHome)
textLine = self.execProg(umountStr)
if not (textLine == None):
self.printERROR(_("Can not umount") + " " + pathHome +\
" ...")
return False
self.execProg("calculate -P install/6intranet")
pathRemote = "/var/calculate/remote"
umountStr = "umount %s"%(pathRemote)
textLine = self.execProg(umountStr)
if not (textLine == None):
self.printERROR(_("Can not umount Samba resource [remote]") + \
" ...")
return False
self.clVars.Delete("cl_remote_host","local")
self.clVars.Delete("cl_remote_pw","local")
self.printOK(_("Deleted in domain") + " ...")
@ -533,7 +594,7 @@ cl_remote_pw") + " ...")
resPing = self.execProg("ping -c 2 -i 0.3 %s" %domain,False,False)
foudHost = False
foudHostSamba = False
foudMountRemote = False
foundMountRemote = False
reFoundHost = re.compile("(\d+)\% packet loss")
if resPing and type(resPing) == types.ListType and len(resPing)>=2:
pingStr = resPing[-2].strip()
@ -554,14 +615,9 @@ cl_remote_pw") + " ...")
if not foudHostSamba:
self.printERROR(_("Not found Samba server in %s")%domain)
return False
reFoundMount = re.compile("on\s+/var/calculate/remote\s+type\s+cifs")
resMount = self.execProg("mount",False,False)
if resMount and type(resMount) == types.ListType:
for string in resMount:
if reFoundMount.search(string):
foudMountRemote = True
break
if foudMountRemote:
foundMountRemote =self.isMount("/var/calculate/remote" ,"cifs")
foundMountHome =self.isMount("/var/calculate/home" ,"none", False)
if foundMountRemote:
self.printWARNING(_("Samba resource [remote] mount") + \
" ...")
else:
@ -582,6 +638,21 @@ cl_remote_pw") + " ...")
" ...")
self.clVars.Write("cl_remote_host", domain, False, "local")
self.clVars.Write("cl_remote_pw", userPwd, False, "local")
pathHome = "/var/calculate/home"
if foundMountHome:
self.printWARNING(str(pathHome)+ " " +_("is mount")+
" ...")
else:
if not os.path.exists(pathHome):
os.makedirs(pathHome)
mountStr = "mount -o bind %s /home" %pathHome
textLine = self.execProg(mountStr)
if not (textLine == None):
self.printERROR(_("Can not mount") + " " + str(pathHome) +\
" ...")
return False
self.printSUCCESS(_("Mount") + " " + str(pathHome) + " " +\
" ...")
self.clVars.flIniFile()
#считаем переменные для клиента
servDn = self.clVars.Get("ld_services_dn")
@ -601,6 +672,93 @@ install/6intranet" %(domain,servDn,unixDN,bindDn,bindPw)
self.printOK(_("Added in domain %s")%domain + " ...")
return True
def mountUserRes(self, userName):
"""Монтирование пользовательских ресурсов и синхронизация настроек"""
self.createClVars()
# Проверим что компьютер в домене и смонтирован [remote]
connectDomain = self.isDomain()
if not connectDomain:
return False
elif not connectDomain[0]:
self.printERROR(_("Can not mount Samba resource [remote]") + \
" ...")
return False
# Подсоединяемся к серверу
domain = self.clVars.Get("cl_remote_host")
if not self.getLdapObjBind(domain):
return False
# homeDir из LDAP
resLdap = self.getUserLdapInfo(userName)
if not resLdap:
return False
uid = int(resLdap[0])
gid = int(resLdap[1])
homeDir = resLdap[4]
# Получаем пароль пользователя из ключей ядра
userPwd = _cl_keys.getKey(userName)
if not userPwd:
self.printERROR(_("Not found user password"))
return False
home = os.path.split(homeDir)[0]
pathRemote = []
# Удаленный ресурс профилей
pathRemote.append((os.path.join(home,"." + userName), "unix"))
# Удаленный ресурс home
pathRemote.append((os.path.join(homeDir,"Home"), "homes"))
# Удаленный ресурс share
pathRemote.append((os.path.join(homeDir,"Disks"), "share"))
flagError = False
for path, res in pathRemote:
# Создаем директории для монтирования
if not os.path.exists(path):
try:
os.mkdir(path)
os.chown(path, uid, gid)
os.chmod(path,0700)
except OSError:
self.printERROR(_("Error creating directory"))
self.printERROR(_("Permission denied: '%s'")%path)
flagError = True
break
# Проверяем на монтирование директории
if self.isMount(path, 'cifs'):
continue
# Монтируем директории
mountStr="mount -t cifs -o user=%s,password=%s"%(userName,
userPwd) + " " +\
"//%s/%s %s" %(self.clVars.Get("cl_remote_host"),
res, path)
textLine = self.execProg(mountStr)
if not (textLine == None):
self.printERROR(_("Can not mount Samba resource [%s]")%res + \
" ...")
flagError = True
break
if flagError:
return False
# Синхронизируем настройки
if not self.syncUser(userName, homeDir, "login"):
return False
self.printOK(_("Mount user resources"))
return True
def syncUser(self, userName, userHome, sync):
"""Синхронизация пользовательских настроек"""
home = os.path.split(userHome)[1]
homeProfile = os.path.join(home,"." + userName)
if sync == "login":
if os.path.exists(userHome) and os.listdir(userHome) and\
os.path.exists(homeProfile) and os.listdir(homeProfile):
execStr = """/usr/bin/rsync --exclude="/.googleearth"
--exclude="/.rdesktop" --exclude="/.aMule" --exclude="*~" --exclude="/Home"
--exclude="/Web" --exclude="/Disks" --exclude="/Office" --exclude="/Factory"
--exclude="/.local" --exclude="/cache-*" --exclude="/socket-*"
--exclude="/tmp-*" --stats -a --delete -x %s/.%s %s/%s""" %(home, userName)
textLines = self.execProg(execStr)
for line in testLine:
print line
return True
class tsOpt(cl_base.opt):
"""Класс для обработки параметров и вывода help
@ -639,10 +797,15 @@ class tsOpt(cl_base.opt):
if len(self.nameParams) != self.__iter:
self.handlerErrOpt()
# В случае остсутствия опций командной строки и имени пользователя
if notOptError and not self.opt and not self.params.has_key('user'):
self.printErrorNotOpt()
if notOptError:
if not self.opt:
self.printErrorNotOpt()
self.flagHelp = True
elif not self.opt and not self.params.has_key('user'):
print helpObj.getHelp(helpObj.relOptions['h'])
self.flagHelp = True
def printErrorNotOpt(self):
"""Сообщение в случае отсутствия опций"""
print _("Options are absent.")

@ -65,7 +65,7 @@ class Data:
sr_samba_host = {'mode':"w",'value':''}
# имя компьютера с настроенным сервисом Jabber
sr_jabber_host = {}
sr_jabber_host = {'mode':"w",'value':''}
# шифрование при получении - ''/ssl
sr_jabber_crypt = {'mode':"w",'value':''}

@ -27,7 +27,7 @@ tr.setLanguage(sys.modules[__name__])
if __name__ == "__main__":
ldapObj = cl_client.cl_client("cl-createhome")
optObj = cl_client.tsOpt(ldapObj,True)
optObj = cl_client.tsOpt(ldapObj)
flagError = False
if not optObj.flagHelp and optObj.opt.has_key('vars'):
terms = optObj.opt['vars'].split(",")

@ -0,0 +1,50 @@
#!/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-sync")
optObj = cl_client.tsOpt(ldapObj, True)
flagError = False
if not optObj.flagHelp and optObj.opt.has_key('vars'):
terms = optObj.opt['vars'].split(",")
clVars = cl_base.DataVars()
clVars.flClient()
clVars.flIniFile()
if terms == ["all"]:
clVars.printVars()
else:
clVars.printVars(terms)
elif not optObj.flagHelp:
if optObj.params.has_key('user') and optObj.opt:
if optObj.opt.has_key('login'):
userName = optObj.params['user']
if not ldapObj.mountUserRes(userName):
flagError = True
if flagError:
sys.exit(1)
else:
sys.exit(0)

@ -120,6 +120,7 @@ setup(
packages = ['calculate-client.pym'],
data_files = data_files,
scripts=["./scripts/cl-createhome",
"./scripts/cl-client"],
"./scripts/cl-client",
"./scripts/cl-sync"],
ext_modules = [module1],
)

Loading…
Cancel
Save