diff --git a/pym/cl_client.py b/pym/cl_client.py index 4d2de4e..bfd8a70 100644 --- a/pym/cl_client.py +++ b/pym/cl_client.py @@ -92,12 +92,9 @@ class share(color_print): else: return dirsFiles - def printVars(self, opts=["all"]): + def printVars(self, *arg, **argv): """Печать существующих переменных""" - if opts == ["all"]: - self.clVars.printVars() - else: - self.clVars.printVars(opts) + self.clVars.printVars(*arg, **argv) class RsyncProgressBar: '''Объект запуска rsync для получения количества созданных файлов и @@ -1040,7 +1037,7 @@ class client(share, commandServer, encrypt): # файлов pathListFile = os.path.join(homeTemplate, self.listTemplFile) - if not self.removeFilesInTemplate(homeDir, pathListFile): + if not self.removeFilesInTemplate(homeDir,pathListFile): # Отмонтируем пользовательские ресурсы в # случае ошибки self.umountUserRes(homeDir) @@ -1280,6 +1277,84 @@ class client(share, commandServer, encrypt): os.remove(rmFile) return True + def scanDirectory(self, scanDir, listFiles, skipPath=[], prefix=False, + flagDir=False): + """Генерация списка файлов и директорий""" + if not prefix: + prefix = os.path.join(scanDir,"") + if flagDir or stat.S_ISDIR(os.lstat(scanDir)[stat.ST_MODE]): + for fileOrDir in os.listdir(scanDir): + absPath = os.path.join(scanDir,fileOrDir) + relPath = absPath.split(prefix)[1] + if relPath in skipPath: + continue + listFiles.append(relPath) + stInfo = os.lstat(absPath) + statInfo = stInfo[stat.ST_MODE] + if stat.S_ISDIR(statInfo): + self.scanDirectory(absPath, listFiles, + skipPath, prefix, True) + + def getListFilesTemplate(self, homeDir): + """Генерация списка файлов в домашней директориии + + Исключая монтируемые директории + """ + home = os.path.join(homeDir, "") + execStr = "mount" + textLines = self.execProg(execStr,False,False) + # Пропускаемые директории для сканирования + skipPaths = [] + if textLines: + for line in textLines: + if home in line: + skipPath =\ + line.partition(home)[2].rpartition(" type")[0] + skipPaths.append(skipPath) + # Список файлов в профиле пользователя + listFiles = [] + if not skipPaths: + self.printERROR(_("Not found the mount point of server resources")) + return False + self.scanDirectory(homeDir, listFiles, skipPaths) + return listFiles + + def removeFilesInTemplate(self, homeDir, pathListFile): + """Удаляем файлы которых нет в профиле пользователя""" + # Получаем файлы профиля на сервере + try: + filesTemplateTxt = open(pathListFile).read() + except: + self.printERROR(_("Can not open %s")%pathListFile) + return False + listFilesTemplate = filter(lambda x: x.strip(), + filesTemplateTxt.split("\n")) + filesTemplate = set(listFilesTemplate) + # Получаем файлы в домашней директории + listFilesHome = self.getListFilesTemplate(homeDir) + if listFilesHome is False: + return False + filesHome = set(listFilesHome) + filesRemove = list(filesHome - filesTemplate) + filesRemove.sort(lambda x, y: cmp(len(y), len(x))) + + rmPath = "" + try: + for rmFile in filesRemove: + rmPath = os.path.join(homeDir, rmFile) + if os.path.islink(rmPath): + os.unlink(rmPath) + elif os.path.isfile(rmPath): + os.remove(rmPath) + elif os.path.isdir(rmPath): + os.rmdir(rmPath) + else: + os.remove(rmPath) + except: + self.printERROR(_("Can nor remove %s")%rmPath) + return False + return True + def clearUserKey(self, userName): """Очищает пользовательский ключ ядра""" # Ищем ключ в ядре diff --git a/pym/cl_client_cmd.py b/pym/cl_client_cmd.py index 86f5fc8..1078ae8 100644 --- a/pym/cl_client_cmd.py +++ b/pym/cl_client_cmd.py @@ -90,7 +90,8 @@ class client_cmd(share_cmd): """Проверка опций командной строки""" optionsNotDomain = self.getOptionsNotDomain(optObj) if not args: - options = optionsNotDomain + [optObj.color, optObj.v] + options = optionsNotDomain + [optObj.color, optObj.v, + optObj.varsfilter] if not filter(lambda x: x, options): errMsg = _("no such argument")+":"+" %s" %USAGE.split(" ")[-1] self.optobj.error(errMsg) diff --git a/pym/cl_share_cmd.py b/pym/cl_share_cmd.py index 49a9a53..095b405 100644 --- a/pym/cl_share_cmd.py +++ b/pym/cl_share_cmd.py @@ -25,10 +25,24 @@ lang().setLanguage(sys.modules[__name__]) class share_cmd(color_print, _error): """Класс общих методов обработки опций командной строки""" + def printVars(self, optObj): """Печать переменных""" if optObj.v: self.logicObj.printVars() + # Печать фильтрованных переменных + elif optObj.varsfilter: + optCmd = optObj.varsfilter + varsFilter=None + varsNames = [] + if ',' in optCmd: + varsNames = optCmd.split(",") + elif '*' in optCmd: + varsFilter = optCmd.replace("*", ".*") + else: + varsNames.append(optCmd) + self.logicObj.printVars(varsFilter, varsNames) + return True def setVars(self, optObj): """Установка переменных""" diff --git a/pym/cl_sync_cmd.py b/pym/cl_sync_cmd.py index 41dcc66..eb7c0d8 100644 --- a/pym/cl_sync_cmd.py +++ b/pym/cl_sync_cmd.py @@ -87,14 +87,16 @@ class sync_cmd(share_cmd): set(self._getNamesAllSetOptions())) return ", ".join(map(lambda x: len(x) == 1 and "'-%s'"%x or "'--%s'"%x,\ listOpt)) - + def checkOpts(self, optObj, args): """Проверка опций командной строки""" optionsRequired = self.getOptionsRequired(optObj) if not args: - errMsg = _("no such argument")+":"+" %s" %USAGE.split(" ")[-1] - self.optobj.error(errMsg) - return False + options = [optObj.color, optObj.v, optObj.varsfilter] + if not filter(lambda x: x, options): + errMsg = _("no such argument")+":"+" %s" %USAGE.split(" ")[-1] + self.optobj.error(errMsg) + return False elif len(filter(lambda x: x, optionsRequired))>1: errMsg = _("incompatible options")+":"+" %s"\ %self.getStringIncompatibleOptions() @@ -117,7 +119,6 @@ class sync_cmd(share_cmd): """Установка имени пользователя""" self.logicObj.clVars.Set("ur_login", userName, True) - def mountUserResAndSync(self, sync=True, progress=False): """Монтирование ресурсов и синхронизация при входе""" userName = self.logicObj.clVars.Get("ur_login") diff --git a/scripts/cl-client b/scripts/cl-client index c75b22a..2ee9d0b 100644 --- a/scripts/cl-client +++ b/scripts/cl-client @@ -42,7 +42,7 @@ if __name__ == "__main__": # Печать переменных obj.printVars(opts) # Если нет печати переменных выполняем логику программы - if not opts.v: + if not opts.v and not opts.varsfilter: if args: domainName = args[0] # Ввод в домен diff --git a/scripts/cl-passwd b/scripts/cl-passwd index 2f6ee4b..cac739f 100644 --- a/scripts/cl-passwd +++ b/scripts/cl-passwd @@ -42,7 +42,7 @@ if __name__ == "__main__": # Печать переменных obj.printVars(opts) # Если нет печати переменных выполняем логику программы - if not opts.v: + if not opts.v and not opts.varsfilter: # Изменение пароля пользователя if not obj.setUserPasswordToServer(): sys.exit(1) diff --git a/scripts/cl-sync b/scripts/cl-sync index d09b79f..5b00ad9 100644 --- a/scripts/cl-sync +++ b/scripts/cl-sync @@ -34,29 +34,34 @@ if __name__ == "__main__": if ret is False: sys.exit(1) opts, args = ret - userName = args[0] # Установка цвета при печати сообщений obj.setPrintNoColor(opts) - # Установка имени пользователя - obj.setUserName(userName) + if len(args) > 0: + userName = args[0] + else: + userName = "" + if userName: + # Установка имени пользователя + obj.setUserName(userName) # Установка переменных if not obj.setVars(opts): sys.exit(1) # Печать переменных obj.printVars(opts) # Если нет печати переменных выполняем логику программы - if not opts.v: - sync = not opts.nosync - if opts.login: - # Монтирование ресурсов и синхронизация при входе - if not obj.mountUserResAndSync(sync=sync, - progress=opts.progress): - sys.exit(1) - elif opts.logout: - # Отмонтирование ресурсов и синхронизация при выходе - if not obj.umountUserResAndSync(sync=sync, + if not opts.v and not opts.varsfilter: + if userName: + sync = not opts.nosync + if opts.login: + # Монтирование ресурсов и синхронизация при входе + if not obj.mountUserResAndSync(sync=sync, progress=opts.progress): - sys.exit(1) + sys.exit(1) + elif opts.logout: + # Отмонтирование ресурсов и синхронизация при выходе + if not obj.umountUserResAndSync(sync=sync, + progress=opts.progress): + sys.exit(1) # Запись переменных if not obj.writeVars(opts): sys.exit(1)