Merge branch 'master' of git.calculate.ru:calculate2/calculate-client

master
Mike Hiretsky 14 years ago
commit 091484f422

@ -140,7 +140,7 @@ org.kde.kdialog.ProgressDialog'
def __init__(self,title,kdialog=None):
self.title = title
self.value = 0
if kdialog == None:
if kdialog is None:
self.openDialog(self.title)
def openDialog(self,title,max=None):
@ -160,7 +160,7 @@ org.kde.kdialog.ProgressDialog'
close_fds=True,
env=env, shell=True)
pipe.stdin.close()
if pipe.poll() == None:
if pipe.poll() is None:
# ожидание в 5 сек
for t in range(500):
time.sleep(0.01)
@ -574,7 +574,11 @@ conjunction with the 'login' or 'logout'")
# файл с дополнительной информацией о профиле
# на данный момент только количество файлов для rsync
# используемое для прогрессбара
self.configFile = ".calculate.ini"
self.configFileDesktop = "desktop.env"
self.configFileServer = "server.env"
# Путь относительно домашней директории в котором находятся
# конфигурационные файлы
self.pathConfig = ".calculate"
# При включениии репликации
# Временные задержки для монтирования в секундах
self.sleeps = [0.5, 2, 5]
@ -590,7 +594,8 @@ conjunction with the 'login' or 'logout'")
# Файл репликации
self.replLogoutFile = ".logout"
self.skipHomeFile = ["Home","Disks","FTP",
self.replLogoutFile]
self.replLogoutFile,
os.path.join(self.pathConfig,self.configFileDesktop)]
# Если атрибут установлен то значит (ошибка и отмонтируются
# пользовательские ресурсы)
self.errorAndUnmountUserRes = False
@ -898,6 +903,25 @@ conjunction with the 'login' or 'logout'")
else:
return ()
def setServerCommand(self, command, varsCommand, fileConfig,
uid=None, gid=None):
"""Установить команду для сервера"""
pathConfig = os.path.split(fileConfig)[0]
# Создаем директорию если ее нет
if not os.path.exists(pathConfig):
os.makedirs(pathConfig)
if not uid is None and not gid is None:
os.chown(pathConfig, uid, gid)
objConfig = cl_base.iniParser(fileConfig)
varsRun = {"run":"on"}
varsRun.update(varsCommand)
if not objConfig.setVar(["command", command], varsRun):
self.printERROR(_("Can not write variables in file %s")\
%fileConfig)
return False
if not uid is None and not gid is None:
os.chown(fileConfig, uid, gid)
return True
def setUserPasswordToServer(self, options):
"""Установка пароля пользователя на сервере"""
@ -929,13 +953,8 @@ conjunction with the 'login' or 'logout'")
if not options:
optPasswd = {"p":""}
password = self.getUserPwd(optPasswd, "p", False)
if password == False:
if password is False:
return False
# ~/.calculate
pathConfig = os.path.join(os.environ["HOME"],".calculate")
# Создаем директорию
if not os.path.exists(pathConfig):
os.makedirs(pathConfig)
# Переменные для записи в env файл
varsConfig = {"unix_hash":self.getHashPasswd(password,"ssha"),
"samba_lm_hash":self.getHashPasswd(password,"lm"),
@ -944,11 +963,9 @@ conjunction with the 'login' or 'logout'")
if filter(lambda x: not x, varsConfig.values()):
return False
# ~/.calculate/server.env
fileConfig = os.path.join(pathConfig,"server.env")
txtConfig = cl_base.iniParser(fileConfig)
if not txtConfig.setVar(["passwd","samba"], varsConfig):
self.printERROR(_("Can not write password variable in file %s")\
%fileConfig)
fileConfig = os.path.join(os.environ["HOME"], self.pathConfig,
self.configFileServer)
if not self.setServerCommand("passwd_samba", varsConfig, fileConfig):
return False
self.printOK(_("Changed password of user %s")%os.environ["USER"] + \
" ...")
@ -1165,7 +1182,7 @@ X session"))
killPid.remove(strPid)
if killPid and " ".join(killPid).strip():
textLine = self.execProg("kill -9 %s" %" ".join(killPid))
if not (textLine == None):
if not (textLine is None):
self.printERROR(_("Can not 'kill %s'")\
%" ".join(killPid))
flagError = True
@ -1310,7 +1327,7 @@ X session"))
mountStr = "mount -t cifs -o user=client //%s/remote %s"\
%(domain,pathRemote)
textLine = self.execProg(mountStr, None, True, {"PASSWD":pwdRemote})
if not (textLine == None):
if not (textLine is None):
self.printWARNING(_("Can not mount Samba resource [%s]")%\
"remote" + " ...")
flagLocalProfile = True
@ -1320,7 +1337,7 @@ X session"))
if foundMountHome:
umountStr = "umount /home"
textLine = self.execProg(umountStr)
if not (textLine == None):
if not (textLine is None):
self.printERROR(_("Can not unmount") + " /home")
return False
return True
@ -1331,7 +1348,7 @@ X session"))
os.makedirs(pathHome)
mountStr = "mount -o bind %s /home" %pathHome
textLine = self.execProg(mountStr)
if not (textLine == None):
if not (textLine is None):
self.printERROR(_("Can not mount") + " " + str(pathHome) +\
" ...")
return False
@ -1533,7 +1550,7 @@ manager") + " ..."
mountStr = "mount -t cifs -o user=client //%s/remote %s"\
%(domain,pathRemote)
textLine = self.execProg(mountStr, None, True, {"PASSWD":pwdRemote})
if not (textLine == None):
if not (textLine is None):
self.printERROR(_("Can not mount Samba resource [%s]")%\
"remote" + " ...")
return False
@ -1551,7 +1568,7 @@ manager") + " ..."
os.makedirs(pathHome)
mountStr = "mount -o bind %s /home" %pathHome
textLine = self.execProg(mountStr)
if not (textLine == None):
if not (textLine is None):
self.printERROR(_("Can not mount") + " " + str(pathHome) +\
" ...")
return False
@ -1607,7 +1624,8 @@ or ld_bind_dn or ld_bind_pw")
def removePrivateFiles(self, userHome):
"""Удаление приватных файлов"""
privateFiles = ['.kde4/share/apps/kwallet/kdewallet.kwl',
'.calculate/server.env']
os.path.join(self.pathConfig,
self.configFileServer)]
# файлы в .ssh
sshHome = ".ssh"
sshPath = os.path.join(userHome,sshHome)
@ -1702,6 +1720,9 @@ or ld_bind_dn or ld_bind_pw")
uid = int(resLdap[0])
gid = int(resLdap[1])
homeDir = resLdap[5]
# Файл хранения настроек пакета
configFileName = os.path.join(homeDir, self.pathConfig,
self.configFileDesktop)
home = os.path.split(homeDir)[0]
pathRemote = []
# Удаленный ресурс профилей
@ -1749,7 +1770,7 @@ or ld_bind_dn or ld_bind_pw")
return False
textLine = self.mountSleepRes(userName,userPwd,uid,gid,
"unix",pathUnix)
if not (textLine == None):
if not (textLine is None):
self.printERROR(_("Can not mount Samba resource [%s]")\
%"unix" + " ...")
# Отмонтируем пользовательские ресурсы в случае ошибки
@ -1768,11 +1789,10 @@ or ld_bind_dn or ld_bind_pw")
if not self.isCorrectProfileOnLocalServer(userName):
needSync = True
else:
FD = open(logOutFile)
exitStr = FD.read().strip()
FD.close()
# проверяем logOutFile: не содержит ли он "PROCESS"
if exitStr != "PROCESS":
exitStr = cl_base.iniParser(\
configFileName).getVar('main','status')
# проверяем logOutFile: не содержит ли он "process"
if exitStr != "process":
needSync = True
except:
# Удаляем приватные файлы
@ -1989,6 +2009,49 @@ or ld_bind_dn or ld_bind_pw")
else:
return False
def setCurrentVersionToConfig(self, configFileName, uid, gid):
"""Записывает текущую версию в файл конфигурации"""
# Текущая версия программы
currentVersion = self.clVars.Get("cl_ver")
if self.setVarToConfig("main", {"version":currentVersion},
configFileName, uid, gid):
return True
self.printERROR(_("can not write the version number in the file %s")\
%configFileName)
return False
def setVarToConfig(self, nameSection, varsDict, configFileName, uid, gid):
"""Записывает переменную в файл конфигурации"""
# Создаем директорию для конфигурационных файлов
pathConfig = os.path.split(configFileName)[0]
if not os.path.exists(pathConfig):
self.createUserDir(uid, gid, pathConfig, mode=False)
try:
if cl_base.iniParser(configFileName).setVar(nameSection, varsDict):
os.chmod(configFileName, 0600)
os.chown(configFileName,uid,gid)
except:
return False
return True
def clearHomeDir(self, homeDir):
"""Очистка домашней директории от файлов"""
rmFiles = list(set(os.listdir(homeDir))-\
set(self.skipHomeFile))
for rmFile in rmFiles:
delFile = os.path.join(homeDir,rmFile)
if os.path.islink(delFile):
os.unlink(delFile)
elif os.path.isfile(delFile):
os.remove(delFile)
elif os.path.isdir(delFile):
if not self.removeDir(delFile):
return False
elif stat.S_ISSOCK(os.stat(delFile)[stat.ST_MODE]):
os.remove(delFile)
return True
def mountUserRes(self, userName, sync=True, progress=False):
"""Монтирование пользовательских ресурсов и синхронизация настроек"""
# Имя пользователя
@ -2031,11 +2094,17 @@ or ld_bind_dn or ld_bind_pw")
uid = int(resLdap[0])
gid = int(resLdap[1])
homeDir = resLdap[5]
# Файл хранения настроек пакета
configFileName = os.path.join(homeDir, self.pathConfig,
self.configFileDesktop)
# При отсуствии создаем домашнюю директорию
if not os.path.exists(homeDir):
os.makedirs(homeDir)
os.chown(homeDir,uid,gid)
os.chmod(homeDir,0700)
# записываем в конфигурационный файл статус "в процессе"
self.setVarToConfig("main", {"status":"process"},
configFileName, uid, gid)
# записываем в .logout файл статус "в процессе"
logOutFile = os.path.join(homeDir,self.replLogoutFile)
self.createUserFile(logOutFile,"PROCESS", uid, gid)
@ -2079,13 +2148,13 @@ or ld_bind_dn or ld_bind_pw")
# Проверяем на монтирование директории
if self.isMount(path, 'cifs'):
continue
# В случае репликации не монтируем профиль пользователя
# Создаем директории пользователя
# на текущем сервере
if replOn and res=="unix":
defaultPath = path
continue
# Монтируем Samba ресурс
textLine = self.mountSambaRes(userName,userPwd,uid,gid,res,path)
if not (textLine == None):
if not (textLine is None):
self.printERROR(_("Can not mount Samba resource [%s]")\
%res + " ...")
flagError = True
@ -2116,25 +2185,27 @@ or ld_bind_dn or ld_bind_pw")
prevHost = searchPrevHost[0][0][1]['host'][0]
# Монтируем ресурс unix текущего сервера
mountServer = "default"
textLine = self.mountSleepRes(userName,userPwd,uid,gid,
"unix",defaultPath)
if not (textLine == None):
self.printERROR(_("Can not mount Samba resource [%s]")\
%"unix" + " ...")
# Переносим настройки пользователя в новую директорию
# CLD
if not self.upgradeProfileClient(userName, homeDir):
# Отмонтируем пользовательские ресурсы в случае ошибки
self.errorAndUnmountUserRes = True
return False
# Переносим настройки пользователя в новую директорию
# .CLD
self.upgradeProfileClient(userName, homeDir)
# Если на текущем сервере в ресурсе unix есть файлы
# то синхронируем настройки
# Получаем директорию хранения профиля на сервере
homeProfile = os.path.join(home, "." + userName, osLinuxShort)
if not os.path.exists(homeProfile):
homeProfile = os.path.join(home, "." + userName,
"." + osLinuxShort)
if os.listdir(homeProfile):
# Конфигурационный файл клинта на сервере desktop.env
configFileNameServer = os.path.join(homeProfile,
self.pathConfig,
self.configFileDesktop)
# Пишем версию клиента на сервер
if not self.setCurrentVersionToConfig(configFileNameServer,
uid,gid):
# Отмонтируем пользовательские ресурсы в случае ошибки
self.errorAndUnmountUserRes = True
return False
if not self.syncUser(userName, homeDir, "login", uid, gid,\
progress=progress,
host=self.clVars.Get('cl_remote_host')):
@ -2142,30 +2213,17 @@ or ld_bind_dn or ld_bind_pw")
self.errorAndUnmountUserRes = True
return False
else:
#Удаляем ненужные файлы
rmFiles = list(set(os.listdir(homeDir))-\
set(self.skipHomeFile))
for rmFile in rmFiles:
delFile = os.path.join(homeDir,rmFile)
if os.path.islink(delFile):
os.unlink(delFile)
elif os.path.isfile(delFile):
os.remove(delFile)
elif os.path.isdir(delFile):
if not self.removeDir(delFile):
# Отмонтируем пользовательские ресурсы
# в случае ошибки
self.errorAndUnmountUserRes = True
return False
elif stat.S_ISSOCK(os.stat(delFile)[stat.ST_MODE]):
os.remove(delFile)
# Отмонтируем ресурс
textLine = self.umountSleepPath(defaultPath)
if not textLine:
# Отмонтируем пользовательские ресурсы в случае ошибки
self.errorAndUnmountUserRes = True
return False
# Удаляем ненужные файлы (очищаем домашнюю директорию)
if not self.clearHomeDir(homeDir):
self.errorAndUnmountUserRes = True
return False
if prevHost and prevHost != self.clVars.Get("cl_remote_host"):
# Отмонтируем ресурс
textLine = self.umountSleepPath(defaultPath)
if not textLine:
# Отмонтируем пользовательские ресурсы в случае ошибки
self.errorAndUnmountUserRes = True
return False
# Монтируем настройки пользователя удаленного сервера
# если сервер найден
self.clVars.Set("cl_remote_host", prevHost, True)
@ -2173,7 +2231,7 @@ or ld_bind_dn or ld_bind_pw")
textLine = self.mountSleepRes(userName,userPwd,uid,gid,
"unix",defaultPath)
self.clVars.Set("cl_remote_host", defaultHost, True)
if not (textLine == None):
if not (textLine is None):
if self.isMount(defaultPath, 'cifs'):
textLine = self.umountSleepPath(defaultPath)
if not textLine:
@ -2186,7 +2244,7 @@ or ld_bind_dn or ld_bind_pw")
mountServer = "default"
textLine = self.mountSleepRes(userName,userPwd,uid,gid,
"unix",defaultPath)
if not (textLine == None):
if not (textLine is None):
self.printERROR(_("Can not mount Samba resource \
[%s]")%"unix" + " ...")
# Отмонтируем пользовательские ресурсы
@ -2194,80 +2252,100 @@ or ld_bind_dn or ld_bind_pw")
self.errorAndUnmountUserRes = True
return False
replErrorMount = True
else:
mountServer = "default"
# Монтируем текущий сервер если сервер не найден в LDAP
textLine = self.mountSleepRes(userName,userPwd,uid,gid,
"unix",defaultPath)
if not (textLine == None):
self.printERROR(_("Can not mount Samba resource \
[%s]")%"unix" + " ...")
# Отмонтируем пользовательские ресурсы в случае ошибки
self.errorAndUnmountUserRes = True
return False
# если репликации нет, то prevHost и remote_host одинаковые
if mountServer == "remote":
# Переносим настройки пользователя в новую директорию
# CLD
if not self.upgradeProfileClient(userName, homeDir):
# Отмонтируем пользовательские ресурсы в случае ошибки
self.errorAndUnmountUserRes = True
return False
# Получаем директорию хранения профиля на сервере
homeProfile = os.path.join(home, "." + userName,
osLinuxShort)
if os.listdir(homeProfile):
# Конфигурационный файл клинта на сервере
# desktop.env
configFileNameServer = os.path.join(homeProfile,
self.pathConfig,
self.configFileDesktop)
# Пишем версию клиента на сервер
if not self.setCurrentVersionToConfig(\
configFileNameServer,
uid,gid):
# Отмонтируем пользовательские ресурсы в случае ошибки
self.errorAndUnmountUserRes = True
return False
if not self.syncUser(userName,homeDir,"login",
uid,gid, progress=progress,
host=prevHost):
replErrorSync = True
else:
# Удаляем ненужные файлы (очищаем домашнюю директорию)
if not self.clearHomeDir(homeDir):
self.errorAndUnmountUserRes = True
return False
# Перемонтируем ресурс профилей
# на текущий сервер
textLine = self.umountSleepPath(defaultPath)
if not textLine:
# Отмонтируем пользовательские ресурсы в случае ошибки
self.errorAndUnmountUserRes = True
return False
textLine = self.mountSambaRes(userName,userPwd,uid,gid,
"unix",defaultPath)
if not (textLine is None):
self.printERROR(_("Can not mount Samba resource [%s]")\
%"unix" + " ...")
# Отмонтируем пользовательские ресурсы в случае ошибки
self.errorAndUnmountUserRes = True
return False
# если репликации нет
else:
prevHost=self.clVars.Get('cl_remote_host')
# Синхронизируем настройки пользователя
if not (replOn and mountServer == "default"):
curHost=self.clVars.Get('cl_remote_host')
# Синхронизируем настройки пользователя
# Переносим настройки пользователя в новую директорию
# .CLD
self.upgradeProfileClient(userName, homeDir)
# CLD
if not self.upgradeProfileClient(userName, homeDir):
# Отмонтируем пользовательские ресурсы в случае ошибки
self.errorAndUnmountUserRes = True
return False
# Получаем директорию хранения профиля на сервере
homeProfile = os.path.join(home, "." + userName, osLinuxShort)
if not os.path.exists(homeProfile):
homeProfile = os.path.join(home, "." + userName,
"." + osLinuxShort)
if os.listdir(homeProfile):
# Конфигурационный файл клинта на сервере desktop.env
configFileNameServer = os.path.join(homeProfile,
self.pathConfig,
self.configFileDesktop)
# Пишем версию клиента на сервер
if not self.setCurrentVersionToConfig(configFileNameServer,
uid,gid):
# Отмонтируем пользовательские ресурсы в случае ошибки
self.errorAndUnmountUserRes = True
return False
if not self.syncUser(userName, homeDir, "login", uid, gid,\
progress=progress,host=prevHost):
if replOn and mountServer == "remote":
replErrorSync = True
else:
progress=progress,host=curHost):
# Отмонтируем пользовательские ресурсы
# в случае ошибки
self.errorAndUnmountUserRes = True
return False
else:
#Удаляем ненужные файлы
rmFiles = list(set(os.listdir(homeDir))-\
set(self.skipHomeFile))
for rmFile in rmFiles:
delFile = os.path.join(homeDir,rmFile)
if os.path.islink(delFile):
os.unlink(delFile)
elif os.path.isfile(delFile):
os.remove(delFile)
elif os.path.isdir(delFile):
if not self.removeDir(delFile):
# Отмонтируем пользовательские ресурсы
# в случае ошибки
self.errorAndUnmountUserRes = True
return False
elif stat.S_ISSOCK(os.stat(delFile)[stat.ST_MODE]):
os.remove(delFile)
if replOn and mountServer == "remote":
# В случае репликации перемонтируем ресурс профилей
# на текущий сервер (в случае необходимости)
textLine = self.umountSleepPath(defaultPath)
if not textLine:
# Отмонтируем пользовательские ресурсы в случае ошибки
self.errorAndUnmountUserRes = True
return False
textLine = self.mountSambaRes(userName,userPwd,uid,gid,
"unix",defaultPath)
if not (textLine == None):
self.printERROR(_("Can not mount Samba resource [%s]")\
%"unix" + " ...")
# Отмонтируем пользовательские ресурсы в случае ошибки
self.errorAndUnmountUserRes = True
return False
# Удаляем ненужные файлы (очищаем домашнюю директорию)
if not self.clearHomeDir(homeDir):
self.errorAndUnmountUserRes = True
return False
if replOn:
if replErrorMount or replErrorSync:
self.createUserFile(logOutFile,"ERROR", uid, gid)
self.setVarToConfig("main", {"status":"error"},
configFileName, uid, gid)
else:
self.setVarToConfig("main", {"status":"success"},
configFileName, uid, gid)
self.createUserFile(logOutFile,"SUCCESS", uid, gid)
else:
self.setVarToConfig("main", {"status":"success"},
configFileName, uid, gid)
self.createUserFile(logOutFile,"SUCCESS", uid, gid)
self.printSUCCESS(_("Mounted user resource of the domain"))
@ -2277,20 +2355,20 @@ or ld_bind_dn or ld_bind_pw")
def mountSleepRes(self,userName,userPwd,uid,gid,res,path):
"""Монтирует ресурс при неудаче задержка потом повторное монитрование"""
textLine = self.mountSambaRes(userName,userPwd,uid,gid,res,path)
if not (textLine == None):
if not (textLine is None):
# Проверяем на монтирование директории
if self.isMount(path, 'cifs'):
textLineUmount = self.umountSleepPath(path)
if not textLineUmount:
return False
i = 0
while (i<len(self.sleeps) and not (textLine == None)):
while (i<len(self.sleeps) and not (textLine is None)):
# Задержка перед следующей попыткой
time.sleep(self.sleeps[i])
# Монтируем Samba ресурс
textLine = self.mountSambaRes(userName,userPwd,uid,
gid,res,path)
if not (textLine == None):
if not (textLine is None):
# Проверяем на монтирование директории
if self.isMount(path, 'cifs'):
textLineUmount = self.umountSleepPath(path)
@ -2350,13 +2428,13 @@ or ld_bind_dn or ld_bind_pw")
for fd in filesDir:
execStr = "cp -r '%s' '%s'" %(fd, movedPath)
textLine = self.execProg(execStr)
if not (textLine == None):
if not (textLine is None):
self.printERROR(_("Can not exec") + " " + str(execStr) +\
" ...")
return False
execStr = "rm -rf '%s'" %fd
textLine = self.execProg(execStr)
if not (textLine == None):
if not (textLine is None):
self.printERROR(_("Can not exec") + " " + str(execStr) +\
" ...")
return False
@ -2387,94 +2465,45 @@ or ld_bind_dn or ld_bind_pw")
FD.close()
return True
def copyProfileDir(self, destDir, srcDir):
"""Перенос файлов и директорий в директории srcDir в директорию destDir
def copyProfileDir(self, srcDir, destDir):
"""Перенос директории srcDir в директорию destDir
При копировании сохраняются владелец, группа, права
"""
if not os.path.exists(srcDir):
self.printERROR(_("Not found directory %s")%srcDir)
return False
files = os.listdir(srcDir)
if os.path.exists(destDir):
if not os.listdir(destDir):
os.rmdir(destDir)
else:
# Файловый объект
fileObj = cl_profile._file()
os.makedirs(destDir)
mode,uid,gid = fileObj.getModeFile(srcDir)
os.chmod(destDir, 0700)
os.chown(destDir, uid,gid)
flagError=False
for nameFile in files:
srcFile = os.path.join(srcDir, nameFile)
destFile = os.path.join(destDir, nameFile)
# Создаем ссылки
if os.path.islink(srcFile):
dst = srcFile
src = os.readlink(srcFile)
os.symlink(src,destFile)
if os.path.exists(destFile):
mode,uid,gid = fileObj.getModeFile(destFile)
#Изменение прав на ссылки
os.lchown(destFile, uid, gid)
os.unlink(srcFile)
continue
# Удаляем сокеты
elif stat.S_ISSOCK(os.stat(srcFile)[stat.ST_MODE]):
os.remove(srcFile)
continue
# Переносим оставшиеся файлы и директории
if os.system("mv %s %s &>/dev/null"%(srcFile,destFile)) != 0:
self.printERROR(_("Can not move %s")%srcFile + " " +\
_("to %s")%destFile)
flagError=True
break
if flagError:
if os.system("mv %s %s &>/dev/null"%(srcDir, destDir)) != 0:
self.printERROR(_("Can not move %s")%srcDir + " " +\
_("to %s")%destDir)
return False
return True
def upgradeProfileClient(self, userName, userHome):
"""Переносит данные клиента в директорию .CLD
"""Переносит данные клиента в директорию без точки
например: было /home/.user/.CLD стало /home/.user/CLD
Перед вызовом этого метода обязательно должен быть определен атрибут
объекта self.clVars - объект переменных
"""
# Директория хранения старых профилей
home = os.path.split(userHome)[0]
pathOldProfile = os.path.join(home, "." + userName)
if os.path.exists(pathOldProfile):
pathProfiles = os.path.join(home, "." + userName)
if os.path.exists(pathProfiles):
osLinuxShort = self.clVars.Get("os_linux_shortname")
# В случае пустой директории профиля
if not os.listdir(pathOldProfile):
pathNewProfile = os.path.join(pathOldProfile,
"." + osLinuxShort)
# Создаем директорию для хранения профиля
os.mkdir(pathNewProfile)
os.chmod(pathNewProfile, 0700)
return True
skipDirs = [".CLD", ".CLDX", "." + osLinuxShort]
# Если есть скрытые файлы кроме skipDir
# а так-же нет файлов skipDir - делаем апгрейд
if filter(lambda x: x[0]==".",
list(set(os.listdir(pathOldProfile))-set(skipDirs))) and\
len(filter(lambda x: not os.path.exists(os.path.join(pathOldProfile,x)),
skipDirs))==len(skipDirs):
pathNewProfile = os.path.join(pathOldProfile,".CLD")
# Копируем профиль в новое место
try:
self.copyProfileDir(pathNewProfile, pathOldProfile)
except:
self.printERROR(_("Error updating user profile"))
self.printERROR(_("path: %s")%pathNewProfile)
pathNewProfile = os.path.join(pathProfiles, osLinuxShort)
pathOldProfile = os.path.join(pathProfiles, "."+osLinuxShort)
if not os.path.exists(pathNewProfile) and\
os.path.exists(pathOldProfile) and\
os.listdir(pathOldProfile):
# Переносим профиль
if not self.copyProfileDir(pathOldProfile,
pathNewProfile):
return False
pathNewProfile = os.path.join(pathOldProfile,
"." + osLinuxShort)
if not os.path.exists(pathNewProfile):
# Создаем директорию для хранения профиля
os.mkdir(pathNewProfile)
os.chmod(pathNewProfile, 0700)
if os.path.exists(pathOldProfile) and\
not os.listdir(pathOldProfile):
os.rmdir(pathOldProfile)
return True
def syncUser(self, userName, userHome, sync, uid, gid, progress=False,\
@ -2546,14 +2575,23 @@ or ld_bind_dn or ld_bind_pw")
_("Receiving file list from %s") % host + " ...",
_("Downloading the user profile from %s") % host \
+ " ...", execStr)
configFileName = os.path.join(homeProfile,self.configFile)
pathConfig = os.path.join(homeProfile,
self.pathConfig)
# Удаляем предыдущий ini файл
prevIniFile = os.path.join(homeProfile,".calculate.ini")
if os.path.exists(prevIniFile):
os.remove(prevIniFile)
# Создаем директорию для конфигурационных файлов
if not os.path.exists(pathConfig):
self.createUserDir(uid, gid, pathConfig, mode=False)
configFileName = os.path.join(pathConfig, self.configFileDesktop)
if sync == "login":
# получить переменную files из секции Rsync файла
# .calculate.ini
try:
numfiles = cl_base.iniParser( \
numfiles = cl_base.iniParser(\
configFileName).getVar('rsync','files')
if numfiles == False:
if numfiles is False:
if os.path.exists(configFileName):
os.remove(configFileName)
numfiles = 1

@ -32,8 +32,7 @@ class fillVars(object, cl_base.glob_attr):
paths = os.listdir(profPath)
for path in paths:
ph = os.path.join(profPath,path)
filesAndDirs = os.listdir(ph)
if os.path.isdir(ph) and filesAndDirs:
if os.path.isdir(ph) and os.listdir(ph):
profpath.append(ph)
return profpath

Loading…
Cancel
Save