diff --git a/pym/cl_fill_server.py b/pym/cl_fill_server.py index 04c303e..5d897f6 100644 --- a/pym/cl_fill_server.py +++ b/pym/cl_fill_server.py @@ -13,6 +13,7 @@ # 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. +from __future__ import print_function import os import cl_base import cl_utils @@ -30,7 +31,7 @@ class fillVars(object, cl_base.glob_attr): res = self._runos(runStr) if res: return res.strip() - print "Error generate hash (slappasswd)" + print("Error generate hash (slappasswd)") exit(1) def get_cl_profile_path(self): @@ -230,7 +231,7 @@ class fillVars(object, cl_base.glob_attr): for replServer in replServers: if replServer: md5hex = hashlib.md5(replServer).hexdigest() - data8bit = "".join(map(lambda x: str(int(x,16)/2),list(md5hex))) + data8bit = "".join((str(int(x,16)/2) for x in list(md5hex))) dStart = 0 dEnd = 3 dMax = 32 @@ -470,13 +471,13 @@ class fillVars(object, cl_base.glob_attr): netAllow = self.Get("sr_proxy_net_allow") if netAllow: netAllow = netAllow.split(",") - netAllow = map(lambda x: "acl localnet src %s"%x,netAllow) + netAllow = ["acl localnet src %s" % x for x in netAllow] netAllow = "\n".join(netAllow) return netAllow netAllow = self.Get("os_net_allow") if netAllow: netAllow = netAllow.split(",") - netAllow = map(lambda x: "acl localnet src %s"%x,netAllow) + netAllow = ["acl localnet src %s" % x for x in netAllow] netAllow = "\n".join(netAllow) return netAllow return "acl localnet src 127.0.0.1/32" @@ -543,14 +544,14 @@ class fillVars(object, cl_base.glob_attr): """Текст в ejabberd.cfg - имена хостов с которыми работает сервис""" jabberHosts = self.Get("sr_jabber_hosts") if jabberHosts: - return ", ".join(map(lambda x: '"'+x+'"', jabberHosts.split(","))) + return ", ".join(('"'+x+'"' for x in jabberHosts.split(","))) return "" def get_sr_jabber_hosts_yml(self): """Текст в ejabberd.cfg - имена хостов с которыми работает сервис""" jabberHosts = self.Get("sr_jabber_hosts") if jabberHosts: - return "\n".join(map(lambda x: ' - "%s"' % x, jabberHosts.split(","))) + return "\n".join((' - "%s"' % x for x in jabberHosts.split(","))) return "" def get_sr_jabber_user_name(self): @@ -591,7 +592,7 @@ class fillVars(object, cl_base.glob_attr): break if not foundLoc: netAllow.append("127.0.0.1") - netAllow = map(lambda x: "%s;"%x,netAllow) + netAllow = ["%s;" % x for x in netAllow] netAllow = " ".join(netAllow) return "listen-on { %s };"%netAllow netAllow = self.Get("sr_dns_net_allow") diff --git a/pym/cl_ldap.py b/pym/cl_ldap.py index 870d4d2..fd29efa 100644 --- a/pym/cl_ldap.py +++ b/pym/cl_ldap.py @@ -14,6 +14,7 @@ # See the License for the specific language governing permissions and # limitations under the License. +from __future__ import print_function import os import sys import re @@ -44,6 +45,7 @@ import readline from xml import xpath # Для 32 битного целого (генерация серийного номера DNS зоны) import ctypes +from functools import reduce Version = "calculate-server 2.1.20" @@ -109,7 +111,7 @@ class report: def printReport(self): """Напечатать данные в табличном виде""" - print self.title + print(self.title) listStrSep = [] for lenCol in self.columnsWidth: listStrSep.append("-"*lenCol) @@ -123,7 +125,7 @@ class report: if printData[-1] == "\n": printData = printData[:-1] lines = printData.splitlines() - lenCols = map(lambda x: len(x), lines[0].strip().split(" ")) + lenCols = [len(x) for x in lines[0].strip().split(" ")] convLines = [] lenLines = len(lines) for i in range(lenLines): @@ -131,8 +133,8 @@ class report: if i == 0 or i == 2 or i == lenLines-1: char ="-+-" convLines.append(self._insertStrChar(lines[i], lenCols, char)) - print "\n".join(convLines) - print "(%s %s)"%(len(self.dataList), _("rows")) + print("\n".join(convLines)) + print("(%s %s)"%(len(self.dataList), _("rows"))) return True def _insertStrChar(self, line, lenCols, char): @@ -185,7 +187,7 @@ class iniLdapParser(cl_base.iniParser): self.nameIniFile = "/var/lib/calculate/calculate.ldap" cl_base.iniParser.__init__(self, self.nameIniFile) # права создаваемого ini-файла - self.setMode(0600) + self.setMode(0o600) pathIniFile = os.path.split(self.nameIniFile)[0] if not os.path.exists(pathIniFile): os.makedirs(pathIniFile) @@ -215,7 +217,7 @@ class ldapFunction(cl_utils2.ldapFun): # Записываем параметры из ldif файла в LDAP сервер parser = addLdif(strLdif,self.conLdap) parser.parse() - except ldap.LDAPError, e: + except ldap.LDAPError as e: self.setError(e[0]['desc']) return False except: @@ -255,27 +257,27 @@ class shareIP: def getNet(self, ip, mask): """По ip и маске получаем сеть""" octetsMult = (0x1, 0x100, 0x10000, 0x1000000) - octetsIp = map(lambda x: int(x), ip.split(".")) - octetsMask = map(lambda x: int(x), mask.split(".")) + octetsIp = [int(x) for x in ip.split(".")] + octetsMask = [int(x) for x in mask.split(".")] ipNumb = 0 for i in octetsMult: - ipNumb += octetsIp.pop()*i + ipNumb += octetsIp.pop() * i maskNumb = 0 for i in octetsMult: - maskNumb += octetsMask.pop()*i + maskNumb += octetsMask.pop() * i startIpNumber = maskNumb&ipNumb x = startIpNumber - nMask = lambda y: len(filter(lambda x: y >> x &1 ,range(32))) + nMask = lambda y: len([x for x in range(32) if y >> x & 1]) return "%s.%s.%s.%s/%s"\ %(x>>24, x>>16&255, x>>8&255, x&255, nMask(maskNumb)) def getNumberIP(self, ip): """По строке ip получаем число (номер ip)""" - octetsIp = map(lambda x: int(x), ip.split(".")) + octetsIp = [int(x) for x in ip.split(".")] octetsMult = (0x1, 0x100, 0x10000, 0x1000000) ipNumb = 0 for i in octetsMult: - ipNumb += octetsIp.pop()*i + ipNumb += octetsIp.pop() * i return ipNumb def getNumberNetmask(self, netmask): @@ -490,7 +492,7 @@ in a sambaDomainName', while ldapObj.getError(): try: # Задержка - wait.next() + next(wait) except StopIteration: break # Очистка ошибки @@ -555,7 +557,7 @@ in a sambaDomainName', term = "" if resRestore == True: term = message - if not flagError and type(resRestore) == types.TupleType: + if not flagError and type(resRestore) == tuple: # Если cansel if resRestore[0] == "Cancel": # Удаляем пользователя @@ -600,7 +602,7 @@ in a sambaDomainName', "%s-%s"%(userName,strUid), service) if strUid and os.path.exists(delBackDir) and os.listdir(delBackDir): - if message == None or type(message) == types.BooleanType: + if message == None or type(message) == bool: dialogRes = message else: dialogRes = self.dialogYesNo(message) @@ -692,9 +694,9 @@ in a sambaDomainName', self.printERROR(_("ERROR") + ": " + execStr) return False else: - splLines = filter(lambda x: len(x)==2 and "default" in x[1],\ - map(lambda x: x.split("|"),textLine)) - splLines = map(lambda x: x[0].strip(), splLines) + splLines = [x for x in (y.split("|") for y in textLine) + if len(x)==2 and "default" in x[1]] + splLines = [x[0].strip() for x in splLines] return splLines @@ -782,7 +784,7 @@ in a sambaDomainName', self.printERROR(clProf.getError()) return False else: - if verbose and type(data) == types.TupleType: + if verbose and type(data) == tuple: dirs, files = data return files return True @@ -990,17 +992,17 @@ in a sambaDomainName', pwDialog - структура для вывода приглашения в режиме диалога """ userPwd = "" - if optStdIn and options.has_key(optStdIn): + if optStdIn and optStdIn in options: pwdA = sys.stdin.readline().rstrip() pwdB = pwdA - elif optDialog and options.has_key(optDialog): + elif optDialog and optDialog in options: if not pwDialog: pwDialog = [_("New password"), _("Retype new password")] pwdA = getpass.getpass(pwDialog[0]+":") pwdB = getpass.getpass(pwDialog[1]+":") - if (optStdIn and options.has_key(optStdIn)) or\ - (optDialog and options.has_key(optDialog)): + if (optStdIn and optStdIn in options) or\ + (optDialog and optDialog in options): if not pwdA or not (pwdA == pwdB): self.printERROR (_("ERROR") + ": " +\ _("password incorrect")+ ": " + _("try again")) @@ -1155,7 +1157,7 @@ in a sambaDomainName', fOut.close() if flagError: return False - if searchUser[0][0][1].has_key('jpegPhoto'): + if 'jpegPhoto' in searchUser[0][0][1]: modAttrs.append((ldap.MOD_REPLACE, 'jpegPhoto', photoData)) else: modAttrs.append((ldap.MOD_ADD, 'jpegPhoto', photoData)) @@ -1204,7 +1206,7 @@ in a sambaDomainName', break return True - def createUserDir(self, uid, gid, userDir, mode=0700): + def createUserDir(self, uid, gid, userDir, mode=0o700): """Создание пользовательской директории""" if not os.path.exists(userDir): os.makedirs(userDir) @@ -1216,7 +1218,7 @@ in a sambaDomainName', self.printERROR(_("Path %s exists") %userDir) return False - def createUserFile(self, fileName, fileTxt, uid, gid, mode=0644): + def createUserFile(self, fileName, fileTxt, uid, gid, mode=0o644): """Создает пользовательский файл с содержимым Если директория файла не существует то ошибка @@ -1357,8 +1359,8 @@ in a sambaDomainName', flagError = True break else: - splIP = map(lambda x: 255>=int(x.split("/")[0]) and\ - x.split("/")[0], find.group().split(".")) + splIP = [255>=int(x.split("/")[0]) and x.split("/")[0] for x + in find.group().split(".")] if not splIP[0] or splIP[0] and int(splIP[0]) == 0: flagError = True break @@ -1400,9 +1402,9 @@ in a sambaDomainName', вывод - список доверительных сетей """ def printW(): - print _("Incorrect string allow networks") - print _("Example - allow networks: 10.0.0.0/24 10.0.10.0/24") - print _("Try again\n") + print(_("Incorrect string allow networks")) + print(_("Example - allow networks: 10.0.0.0/24 10.0.10.0/24")) + print(_("Try again\n")) strNet = self.raw_input(strPrompt, strNetAllow) i = 0 while i<3 and not self.isCorrectStringNet(strNet): @@ -1477,7 +1479,7 @@ if you want to continue to run the program again")) """Добавление узла в LDAP""" try: self.conLdap.add_s(DN, entry) - except ldap.LDAPError, e: + except ldap.LDAPError as e: self.printERROR(_("LDAP Error") + ": " + e[0]['desc'].strip()) self.printERROR(errorMessage) return False @@ -1542,7 +1544,7 @@ This command is not allowed.")) if modAttrs: try: self.conLdap.modify_s(DN, modAttrs) - except ldap.LDAPError, e: + except ldap.LDAPError as e: self.printERROR(e[0]['desc']) return False return True @@ -1553,7 +1555,7 @@ This command is not allowed.")) DN = self.addDN(relDN,self.baseDN) try: self.conLdap.modrdn_s(DN, newFirstDn) - except ldap.LDAPError, e: + except ldap.LDAPError as e: self.printERROR(e[0]['desc']) return False return True @@ -1564,7 +1566,7 @@ This command is not allowed.")) DN = self.addDN(relDN,self.baseDN) try: self.conLdap.delete_s(DN) - except ldap.LDAPError, e: + except ldap.LDAPError as e: self.printERROR(e[0]['desc']) return False return True @@ -1577,7 +1579,7 @@ This command is not allowed.")) lst.append(0) if resSearch: for scope in resSearch: - if scope[0][1].has_key(attrSearch): + if attrSearch in scope[0][1]: uid = int(scope[0][1][attrSearch][0]) if uid<=numMax and uid>=numMin: lst.append(uid) @@ -1593,7 +1595,7 @@ This command is not allowed.")) dnList = self.conLdap.search_s(DN, ldap.SCOPE_SUBTREE, ldapFilter,None) - except ldap.LDAPError, e: + except ldap.LDAPError as e: self.printERROR("fullElementDN: "+e[0]['desc']) return False FDOUT = StringIO.StringIO("") @@ -1672,7 +1674,7 @@ This command is not allowed.")) ldap.SCOPE_SUBTREE, '(objectclass=*)', ['']) - except ldap.LDAPError, e: + except ldap.LDAPError as e: self.printERROR("deleteDN: "+e[0]['desc']) return False for dn, f in dnList: @@ -1681,7 +1683,7 @@ This command is not allowed.")) for dn in delListDN: try: self.conLdap.delete_s(dn) - except ldap.LDAPError, e: + except ldap.LDAPError as e: self.printERROR("deleteDN: "+e[0]['desc']) return False return True @@ -1780,7 +1782,7 @@ This command is not allowed.")) while ldapObj.getError(): try: # Задержка - wait.next() + next(wait) except StopIteration: break # Очистка ошибки @@ -1882,11 +1884,11 @@ This command is not allowed.")) sslBits=1024, userName="root",groupName="root", certFile="/tmp/server.pem", - certFileMode=0400, + certFileMode=0o400, keyFile="/tmp/server.key", - keyFileMode=0400, + keyFileMode=0o400, dhFile=None, - dhFileMode=0400, + dhFileMode=0o400, genDH=False): """Создает сертификат""" sslFile = "/usr/bin/openssl" @@ -1897,7 +1899,7 @@ This command is not allowed.")) if genDH and dhFile: certAndKeyFiles = [dhFile, certFile, keyFile] - foundCertFiles = filter(lambda x: os.path.exists(x), certAndKeyFiles) + foundCertFiles = [x for x in certAndKeyFiles if os.path.exists(x)] if not os.path.exists(dhFile): rndFile = "/tmp/%s.rnd" %strData self.execProg("dd if=/dev/urandom of=%s count=1"%rndFile) @@ -1914,23 +1916,23 @@ This command is not allowed.")) return False if os.path.exists(rndFile): os.remove(rndFile) - foundCertFiles = filter(lambda x: os.path.exists(x), certAndKeyFiles) + foundCertFiles = [x for x in certAndKeyFiles if os.path.exists(x)] if len(foundCertFiles)==3: return True else: if genDH: keyFile = certFile certAndKeyFiles = [certFile] - foundCertFiles = filter(lambda x: os.path.exists(x),certAndKeyFiles) + foundCertFiles = [x for x in certAndKeyFiles if os.path.exists(x)] if len(foundCertFiles)==1: return True else: certAndKeyFiles = [certFile, keyFile] - foundCertFiles = filter(lambda x: os.path.exists(x), certAndKeyFiles) + foundCertFiles = [x for x in certAndKeyFiles if os.path.exists(x)] if len(foundCertFiles)==2: return True # Удаляем файл сертификата - map(lambda x: os.remove(x), foundCertFiles) + [os.remove(x) for x in foundCertFiles] uidAndGid = self.getUserUidAndGid(userName, groupName) if not uidAndGid: return False @@ -1965,9 +1967,9 @@ nsCertType = %s for fileName in certAndKeyFiles: dirName = os.path.split(fileName)[0] if not os.path.exists(dirName): - self.createUserDir(0, 0, dirName, 0755) + self.createUserDir(0, 0, dirName, 0o755) # Создание конфигурационного файла - self.createUserFile(cnfFile, textCnf, 0, 0, 0600) + self.createUserFile(cnfFile, textCnf, 0, 0, 0o600) # Создание сертификата textLine = self.execProg(\ "%s req -new -x509 -nodes -config %s -days %s -out %s -keyout %s"\ @@ -2137,7 +2139,7 @@ class servUnix(shareLdap): os.symlink(src,dst) #Изменение прав на ссылки os.lchown(dst, uid, gid) - os.chmod(homeDir, 0700) + os.chmod(homeDir, 0o700) os.chown(homeDir, uid,gid) return True @@ -2299,7 +2301,7 @@ class servUnix(shareLdap): return False else: findUsers = [] - if res[0][0][1].has_key('memberUid'): + if 'memberUid' in res[0][0][1]: usersInGroup = res[0][0][1]['memberUid'] for userName in usersNames: if userName in usersInGroup: @@ -2336,7 +2338,7 @@ class servUnix(shareLdap): return False # Если группа существует выходим без ошибки flagSearchGroups = True - if options.has_key('f'): + if 'f' in options: flagSearchGroups = False if flagSearchGroups and self.searchGroupGroupName(groupName): self.printERROR(\ @@ -2357,7 +2359,7 @@ class servUnix(shareLdap): self.clVars.Set("ur_group",groupName) # номер группы gid = str(self.getMaxGid()) - if options.has_key('g'): + if 'g' in options: gid = options['g'] try: int(gid) @@ -2378,20 +2380,20 @@ class servUnix(shareLdap): self.clVars.Set("ur_group_id", gid) # Коментарий к группе gecos = self.groupGecos - if options.has_key('c'): + if 'c' in options: gecos = options['c'] self.clVars.Set("ur_group_comment",gecos) ldifFile = self.ldifFileGroup groupLdif = self.createLdif(ldifFile) if not groupLdif: - print self.getError() + print(self.getError()) return False if not self.ldapObj.getError(): self.ldapObj.ldapAdd(groupLdif) if self.ldapObj.getError(): - print _("LDAP Error") + ": " + self.ldapObj.getError().strip() + print(_("LDAP Error") + ": " + self.ldapObj.getError().strip()) return False - if options.has_key('p'): + if 'p' in options: sys.stdout.write(gid) else: if printSuccess: @@ -2438,7 +2440,7 @@ class servUnix(shareLdap): #Добавляем пользователя в LDAP self.ldapObj.ldapAdd(userLdif) if self.ldapObj.getError(): - print _("LDAP Error") + ": " + self.ldapObj.getError().strip() + print(_("LDAP Error") + ": " + self.ldapObj.getError().strip()) return False self.printSUCCESS(_("Added machine")) return True @@ -2461,15 +2463,15 @@ class servUnix(shareLdap): self.clVars.Set("ur_name", userName) baseDir = self.baseDir # Базовая домашняя директория - if options.has_key('b'): + if 'b' in options: baseDir = options['b'] # Устанавливаем скелетную директорию - if options.has_key('k'): + if 'k' in options: skelDir = options['k'] else: skelDir = self.skelDir # Устанавливаем домашнюю директорию - if options.has_key('d'): + if 'd' in options: homeDir = options['d'] else: homeDir = os.path.join(baseDir, userName) @@ -2477,22 +2479,22 @@ class servUnix(shareLdap): fullNameUser = self.fullNameUser # Полное имя пользователя - if options.has_key('c'): + if 'c' in options: fullNameUser = options['c'] self.clVars.Set("ur_fio",fullNameUser) # По умолчанию пользователя не видно visible = '0' - if options.has_key('v'): + if 'v' in options: visible = '1' self.clVars.Set("ur_visible",visible) # Оболочка пользователя userShell = self.userShell - if options.has_key('s'): + if 's' in options: userShell = options['s'] self.clVars.Set("ur_shell", userShell) # id пользователя - if options.has_key('u'): + if 'u' in options: userId = options['u'] try: int(userId) @@ -2511,17 +2513,17 @@ class servUnix(shareLdap): self.clVars.Set("ur_id",userId) # Добавляем пользователя в группы (находим имена групп) - if options.has_key('G'): + if 'G' in options: userGroups = options['G'].split(',') data = self.servSambaObj.searchUnixAndSambaGroups(userGroups, callSamba) - if data and type(data) == types.TupleType: + if data and type(data) == tuple: userGroupNamesUnix, userGroupNamesSamba = data else: return False userGid = str(self.getMaxGid()) # Группа пользователя - if options.has_key('g'): + if 'g' in options: userGid = options['g'] retCondUnix, userGidNamesUnix, errMessUnix =\ self.searchGroupsUnix([userGid], False) @@ -2589,7 +2591,7 @@ class servUnix(shareLdap): # флаги добавления flagAdd = {} # Добавление основной группы пользователя - if options.has_key('g'): + if 'g' in options: resLdap = self.searchUnixGroupName(groupName) if not resLdap and callSamba: resLdap = self.servSambaObj.searchSambaGroupName(groupName) @@ -2617,14 +2619,14 @@ class servUnix(shareLdap): self.ldapObj.ldapAdd(userLdif) #Добавляем пользователя в дополнительные группы (опция G) - if options.has_key('G') and userGroupNamesUnix: + if 'G' in options and userGroupNamesUnix: for group in userGroupNamesUnix: if not self.addUsersGroupUnix([userName], group): flagError = True break # не переделывать на else if self.ldapObj.getError(): - print _("LDAP Error") + ": " + self.ldapObj.getError().strip() + print(_("LDAP Error") + ": " + self.ldapObj.getError().strip()) flagError = True removeHomeBack = False if not flagError: @@ -2647,14 +2649,14 @@ class servUnix(shareLdap): if not flagError and not self.setShadowLastChange(userName): flagError = True # Добавим домашнюю директорию - if not flagError and createDirHome and options.has_key('m'): + if not flagError and createDirHome and 'm' in options: if not os.path.exists(homeDir): if not self.createHomeDir(userName, homeDir, skelDir): self.printERROR (_("ERROR") + ": " +\ _("cannot create HOME dir")) flagError = True #загружаем картинку - if not flagError and options.has_key('i'): + if not flagError and 'i' in options: photoFile = options['i'] if not self.setJpegPhotoUser(userName, photoFile): self.printERROR(_("Can not add jpeg photo for user") + " " +\ @@ -2665,11 +2667,11 @@ class servUnix(shareLdap): self.printERROR (_("Can not add user")+ " " + str(userName)) return False if printSuccess: - if flagAdd.has_key('group'): + if 'group' in flagAdd: self.printSUCCESS(_("Added group in Unix service")) - if createDirHome and options.has_key('m'): + if createDirHome and 'm' in options: self.printSUCCESS(_("Created home dir %s")%homeDir) - if options.has_key('i'): + if 'i' in options: self.printSUCCESS(_("Added jpeg photo %s")% photoFile) self.printSUCCESS(_("Added user in Unix service")) return True @@ -2680,7 +2682,7 @@ class servUnix(shareLdap): if not searchUser: return True modAttrs = [] - if searchUser[0][0][1].has_key('registeredAddress'): + if 'registeredAddress' in searchUser[0][0][1]: modAttrs.append((ldap.MOD_REPLACE, 'registeredAddress', jabberID)) else: modAttrs.append((ldap.MOD_ADD, 'registeredAddress', jabberID)) @@ -2698,7 +2700,7 @@ Unix service")) self.printERROR(_("User %s not found in Unix service")\ %str(userName)) return False - if searchUser[0][0][1].has_key('registeredAddress'): + if 'registeredAddress' in searchUser[0][0][1]: return searchUser[0][0][1]['registeredAddress'][0] else: return "" @@ -2722,7 +2724,7 @@ in Unix service")) %str(userName)) return False modAttrs = [] - if searchUser[0][0][1].has_key('mail'): + if 'mail' in searchUser[0][0][1]: modAttrs.append((ldap.MOD_REPLACE, 'mail', mail)) else: modAttrs.append((ldap.MOD_ADD, 'mail', mail)) @@ -2739,7 +2741,7 @@ in Unix service")) self.printERROR(_("User %s not found in Unix service")\ %str(userName)) return False - if searchUser[0][0][1].has_key('mail'): + if 'mail' in searchUser[0][0][1]: return searchUser[0][0][1]['mail'][0] else: return "" @@ -2809,7 +2811,7 @@ service")) if self.isServiceSetup("samba", False): maxGidSamba = self.servSambaObj.getMaxGidSamba() maxGids.append(maxGidSamba) - maxGid = max(map(lambda x: int(x), maxGids)) + maxGid = max(int(x) for x in maxGids) if maxGid == 0: return self.minGid else: @@ -2945,10 +2947,10 @@ service")) self.printERROR (_("ERROR") + ": " +\ _("User %s is not found in Unix service") % str(userName)) return False - if options.has_key('r'): + if 'r' in options: backup = False homeDir = False - if resLdap[0][0][1].has_key('homeDirectory'): + if 'homeDirectory' in resLdap[0][0][1]: #Домашняя директория пользователя homeDir = resLdap[0][0][1]['homeDirectory'][0] if backup and os.path.exists(homeDir) and\ @@ -2964,7 +2966,7 @@ service")) # Удаляем пользователя из групп if not self.delUserInGroup(userName): return False - if resLdap[0][0][1].has_key('gidNumber'): + if 'gidNumber' in resLdap[0][0][1]: gid = resLdap[0][0][1]['gidNumber'][0] else: resPasswd = self.searchPasswdUser(userName) @@ -2980,11 +2982,10 @@ service")) if resGroupSamba: # В случае отсутствия других пользователей удаляем # основную группу в Samba сервисе - if not resGroupSamba[0][0][1].has_key('memberUid'): + if 'memberUid' not in resGroupSamba[0][0][1]: groupName = resGroupSamba[0][0][1]['cn'][0] # Находим группы у которых есть аттрибут type - groupsSambaList = filter(\ - lambda x: x[1].type, self.staticGroups.items()) + groupsSambaList = [x for x in self.staticGroups.items() if x[1].type] groupsSamba = {} groupsSamba.update(groupsSambaList) # Группы которые нельзя удалять @@ -2998,7 +2999,7 @@ service")) if resGroup: # В случае отсутствия других пользователей # удаляем основную группу в Unix сервисе - if not resGroup[0][0][1].has_key('memberUid'): + if 'memberUid' not in resGroup[0][0][1]: groupName = resGroup[0][0][1]['cn'][0] if not self.delGroupUnixServer(groupName, {}, False): return False @@ -3057,11 +3058,11 @@ service")) _("User %s is not found in Unix service")%str(userName)) return False # Новые группы в которые входит пользователь - if options.has_key('G'): + if 'G' in options: userGroups = options['G'].split(',') data = self.servSambaObj.searchUnixAndSambaGroups(userGroups, callSamba) - if data and type(data) == types.TupleType: + if data and type(data) == tuple: userGroupNamesUnix, userGroupNamesSamba = data else: return False @@ -3078,11 +3079,11 @@ service")) if printSuccess: self.printSUCCESS(_("Replaced list of supplementary group")) # Добавляем группы в которые входит пользователь - elif options.has_key('a'): + elif 'a' in options: userGroups = options['a'].split(',') data = self.servSambaObj.searchUnixAndSambaGroups(userGroups, callSamba) - if data and type(data) == types.TupleType: + if data and type(data) == tuple: userGroupNamesUnix, userGroupNamesSamba = data else: return False @@ -3099,7 +3100,7 @@ service")) # Изменяемые аттрибуты пользователя modAttrs = [] # Изменяем первичную группу пользователя - if options.has_key('g'): + if 'g' in options: newFirstGroup = options['g'] # В случае вызова из Samba объекта ищем gid в Unix и Samba if callSamba: @@ -3138,33 +3139,33 @@ service")) modAttrs += [(ldap.MOD_REPLACE, 'gidNumber', userGid)] visible = False # пользователя видно - if options.has_key('V'): + if 'V' in options: visible = '1' # пользователя не видно - if options.has_key('I'): + if 'I' in options: visible = '0' if visible: modAttrs += [(ldap.MOD_REPLACE, 'shadowFlag', visible)] # Изменяем домашнюю директорию - if options.has_key('d'): + if 'd' in options: homeDir = options['d'] modAttrs += [(ldap.MOD_REPLACE, 'homeDirectory', homeDir)] # Включаем пользователя - if options.has_key('U'): + if 'U' in options: modAttrs += [(ldap.MOD_REPLACE, 'shadowExpire', "-1")] # Выключаем пользователя - if options.has_key('L'): + if 'L' in options: modAttrs += [(ldap.MOD_REPLACE, 'shadowExpire', "1")] # Изменяем комментарий к пользователю - if options.has_key('c'): + if 'c' in options: comment = options['c'] - if res[0][0][1].has_key('displayName'): + if 'displayName' in res[0][0][1]: modAttrs += [(ldap.MOD_REPLACE, 'displayName', comment), (ldap.MOD_REPLACE, 'cn', comment)] else: modAttrs += [(ldap.MOD_REPLACE, 'cn', comment)] # Изменяем оболочку пользователя - if options.has_key('s'): + if 's' in options: shell = options['s'] modAttrs.append((ldap.MOD_REPLACE, 'loginShell', shell)) # Изменяем пароль пользователя @@ -3175,7 +3176,7 @@ service")) userPwdHash = self.getHashPasswd(userPwd, self.userCrypt) if not userPwdHash: return False - if res[0][0][1].has_key('userPassword'): + if 'userPassword' in res[0][0][1]: modAttrs.append((ldap.MOD_REPLACE, 'userPassword', userPwdHash)) else: @@ -3186,7 +3187,7 @@ service")) if not self.modAttrsDN(DN, modAttrs): return False # Переносим домашнюю директорию пользователя - if options.has_key('d') and options.has_key('m'): + if 'd' in options and 'm' in options: homeDirOld = res[0][0][1]['homeDirectory'][0] homeDirNew = homeDir textLine = self.execProg("mv %s %s" %(homeDirOld, homeDirNew)) @@ -3199,7 +3200,7 @@ service")) else: if printSuccess: self.printSUCCESS(_("Moved home directory")) - if options.has_key('P') or options.has_key('p'): + if 'P' in options or 'p' in options: # Изменим время последнего измения пароля пользователя if not self.setShadowLastChange(userName): return False @@ -3207,7 +3208,7 @@ service")) self.printSUCCESS(\ _("Modified user password of Unix service")) if printSuccess: - if options.has_key('g'): + if 'g' in options: flagInt = False try: int(newFirstGroup) @@ -3218,20 +3219,20 @@ service")) if flagInt: self.printSUCCESS(_("Modified GID primary group to %s")\ %newFirstGroup) - if options.has_key('c'): + if 'c' in options: self.printSUCCESS(_("Modified comment")) - if options.has_key('s'): + if 's' in options: self.printSUCCESS(_("Modified shell")) - if options.has_key('d'): + if 'd' in options: self.printSUCCESS(_("Modified home directory")) - if options.has_key('U'): + if 'U' in options: self.printSUCCESS(_("Unlocked user %s")% str(userName)) - if options.has_key('I'): + if 'I' in options: self.printSUCCESS(\ _("User %s is invisible")% str(userName)) - if options.has_key('V'): + if 'V' in options: self.printSUCCESS(_("User %s is visible")% str(userName)) - if options.has_key('L'): + if 'L' in options: self.printSUCCESS(_("Locked user %s")% str(userName)) return True @@ -3248,18 +3249,18 @@ service")) # Изменяемые аттрибуты пользователя modAttrs = [] # Удаляем пароль пользователя - if options.has_key('d'): - if res[0][0][1].has_key('userPassword'): + if 'd' in options: + if 'userPassword' in res[0][0][1]: modAttrs += [(ldap.MOD_DELETE, 'userPassword', None)] else: self.printERROR(\ _("User %s has not password for Unix service")%\ str(userName)) # Включаем пользователя - if options.has_key('u'): + if 'u' in options: modAttrs += [(ldap.MOD_REPLACE, 'shadowExpire', "-1")] # Выключаем пользователя - elif options.has_key('l'): + elif 'l' in options: modAttrs += [(ldap.MOD_REPLACE, 'shadowExpire', "1")] if not options: optPasswd = {"p":""} @@ -3272,7 +3273,7 @@ service")) userPwdHash = self.getHashPasswd(userPwd, self.userCrypt) if not userPwdHash: return False - if res[0][0][1].has_key('userPassword'): + if 'userPassword' in res[0][0][1]: modAttrs.append((ldap.MOD_REPLACE, 'userPassword', userPwdHash)) else: @@ -3283,14 +3284,14 @@ service")) DN = self.addDN("uid="+userName, self.relUsersDN) if not self.modAttrsDN(DN, modAttrs): return False - if options.has_key('d'): + if 'd' in options: self.printSUCCESS( _("Deleted password of Unix service for user")+ " " +\ str(userName)) - if options.has_key('l'): + if 'l' in options: self.printSUCCESS(_("Locked user") + " " + str(userName) +\ " " +_("of Unix service")) - if options.has_key('u'): + if 'u' in options: self.printSUCCESS(_("Unlocked user") + " " + str(userName) +\ " " +_("of Unix service")) if not options: @@ -3310,7 +3311,7 @@ service")) self.printERROR(_("group name not found in Unix service")) return False # Добавляем список пользователей в группу - if options.has_key('a'): + if 'a' in options: # добавляемые пользователи в группу users = options['a'].split(',') res = self.addUsersGroupUnix(users, groupName) @@ -3323,7 +3324,7 @@ service")) " " + str(groupName)) return False # Удаляем список пользователей из группы - if options.has_key('d'): + if 'd' in options: # удаляемые пользователи из группы users = options['d'].split(',') res = self.delUsersGroupUnix(users, groupName) @@ -3337,7 +3338,7 @@ service")) return False modGroupName = groupName # Изменяем имя группы - if options.has_key('n'): + if 'n' in options: newGroupName = options['n'] if self.searchUnixGroupName(newGroupName): self.printERROR( @@ -3364,19 +3365,19 @@ service")) return False modAttrs = [] # Изменяем комментарий к группе - if options.has_key('c'): + if 'c' in options: gecos = options['c'] modAttrs.append((ldap.MOD_REPLACE, 'description', gecos)) if modAttrs: groupDN = self.addDN("cn=" + modGroupName, self.relGroupsDN) res = self.modAttrsDN(groupDN, modAttrs) if res: - if options.has_key('c'): + if 'c' in options: if printSuccess: self.printSUCCESS(_("Modified group comment")) return True else: - if options.has_key('c'): + if 'c' in options: self.printSUCCESS(_("Can not modify group comment")) return False @@ -3421,7 +3422,7 @@ service")) if not res : self.printERROR(_("group name is not found in Unix service")) return False - if not res[0][0][1].has_key("memberUid"): + if "memberUid" not in res[0][0][1]: if not getPrimaryUsers(): return False self.printERROR( @@ -3454,7 +3455,7 @@ service")) # Создаем объект переменных и начальная проверка if not self.initialChecksSetup(): return False - if options.has_key("f"): + if "f" in options: forceOptions = True # В случае если сервер установлен if self.clVars.Get("sr_unix_set") == "on" and\ @@ -3550,7 +3551,7 @@ service")) if not self.ldapObj.getError(): self.ldapObj.ldapAdd(baseLdif) if self.ldapObj.getError(): - print _("LDAP Error") + ": " + self.ldapObj.getError().strip() + print(_("LDAP Error") + ": " + self.ldapObj.getError().strip()) return False self.printOK(_("Added ldif file") + " ...") # Записываем данные администратора сервиса Unix @@ -3655,7 +3656,7 @@ class servMail(shareLdap): #почтовая директория пользователя mailDir = os.path.join(self.clVars.Get("sr_mail_path"), userName) - if options.has_key('r'): + if 'r' in options: backup = False # Делаем сохранение данных удаляемого пользователя if backup and os.path.exists(mailDir) and os.listdir(mailDir): @@ -3746,7 +3747,7 @@ for user %s in 'Replication/Mail' branch") %str(userName)) if not res : self.printERROR(_("group name is not found in Mail service")) return False - if not res[0][0][1].has_key("rfc822member"): + if "rfc822member" not in res[0][0][1]: self.printERROR(\ _("Member list of group %s is empty")%str(groupName)) return False @@ -3808,7 +3809,7 @@ for group %s in 'Replication/Mail' branch") %str(userName)) res = self.searchMailUserToName(userName) if not res: return False - if not res[0][0][1].has_key('mailAlternateAddress'): + if 'mailAlternateAddress' not in res[0][0][1]: return True modAttrs = [(ldap.MOD_DELETE, 'mailAlternateAddress', None)] userDN = self.addDN("uid=" + userName, self.relUsersDN) @@ -3825,11 +3826,11 @@ for group %s in 'Replication/Mail' branch") %str(userName)) if not searchGroup: self.printERROR(_("group name not found in Mail service")) return False - if options.has_key('n') and options.has_key('e'): + if 'n' in options and 'e' in options: self.printERROR(_("Command Line Options '-n' and '-e' are \ incompatible, use one of the options")) return False - if options.has_key('hide') and options.has_key('hide-off'): + if 'hide' in options and 'hide-off' in options: self.printERROR(_("Command Line Options '--hide' and '--hide-off' \ are incompatible, use one of the options")) return False @@ -3843,20 +3844,19 @@ are incompatible, use one of the options")) # Объект сервис репликации servReplObj = servRepl() filterHosts = [] - if options.has_key('hide'): + if 'hide' in options: filterHosts = options['hide'].split(",") - if searchGroup[0][0][1].has_key('filtersender'): + if 'filtersender' in searchGroup[0][0][1]: attrDeleteFirst.append((ldap.MOD_DELETE, 'filtersender', None)) domain = self.clVars.Get('os_net_domain') # Если необходимо добавляем домен к именам хостов - fHosts = map(lambda x: (not '.' in x and x+"."+domain) or x, - filterHosts) + fHosts = [(not '.' in x and x + "." + domain) or x for x in filterHosts] for host in fHosts: attrAppend.append((ldap.MOD_ADD, 'filtersender', host)) - if options.has_key('hide-off'): - if searchGroup[0][0][1].has_key('filtersender'): + if 'hide-off' in options: + if 'filtersender' in searchGroup[0][0][1]: attrDeleteFirst.append((ldap.MOD_DELETE, 'filtersender', None)) - if options.has_key('e'): + if 'e' in options: altMails = options['e'].split(",") email = searchGroup[0][0][1]["mail"][0] altEmails = searchGroup[0][0][1]["mailAlternateAddress"] @@ -3922,14 +3922,14 @@ mail user or group: %s")%foundReplUser) "(%s)"%", ".join(altMails) self.printERROR(errorMsg) return False - if options.has_key('hide-off'): + if 'hide-off' in options: if not servReplObj.deleteHideHosts(groupName): errorMsg = _("Can not delete hide host in mail alias,") +\ " " + _("for name %s")%groupName self.printERROR(errorMsg) return False # Добавляем список пользователей в группу - if options.has_key('a'): + if 'a' in options: # добавляемые пользователи в группу users = options['a'].split(',') res = self.addUsersGroupMail(users, groupName) @@ -3941,7 +3941,7 @@ mail user or group: %s")%foundReplUser) " " + str(groupName)) return False # Удаляем список пользователей из группы - if options.has_key('d'): + if 'd' in options: # удаляемые пользователи из группы users = options['d'].split(',') res = self.delUsersGroupMail(users, groupName) @@ -3954,7 +3954,7 @@ mail user or group: %s")%foundReplUser) return False # Изменяем имя группы modGroupName = groupName - if options.has_key('n'): + if 'n' in options: newGroupName = options['n'] if self.searchMailGroupToName(newGroupName): self.printERROR( @@ -4006,11 +4006,11 @@ in 'Replication/Mail' branch") %groupName) return False modAttrs = attrDeleteFirst + attrAppend + attrDelete # Изменяем комментарий к группе - if options.has_key('c'): + if 'c' in options: gecos = options['c'] modAttrs.append((ldap.MOD_REPLACE, 'description', gecos)) if not modAttrs: - if options.has_key('hide-off'): + if 'hide-off' in options: self.printWARNING(\ _("Hide mail hosts have already been deleted")) return True @@ -4018,23 +4018,23 @@ in 'Replication/Mail' branch") %groupName) groupDN = self.addDN("cn=" + modGroupName, self.relGroupsDN) res = self.modAttrsDN(groupDN, modAttrs) if res: - if options.has_key('c'): + if 'c' in options: self.printSUCCESS(_("Modified group comment")) - if options.has_key('e'): + if 'e' in options: self.printSUCCESS(_("Modified mail alternate address")) - if options.has_key('hide'): + if 'hide' in options: self.printSUCCESS(_("Modified hide mail hosts")) - if options.has_key('hide-off'): + if 'hide-off' in options: self.printSUCCESS(_("Deleted hide mail hosts")) return True else: - if options.has_key('c'): + if 'c' in options: self.printERROR(_("Can not modify group comment")) - if options.has_key('e'): + if 'e' in options: self.printERROR(_("Can not modify mail alternate address")) - if options.has_key('hide'): + if 'hide' in options: self.printERROR(_("Can not modify hide mail hosts")) - if options.has_key('hide-off'): + if 'hide-off' in options: self.printERROR(_("Can not delete hide mail hosts")) return False return True @@ -4052,7 +4052,7 @@ in 'Replication/Mail' branch") %groupName) str(userName)) return False # Новые группы в которые входит пользователь - if options.has_key('G'): + if 'G' in options: userGroups = options['G'].split(',') #список имен добавляемых групп userGroupNames = self.searchGroupsMail(userGroups) @@ -4070,7 +4070,7 @@ in 'Replication/Mail' branch") %groupName) return False self.printSUCCESS(_("Replaced list of supplementary group")) # Добавляем группы в которые входит пользователь - elif options.has_key('a'): + elif 'a' in options: userGroups = options['a'].split(',') #список имен добавляемых групп userGroupNames = self.searchGroupsMail(userGroups) @@ -4087,14 +4087,14 @@ in 'Replication/Mail' branch") %groupName) # Изменяемые аттрибуты пользователя modAttrs = [] # Включаем пользователя - if options.has_key('U'): + if 'U' in options: modAttrs += [(ldap.MOD_REPLACE, 'accountStatus', "active")] # Выключаем пользователя - elif options.has_key('L'): + elif 'L' in options: modAttrs += [(ldap.MOD_REPLACE, 'accountStatus', "passive")] # Изменяем комментарий к пользователю - if options.has_key('c'): + if 'c' in options: comment = options['c'] modAttrs += [(ldap.MOD_REPLACE, 'sn', comment), (ldap.MOD_REPLACE, 'cn', comment)] @@ -4106,7 +4106,7 @@ in 'Replication/Mail' branch") %groupName) userPwdHash = self.getHashPasswd(userPwd, self.userCrypt) if not userPwdHash: return False - if res[0][0][1].has_key('userPassword'): + if 'userPassword' in res[0][0][1]: modAttrs.append((ldap.MOD_REPLACE, 'userPassword', userPwdHash)) else: @@ -4116,7 +4116,7 @@ in 'Replication/Mail' branch") %groupName) # Первичный почтовый адрес primaryMail = "" altMails = [] - if options.has_key('e'): + if 'e' in options: altEmails = res[0][0][1]["mailAlternateAddress"] altMails = options['e'].split(",") for altMail in altMails: @@ -4180,15 +4180,15 @@ for user %s in 'Replication/Mail' branch") %userName) DN = self.addDN("uid="+userName, self.relUsersDN) if not self.modAttrsDN(DN, modAttrs): return False - if options.has_key('c'): + if 'c' in options: self.printSUCCESS(_("Modified comment")) - if options.has_key('L'): + if 'L' in options: self.printSUCCESS(_("Locked Mail user %s")%str(userName)) - if options.has_key('U'): + if 'U' in options: self.printSUCCESS(_("Unlocked Mail user %s")%str(userName)) - if options.has_key('e'): + if 'e' in options: self.printSUCCESS(_("Modified Mail alternate addresses")) - if options.has_key('P') or options.has_key('p'): + if 'P' in options or 'p' in options: self.printSUCCESS(_("Modified Mail user password")) return True @@ -4210,7 +4210,7 @@ for user %s in 'Replication/Mail' branch") %userName) #Проверяем альтернативные почтовые адреса modAttrs = [] altMails = [] - if options.has_key('e'): + if 'e' in options: altMails = options['e'].split(",") for altMail in altMails: if "@" in altMail: @@ -4239,7 +4239,7 @@ mail user or group: %s")%foundReplUser) modAttrs.append('mailAlternateAddress: %s' %mail) # Фильтр почты (hostname) fHostNames = [] - if options.has_key('hide'): + if 'hide' in options: fHostNames = options['hide'].split(",") for fHostName in fHostNames: if not "." in fHostName: @@ -4270,19 +4270,19 @@ mail user or group: %s")%foundReplUser) self.clVars.Set("ur_group", groupName) # Комментарий к группе groupGecos = self.servUnixObj.groupGecos - if options.has_key('c'): + if 'c' in options: groupGecos = options['c'] self.clVars.Set("ur_group_comment",groupGecos) ldifFile = self.ldifFileGroup groupRawLdif = self.createLdif(ldifFile) if not groupRawLdif: - print self.getError() + print(self.getError()) return False groupLdif = groupRawLdif.rstrip() + "\n" + "\n".join(modAttrs) if not self.ldapObj.getError(): self.ldapObj.ldapAdd(groupLdif) if self.ldapObj.getError(): - print _("LDAP Error") + ": " + self.ldapObj.getError().strip() + print(_("LDAP Error") + ": " + self.ldapObj.getError().strip()) return False if servReplObj: # Записываем почтовые алиасы в ветку @@ -4311,10 +4311,10 @@ for user %s in 'Replication/Mail' branch") %str(primaryMail)) # Изменяемые аттрибуты пользователя modAttrs = [] # Включаем пользователя - if options.has_key('u'): + if 'u' in options: modAttrs += [(ldap.MOD_REPLACE, 'accountStatus', "active")] # Выключаем пользователя - elif options.has_key('l'): + elif 'l' in options: modAttrs += [(ldap.MOD_REPLACE, 'accountStatus', "passive")] if not options: optPasswd = {"p":""} @@ -4324,7 +4324,7 @@ for user %s in 'Replication/Mail' branch") %str(primaryMail)) userPwdHash = self.getHashPasswd(userPwd, self.userCrypt) if not userPwdHash: return False - if res[0][0][1].has_key('userPassword'): + if 'userPassword' in res[0][0][1]: modAttrs.append((ldap.MOD_REPLACE, 'userPassword', userPwdHash)) else: @@ -4334,9 +4334,9 @@ for user %s in 'Replication/Mail' branch") %str(primaryMail)) DN = self.addDN("uid="+userName, self.relUsersDN) if not self.modAttrsDN(DN, modAttrs): return False - if options.has_key('l'): + if 'l' in options: self.printSUCCESS(_("Locked Mail user %s")% str(userName)) - if options.has_key('u'): + if 'u' in options: self.printSUCCESS(_("Unlocked Mail user %s")% str(userName)) if not options: self.printSUCCESS(_("Changed Mail user password")) @@ -4355,7 +4355,7 @@ for user %s in 'Replication/Mail' branch") %str(primaryMail)) return False else: findUsers = [] - if res[0][0][1].has_key('rfc822member'): + if 'rfc822member' in res[0][0][1]: usersInGroup = res[0][0][1]['rfc822member'] for userName in usersNames: userMail = "%s@%s" %(userName, @@ -4459,7 +4459,7 @@ for user %s in 'Replication/Mail' branch") %str(primaryMail)) addUsers.append(user) modAttrs = [] for userName in addUsers: - userMail = "%s@%s" %(userName,self.clVars.Get("sr_mail_host")) + userMail = "%s@%s" % (userName, self.clVars.Get("sr_mail_host")) modAttrs.append((ldap.MOD_ADD, 'rfc822member', userMail)) if modAttrs: groupDN = self.addDN("cn="+groupName, self.relGroupsDN) @@ -4498,7 +4498,7 @@ for user %s in 'Replication/Mail' branch") %str(primaryMail)) modAttrs = [] primaryMail = "" altMails = [] - if options.has_key('e'): + if 'e' in options: altMails = options['e'].split(",") for altMail in altMails: if "@" in altMail: @@ -4572,7 +4572,7 @@ mail user or group: %s")%foundReplUser) # Флаг создания группы по умолчанию flagCreateUnixGroup = False # Группа пользователя - if options.has_key('g'): + if 'g' in options: optUnix['g'] = options['g'] else: optUnix['g'] = self.defaultUnixGroup["name"] @@ -4588,7 +4588,7 @@ mail user or group: %s")%foundReplUser) if not self.servUnixObj.searchUnixGroupName(optUnix['g']): flagCreateUnixGroup = True # Полное имя пользователя - if options.has_key('c'): + if 'c' in options: optUnix['c'] = options['c'] # Если нужно создаем новую Unix группу if flagCreateUnixGroup: @@ -4609,10 +4609,10 @@ mail user or group: %s")%foundReplUser) self.clVars.Set("ur_name", userName) #Полное имя пользователя fullNameUser = self.servUnixObj.fullNameUser - if options.has_key('c'): + if 'c' in options: fullNameUser = options['c'] else: - if resUnix and resUnix[0][0][1].has_key('cn'): + if resUnix and 'cn' in resUnix[0][0][1]: fullNameUser = resUnix[0][0][1]['cn'][0] self.clVars.Set("ur_fio",fullNameUser) if not userPwd: @@ -4627,7 +4627,7 @@ mail user or group: %s")%foundReplUser) ldifFile = self.ldifFileUser userRawLdif = self.createLdif(ldifFile) if not userRawLdif: - print self.getError() + print(self.getError()) if flagCreateUnixUser: self.servUnixObj.delUserUnixServer(userName, {}, False, False) return False @@ -4639,7 +4639,7 @@ mail user or group: %s")%foundReplUser) # не переделывать на else flagError = False if self.ldapObj.getError(): - print _("LDAP Error") + ": " + self.ldapObj.getError().strip() + print(_("LDAP Error") + ": " + self.ldapObj.getError().strip()) flagError = True if not flagError: if resUnix: @@ -4701,8 +4701,8 @@ for user %s in 'Replication/Mail' branch") %userName) self.clVars должен быть определен """ - print _("Enter the allowed ip addresses and network for %s service")\ - %"Mail" + " (" + _("comma or space delimited") + ")" + print(_("Enter the allowed ip addresses and network for %s service")\ + %"Mail" + " (" + _("comma or space delimited") + ")") strPrompt = _("allow networks: ") netAllow = self.clVars.Get("sr_mail_net_allow") strNetAllow = "" @@ -4734,10 +4734,10 @@ for user %s in 'Replication/Mail' branch") %userName) return False def printW(): - print _("Incorrect string hostname") - print _("Try again\n") + print(_("Incorrect string hostname")) + print(_("Try again\n")) - print _("Enter the hostname for %s service")%"Mail" + print(_("Enter the hostname for %s service")%"Mail") strPrompt = _("hostname: ") hostname = self.clVars.Get("sr_mail_host") hostname = self.raw_input(strPrompt, hostname) @@ -4779,7 +4779,7 @@ if you want to continue to run the program again")) """Начальная настройка Mail сервиса""" # Принудительная установка forceOptions = False - if options.has_key("f"): + if "f" in options: forceOptions = True # Создаем объект переменных и начальная проверка if not self.initialChecksSetup(): @@ -4811,13 +4811,13 @@ if you want to continue to run the program again")) _("input 'yes'") +", "+ _("if not 'no'") if not self.dialogYesNo(messDialog): return True - if options.has_key("a"): + if "a" in options: # Получаем от пользователя доверительные сети allowNet = self.getAllowNet() if not allowNet: return False else: - if options.has_key("a"): + if "a" in options: # Получаем от пользователя доверительные сети allowNet = self.getAllowNet() if not allowNet: @@ -4867,7 +4867,7 @@ if you want to continue to run the program again")) # Почтовый ност fullHostName = "%s.%s"%(self.clVars.Get('os_net_hostname'), self.clVars.Get('os_net_domain')) - if options.has_key("host"): + if "host" in options: fullHostName = options['host'] if not "." in fullHostName: fullHostName = "%s.%s" %(fullHostName, @@ -4875,7 +4875,7 @@ if you want to continue to run the program again")) self.clVars.Set("sr_mail_host",fullHostName,True) history,history_domain,history_path = self.getMailHistoryData(options) mailType = "imap" - if options.has_key("t"): + if "t" in options: mailType = options['t'] if mailType: if not set(mailType.split(",")) <= set(["imap","pop3"]): @@ -4889,7 +4889,7 @@ if you want to continue to run the program again")) return False self.clVars.Set("sr_mail_type", mailType) mailCrypt = "tls" - if options.has_key("c"): + if "c" in options: mailCrypt = options['c'] if not mailCrypt in ["none", "tls"]: self.printERROR(_("Мail encryption not 'none' or 'tls'")) @@ -4933,7 +4933,7 @@ if you want to continue to run the program again")) if not self.ldapObj.getError(): self.ldapObj.ldapAdd(baseLdif) if self.ldapObj.getError(): - print _("LDAP Error") + ": " + self.ldapObj.getError().strip() + print(_("LDAP Error") + ": " + self.ldapObj.getError().strip()) return False # Записываем данные администратора сервиса Mail ldapParser = iniLdapParser() @@ -5092,7 +5092,7 @@ class servJabber(shareLdap): modAttrs = [] descr = groupSearch[0][0][1]["cn"][0] uid = userSearch[0][0][1]["uid"][0] - if userSearch[0][0][1].has_key('departmentNumber'): + if 'departmentNumber' in userSearch[0][0][1]: modAttrs.append((ldap.MOD_REPLACE, 'departmentNumber', descr)) else: modAttrs.append((ldap.MOD_ADD, 'departmentNumber', descr)) @@ -5107,7 +5107,7 @@ class servJabber(shareLdap): str(userName)) return False modAttrs = [] - if searchUser[0][0][1].has_key('mail'): + if 'mail' in searchUser[0][0][1]: modAttrs.append((ldap.MOD_REPLACE, 'mail', newJabberId)) else: modAttrs.append((ldap.MOD_ADD, 'mail', newJabberId)) @@ -5151,7 +5151,7 @@ in Jabber service")) flagFalse = True break if not replaceFlag and\ - userSearch[0][0][1].has_key('departmentNumber'): + 'departmentNumber' in userSearch[0][0][1]: self.printERROR(_("User %s is found in group")%\ str(userName) + " " + str(groupName)) flagFalse = True @@ -5176,7 +5176,7 @@ in Jabber service")) res = True for userName in users: userSearch = self.searchUserToNameOrId(userName) - if userSearch and userSearch[0][0][1].has_key('departmentNumber'): + if userSearch and 'departmentNumber' in userSearch[0][0][1]: if not userSearch[0][0][1]['departmentNumber'][0] == \ groupSearch[0][0][1]['cn'][0]: self.printERROR(_("User %s is not found in group")%\ @@ -5247,10 +5247,10 @@ in Jabber service")) # Изменяемые аттрибуты пользователя modAttrs = [] # Включаем пользователя - if options.has_key('u'): + if 'u' in options: modAttrs += [(ldap.MOD_REPLACE, 'initials', "Yes")] # Выключаем пользователя - elif options.has_key('l'): + elif 'l' in options: modAttrs += [(ldap.MOD_REPLACE, 'initials', "No")] if not options: optPasswd = {"p":""} @@ -5258,7 +5258,7 @@ in Jabber service")) if userPwd == False: return False userPwdHash = userPwd - if resSearch[0][0][1].has_key('userPassword'): + if 'userPassword' in resSearch[0][0][1]: modAttrs.append((ldap.MOD_REPLACE, 'userPassword', userPwdHash)) else: @@ -5269,9 +5269,9 @@ in Jabber service")) DN = self.addDN("uid="+userName, self.relUsersDN) if not self.modAttrsDN(DN, modAttrs): return False - if options.has_key('l'): + if 'l' in options: self.printSUCCESS(_("Locked Jabber user %s")% str(userName)) - if options.has_key('u'): + if 'u' in options: self.printSUCCESS(_("Unlocked Jabber user %s")%\ str(userName)) if not options: @@ -5294,7 +5294,7 @@ in Jabber service")) modAttrs = [] # Изменяем Jabber ID jabber_hosts = self.get_jabber_hosts() - if options.has_key('j'): + if 'j' in options: # Изменяем JID jabberId = options['j'] if not "@" in jabberId: @@ -5320,13 +5320,13 @@ in Jabber service")) self.printERROR(_("Failed set jabberID for user %s \ in Unix service") %str(jabberId)) return False - if res[0][0][1].has_key('mail'): + if 'mail' in res[0][0][1]: modAttrs.append((ldap.MOD_REPLACE, 'mail', jabberId)) else: modAttrs.append((ldap.MOD_ADD, 'mail', jabberId)) modAttrs.append((ldap.MOD_REPLACE,'cn',jabberId.partition("@")[0])) # Изменяет группу в которую входит пользователь - if options.has_key('g'): + if 'g' in options: userGroup = options['g'] if self.setUserGroup(userName, userGroup, res): self.printSUCCESS(_("Replaced user group")) @@ -5334,20 +5334,20 @@ in Unix service") %str(jabberId)) self.printERROR(_("Not replaced user group")) return False #загружаем картинку - if options.has_key('i'): + if 'i' in options: photoFile = options['i'] if not self.setJpegPhotoUser(userName, photoFile): self.printERROR(_("Can not add jpeg photo for user") + " " +\ str(userName)) return False # Включаем пользователя - if options.has_key('U'): + if 'U' in options: modAttrs += [(ldap.MOD_REPLACE, 'initials', "Yes")] # Выключаем пользователя - elif options.has_key('L'): + elif 'L' in options: modAttrs += [(ldap.MOD_REPLACE, 'initials', "No")] # Изменяем комментарий к пользователю - if options.has_key('c'): + if 'c' in options: comment = options['c'] modAttrs += [(ldap.MOD_REPLACE, 'sn', comment)] # Изменяем пароль пользователя @@ -5356,7 +5356,7 @@ in Unix service") %str(jabberId)) return False if userPwd: userPwdHash = userPwd - if res[0][0][1].has_key('userPassword'): + if 'userPassword' in res[0][0][1]: modAttrs.append((ldap.MOD_REPLACE, 'userPassword', userPwdHash)) else: @@ -5368,19 +5368,19 @@ in Unix service") %str(jabberId)) if not self.modAttrsDN(DN, modAttrs): return False if printSuccess: - if options.has_key('c'): + if 'c' in options: self.printSUCCESS(_("Modified comment (full name)")) - if options.has_key('L'): + if 'L' in options: self.printSUCCESS(_("Locked Jabber user %s")%str(userName)) - if options.has_key('U'): + if 'U' in options: self.printSUCCESS(_("Unlocked Jabber user %s")\ %str(userName)) - if options.has_key('P') or options.has_key('p'): + if 'P' in options or 'p' in options: self.printSUCCESS(_("Modified Jabber user password")) - if options.has_key('j'): + if 'j' in options: self.printSUCCESS(_("JID changed, a new JID is %s")\ %jabberId) - if printSuccess and options.has_key('i'): + if printSuccess and 'i' in options: self.printSUCCESS(_("Set image %s for Jabber user")%\ str(options['i']) + " " + str(userName)) return True @@ -5396,7 +5396,7 @@ in Unix service") %str(jabberId)) %str(groupName)) return False # Добавляем список пользователей в группу - if options.has_key('a'): + if 'a' in options: # добавляемые пользователи в группу users = options['a'].split(',') res = self.addUsersGroupJabber(users, groupName) @@ -5408,7 +5408,7 @@ in Unix service") %str(jabberId)) " " + str(groupName)) return False # Удаляем список пользователей из группы - if options.has_key('d'): + if 'd' in options: # удаляемые пользователи из группы users = options['d'].split(',') res = self.delUsersGroupJabber(users, groupName) @@ -5420,7 +5420,7 @@ in Unix service") %str(jabberId)) " " + str(groupName)) return False # Изменяем комментарий к группе - if options.has_key('c'): + if 'c' in options: gecos = options['c'] modAttrs = [(ldap.MOD_REPLACE, 'description', gecos)] groupDN = self.addDN("cn="+groupName, self.relGroupsDN) @@ -5431,7 +5431,7 @@ in Unix service") %str(jabberId)) " " + str(groupName)) return False # Изменяем имя группы - if options.has_key('n'): + if 'n' in options: newGroupName = options['n'] oldGroupName = searchGroup[0][0][1]["cn"][0] if self.renameGroup(oldGroupName, newGroupName): @@ -5517,18 +5517,18 @@ in Unix service") %str(jabberId)) self.clVars.Set("ur_group",groupName) # Комментарий к группе groupGecos = self.servUnixObj.groupGecos - if options.has_key('c'): + if 'c' in options: groupGecos = options['c'] self.clVars.Set("ur_group_comment",groupGecos) ldifFile = self.ldifFileGroup groupLdif = self.createLdif(ldifFile) if not groupLdif: - print self.getError() + print(self.getError()) return False if not self.ldapObj.getError(): self.ldapObj.ldapAdd(groupLdif) if self.ldapObj.getError(): - print _("LDAP Error") + ": " + self.ldapObj.getError().strip() + print(_("LDAP Error") + ": " + self.ldapObj.getError().strip()) return False self.printSUCCESS(_("Added group '%s' in Jabber service")\ %groupName) @@ -5544,7 +5544,7 @@ in Unix service") %str(jabberId)) searchUsers = self.searchAllUsers() flagError = False for fieldUser in searchUsers: - if fieldUser[0][1].has_key("mail"): + if "mail" in fieldUser[0][1]: userName = fieldUser[0][1]['uid'][0] jabberId = fieldUser[0][1]['mail'][0] cn = fieldUser[0][1]['cn'][0] @@ -5581,7 +5581,7 @@ in Unix service") %str(jabberId)) return False #jabber id jabberId = "%s@%s" %(userName,self.clVars.Get("sr_jabber_host")) - if options.has_key('j'): + if 'j' in options: # Изменяем JID jabberId = options['j'] if not "@" in jabberId: @@ -5617,7 +5617,7 @@ in Unix service") %str(jabberId)) self.clVars.Set("ur_name", userName) #Полное имя пользователя fullNameUser = self.servUnixObj.fullNameUser - if options.has_key('c'): + if 'c' in options: fullNameUser = options['c'] else: # Проверяем установку сервиса не печатая ошибку в случае @@ -5625,7 +5625,7 @@ in Unix service") %str(jabberId)) if self.isServiceSetup("unix",False): resUnix = self.servUnixObj.searchUnixUser(userName) # Берем комментарий для пользователя из Unix - if resUnix and resUnix[0][0][1].has_key('cn'): + if resUnix and 'cn' in resUnix[0][0][1]: fullNameUser = resUnix[0][0][1]['cn'][0] self.clVars.Set("ur_fio",fullNameUser) ldifFile = self.ldifFileUser @@ -5636,10 +5636,10 @@ in Unix service") %str(jabberId)) #ldapObj.ldapAdd(userLdif1) # не переделывать на else if self.ldapObj.getError(): - print _("LDAP Error") + ": " + self.ldapObj.getError().strip() + print(_("LDAP Error") + ": " + self.ldapObj.getError().strip()) return False # загружаем картинку - if options.has_key('i'): + if 'i' in options: photoFile = options['i'] if not self.setJpegPhotoUser(userName, photoFile): self.printERROR(_("Can not add jpeg photo for user") + " " +\ @@ -5653,7 +5653,7 @@ in Unix service") %str(jabberId)) """Начальная настройка Jabber сервиса""" # Принудительная установка forceOptions = False - if options.has_key("f"): + if "f" in options: forceOptions = True # Создаем объект переменных и начальная проверка if not self.initialChecksSetup(): @@ -5712,14 +5712,14 @@ in Unix service") %str(jabberId)) fullHostName = "%s.%s"%(self.clVars.Get('os_net_hostname'), self.clVars.Get('os_net_domain')) jabberHosts = fullHostName - if options.has_key("host"): + if "host" in options: fullHostName = options['host'] if not "." in fullHostName: fullHostName = "%s.%s" %(fullHostName, self.clVars.Get('os_net_domain')) self.clVars.Set("sr_jabber_host",fullHostName,True) # Устанавливаем дополнительные хосты jabber cервиса - if options.has_key("hosts"): + if "hosts" in options: hosts = options['hosts'].split(",") jabberHostsList = [self.clVars.Get("sr_jabber_host")] for host in hosts: @@ -5768,12 +5768,12 @@ in Unix service") %str(jabberId)) if not self.ldapObj.getError(): self.ldapObj.ldapAdd(baseLdif) if self.ldapObj.getError(): - print _("LDAP Error") + ": " + self.ldapObj.getError().strip() + print(_("LDAP Error") + ": " + self.ldapObj.getError().strip()) return False # Администратор сервиса adminName = "admin" adminFullName = "%s@%s" %(adminName, self.clVars.Get("sr_jabber_host")) - print _("Enter the %s password") %adminFullName + print(_("Enter the %s password") %adminFullName) if not self.addUserJabberServer(adminName,{'p':""}, False): return False # Записываем данные администратора сервиса Jabber @@ -5850,7 +5850,7 @@ class servSamba(shareLdap): Если группы нет она будет добавлена в противном случае пропущена """ # Находим группы у которых есть аттрибут type - groupsSambaList = filter(lambda x: x[1].type, self.staticGroups.items()) + groupsSambaList = [x for x in self.staticGroups.items() if x[1].type] groupsSamba = {} groupsSamba.update(groupsSambaList) flagError = False @@ -5903,7 +5903,7 @@ class servSamba(shareLdap): warning += _("If all clients of this server are calculate-client \ of version > 2.1.10, then you can delete this file.") + "\n" if not self.createUserFile(fileReplRun,warning,0,0, - mode=0644): + mode=0o644): return False return True @@ -5934,7 +5934,7 @@ of version > 2.1.10, then you can delete this file.") + "\n" if not res : self.printERROR(_("group name is not found in Samba service")) return False - if not res[0][0][1].has_key("memberUid"): + if "memberUid" not in res[0][0][1]: if not getPrimaryUsers(): return False self.printERROR( @@ -6038,7 +6038,7 @@ of version > 2.1.10, then you can delete this file.") + "\n" userNetlogonDir =\ os.path.join(self.clVars.Get("sr_samba_winlogon_path"), userName) - if options.has_key('r'): + if 'r' in options: backup = False # Делаем сохранение данных удаляемого пользователя if backup: @@ -6110,7 +6110,7 @@ of version > 2.1.10, then you can delete this file.") + "\n" if checkSetup and not self.initialChecks("samba"): return False # Добавление машины samba - if options.has_key('w'): + if 'w' in options: if self.addMachineSambaServer(userName, options): return True else: @@ -6146,25 +6146,25 @@ of version > 2.1.10, then you can delete this file.") + "\n" # Добавим пользователя LDAP optUnix = {} # id пользователя - if options.has_key('u'): + if 'u' in options: optUnix['u'] = options['u'] # Группа пользователя - if options.has_key('g'): + if 'g' in options: optUnix['g'] = options['g'] # Группы в которые входит пользователь - if options.has_key('G'): + if 'G' in options: optUnix['G'] = options['G'] # Полное имя пользователя - if options.has_key('c'): + if 'c' in options: optUnix['c'] = options['c'] # shell - if options.has_key('s'): + if 's' in options: optUnix['s'] = options['s'] # Домашняя директория - if options.has_key('d'): + if 'd' in options: optUnix['d'] = options['d'] # Cделаем пользователя видимым - if optUnix.has_key('u'): + if 'u' in optUnix: try: int(optUnix['u']) except: @@ -6199,11 +6199,11 @@ of version > 2.1.10, then you can delete this file.") + "\n" if textLine != False: flagError = False - if options.has_key('G'): + if 'G' in options: # Изменяем Samba группы пользователя userGroups = options['G'].split(',') data = self.searchUnixAndSambaGroups(userGroups, True) - if data and type(data) == types.TupleType: + if data and type(data) == tuple: userGroupNamesUnix, userGroupNamesSamba = data else: flagError = True @@ -6294,12 +6294,13 @@ of version > 2.1.10, then you can delete this file.") + "\n" uid = int(resPasswd.split(":")[2]) gid = int(resPasswd.split(":")[3]) # Не удаляемые директории - notDeletedDirs = filter(lambda x:x and os.path.exists(x), - (createDirHome,createDirLogon, + notDeletedDirs = [x for x in (createDirHome, createDirLogon, createDirWin7Profile, - createDirWinProfile,createDirLinProfile)) + createDirWinProfile, createDirLinProfile) + if x and os.path.exists(x)] + if (resPasswd or resSearchUnix) and\ - (options.has_key('n') or int(uid) >=1000): + ('n' in options or int(uid) >=1000): # Cоздаем домашнюю директорию if createDirHome: if not self.createUserDir(uid, gid, createDirHome): @@ -6417,7 +6418,7 @@ if %%errorlevel%%==0 NET USE T: \\\\%s\\ftp' %(netbios,netbios,netbios) return False else: findUsers = [] - if res[0][0][1].has_key('memberUid'): + if 'memberUid' in res[0][0][1]: usersInGroup = res[0][0][1]['memberUid'] for userName in usersNames: if userName in usersInGroup: @@ -6574,7 +6575,7 @@ Samba and Unix services") %", ".join(exclGroup) return False # Если группа существует выходим без ошибки flagSearchGroups = True - if options.has_key('f'): + if 'f' in options: flagSearchGroups = False if flagSearchGroups and\ self.servUnixObj.searchGroupGroupName(groupName): @@ -6595,7 +6596,7 @@ Samba and Unix services") %", ".join(exclGroup) self.clVars.Set("ur_group",groupName) # номер группы gid = str(self.servUnixObj.getMaxGid()) - if options.has_key('g'): + if 'g' in options: gid = options['g'] try: int(gid) @@ -6613,7 +6614,7 @@ Samba and Unix services") %", ".join(exclGroup) return False groupSid = "" # Получаем sid - if options.has_key('s'): + if 's' in options: # Проверяем кoрректность sid sidRe = re.compile("^S-(?:\d+-)+\d+$") if not sidRe.search(options['s']): @@ -6626,7 +6627,7 @@ Samba and Unix services") %", ".join(exclGroup) return False # Получаем samba rid sambaRid = str(2*int(gid)+1001) - if options.has_key('r'): + if 'r' in options: try: int(options['r']) except: @@ -6640,7 +6641,7 @@ Samba and Unix services") %", ".join(exclGroup) return False # По умолчанию тип группы - доменная группа groupType = "2" - if options.has_key('t'): + if 't' in options: try: int(options['t']) except: @@ -6660,20 +6661,20 @@ Samba and Unix services") %", ".join(exclGroup) self.clVars.Set("ur_group_id", gid) # Комментарий к группе gecos = self.servUnixObj.groupGecos - if options.has_key('c'): + if 'c' in options: gecos = options['c'] self.clVars.Set("ur_group_comment",gecos) ldifFile = self.ldifFileGroup groupLdif = self.createLdif(ldifFile) if not groupLdif: - print self.getError() + print(self.getError()) return False if not self.ldapObj.getError(): self.ldapObj.ldapAdd(groupLdif) if self.ldapObj.getError(): - print _("LDAP Error") + ": " + self.ldapObj.getError().strip() + print(_("LDAP Error") + ": " + self.ldapObj.getError().strip()) return False - if options.has_key('p'): + if 'p' in options: sys.stdout.write(gid) else: if printSuccess: @@ -6750,7 +6751,7 @@ Samba and Unix services") %", ".join(exclGroup) self.printERROR(_("group name not found in Samba service")) return False # Добавляем список пользователей в группу - if options.has_key('a'): + if 'a' in options: # добавляемые пользователи в группу users = options['a'].split(',') res = self.addUsersGroupSamba(users, groupName) @@ -6762,7 +6763,7 @@ Samba and Unix services") %", ".join(exclGroup) " " + str(groupName)) return False # Удаляем список пользователей из группы - if options.has_key('d'): + if 'd' in options: # удаляемые пользователи из группы users = options['d'].split(',') res = self.delUsersGroupSamba(users, groupName) @@ -6775,7 +6776,7 @@ Samba and Unix services") %", ".join(exclGroup) return False modGroupName = groupName # Изменяем имя группы - if options.has_key('n'): + if 'n' in options: newGroupName = options['n'] if self.servUnixObj.searchUnixGroupName(newGroupName): self.printERROR( @@ -6799,7 +6800,7 @@ Samba and Unix services") %", ".join(exclGroup) return False modAttrs = [] # Изменяем тип группы - if options.has_key('t'): + if 't' in options: try: int(options['t']) except: @@ -6814,7 +6815,7 @@ Samba and Unix services") %", ".join(exclGroup) groupType = options['t'] modAttrs.append((ldap.MOD_REPLACE, 'sambaGroupType', groupType)) # Изменяем комментарий к группе - if options.has_key('c'): + if 'c' in options: gecos = options['c'] modAttrs.append((ldap.MOD_REPLACE, 'description', gecos)) modAttrs.append((ldap.MOD_REPLACE, 'displayName', gecos)) @@ -6822,15 +6823,15 @@ Samba and Unix services") %", ".join(exclGroup) groupDN = self.addDN("cn=" + modGroupName, self.relGroupsDN) res = self.modAttrsDN(groupDN, modAttrs) if res: - if options.has_key('c'): + if 'c' in options: self.printSUCCESS(_("Modified group comment")) - if options.has_key('t'): + if 't' in options: self.printSUCCESS(_("Modified group type")) return True else: - if options.has_key('c'): + if 'c' in options: self.printERROR(_("Can not modify group comment")) - if options.has_key('t'): + if 't' in options: self.printERROR(_("Can not modify group type")) return False return True @@ -6840,7 +6841,7 @@ Samba and Unix services") %", ".join(exclGroup) machineLogin = machineName.replace('$','') + "$" res = self.searchSambaMachine(machineLogin) if res: - if res[0][0][1].has_key('sambaSID'): + if 'sambaSID' in res[0][0][1]: self.printERROR(_("machine")+" "+machineLogin+" "+\ "is found in Samba service") return True @@ -6883,8 +6884,8 @@ Samba and Unix services") %", ".join(exclGroup) self.clVars должен быть определен """ - print _("Enter the allowed ip addresses and network for %s service")\ - %"Samba" + " (" + _("comma or space delimited") + ")" + print(_("Enter the allowed ip addresses and network for %s service")\ + %"Samba" + " (" + _("comma or space delimited") + ")") strPrompt = _("allow networks: ") netAllow = self.clVars.Get("sr_samba_net_allow") strNetAllow = "" @@ -6905,7 +6906,7 @@ Samba and Unix services") %", ".join(exclGroup) # Создаем объект переменных и начальная проверка if not self.initialChecksSetup(): return False - if options.has_key("f"): + if "f" in options: forceOptions = True if self.clVars.Get("sr_unix_set") != "on": self.printERROR(_("Unix service is not setuped")) @@ -6932,13 +6933,13 @@ Samba and Unix services") %", ".join(exclGroup) _("input 'yes'") +", "+ _("if not 'no'") if not self.dialogYesNo(messDialog): return True - if options.has_key("a"): + if "a" in options: # Получаем от пользователя доверительные сети allowNet = self.getAllowNet() if not allowNet: return False else: - if options.has_key("a"): + if "a" in options: # Получаем от пользователя доверительные сети allowNet = self.getAllowNet() if not allowNet: @@ -6974,7 +6975,7 @@ Samba and Unix services") %", ".join(exclGroup) # Устанавливаем доступные сети self.clVars.Set("sr_samba_net_allow",allowNet,True) # Задаем рабочую группу (домен) - if options.has_key("w"): + if "w" in options: workgroup = options['w'].strip() if len(workgroup)>15: self.printERROR(_("A very long name of the command line \ @@ -6982,10 +6983,10 @@ options '-w, --workgroup'")) return False self.clVars.Set("sr_samba_domain",workgroup) # Задаем netbios имя - if options.has_key("n"): + if "n" in options: netbios = options['n'].strip() # Проверка на неравенство workgroup и netbios - if options.has_key("w") and workgroup == netbios: + if "w" in options and workgroup == netbios: self.printERROR(_("Value of command line option \ '-w, --workgroup' equal to value of command line option '-n, --netbios'")) return False @@ -7059,7 +7060,7 @@ options '-w, --workgroup'")) if not self.ldapObj.getError(): self.ldapObj.ldapAdd(baseLdif) if self.ldapObj.getError(): - print _("LDAP Error") + ": " + self.ldapObj.getError().strip() + print(_("LDAP Error") + ": " + self.ldapObj.getError().strip()) return False self.printOK(_("Added ldif file") + " ...") for service_initd, service_name in [("samba", "Samba"), ("calculate-profile", "Calculate Profile")]: @@ -7133,12 +7134,12 @@ options '-w, --workgroup'")) # права и владелец /var/calculate/remote if os.path.exists(remotePath): os.chown(remotePath,0,int(cl.gid)) - os.chmod(remotePath,02755) + os.chmod(remotePath,0o2755) # изменяем владельца remote на client if not os.path.exists(remoteEnvFile): fd = os.open(remoteEnvFile, os.O_CREAT) os.close(fd) - os.chmod(remoteEnvFile, 0640) + os.chmod(remoteEnvFile, 0o640) if os.path.exists(remoteEnvFile): os.chown(remoteEnvFile,0,int(cl.gid)) if not self.setDaemonAutostart("slapd"): @@ -7187,7 +7188,7 @@ options '-w, --workgroup'")) _("Samba user %s is not found")%str(userName)) return False # отключаем samba account - if options.has_key('l'): + if 'l' in options: textLine = self.execProg("smbpasswd -d %s" %(userName)) if textLine == False: self.printERROR(_("Can not disable Samba user")+ " "+\ @@ -7196,7 +7197,7 @@ options '-w, --workgroup'")) else: self.printSUCCESS(_("Disabled Samba user %s")%str(userName)) # включаем Samba account - if options.has_key('u'): + if 'u' in options: textLine = self.execProg("smbpasswd -e %s" %(userName)) if textLine == False: self.printERROR(_("Can not enable Samba user")+ " "+\ @@ -7204,14 +7205,14 @@ options '-w, --workgroup'")) return False else: self.printSUCCESS(_("Enabled Samba user %s")%str(userName)) - if not options or options.has_key('s'): + if not options or 's' in options: optPasswd = {"p":""} userPwd = self.getUserPassword(optPasswd, "p", False) if userPwd == False: return False if userPwd: # Опция s пароль только для Samba - if not options.has_key('s'): + if 's' not in options: if not self.servUnixObj.modUserUnixPasswd(userName,{}, userPwd): return False @@ -7240,7 +7241,7 @@ options '-w, --workgroup'")) str(userName)) return False # отключаем Samba account - if options.has_key('L'): + if 'L' in options: textLine = self.execProg("smbpasswd -d %s" %(userName)) if textLine == False: self.printERROR(_("Can not disable Samba user")+ " "+\ @@ -7249,7 +7250,7 @@ options '-w, --workgroup'")) else: self.printSUCCESS(_("Disabled Samba user %s")%str(userName)) # включаем samba account - elif options.has_key('U'): + elif 'U' in options: textLine = self.execProg("smbpasswd -e %s" %(userName)) if textLine == False: self.printERROR(_("Can not enable Samba user")+ " "+\ @@ -7258,14 +7259,14 @@ options '-w, --workgroup'")) else: self.printSUCCESS(_("Enabled Samba user %s")%str(userName)) # модифицируем пароль - if options.has_key('P') or options.has_key('p'): + if 'P' in options or 'p' in options: pwDialog = [_("New SMB password"), _("Retype new SMB password")] userPwd = self.getUserPassword(options, "p", "P", pwDialog) if userPwd == False: return False # Опция s пароль только для Samba - if not options.has_key('s'): + if 's' not in options: if not self.servUnixObj.modUserUnixPasswd(userName,{}, userPwd): return False @@ -7276,17 +7277,17 @@ options '-w, --workgroup'")) return False self.printSUCCESS(_("Modified Samba user password")) - if options.has_key("g"): + if "g" in options: optUnix = {'g':options['g']} if not self.servUnixObj.modUserUnixServer(userName, optUnix, True, True): return False # изменяем Unix и Samba группы в которые включен пользователь - if options.has_key("G"): + if "G" in options: # Изменяем Samba группы пользователя userGroups = options['G'].split(',') data = self.searchUnixAndSambaGroups(userGroups, True) - if data and type(data) == types.TupleType: + if data and type(data) == tuple: userGroupNamesUnix, userGroupNamesSamba = data else: return False @@ -7309,9 +7310,9 @@ options '-w, --workgroup'")) if printSuccess: self.printSUCCESS(_("Replaced list of supplementary group")) # Изменяем комментарий к пользователю - if options.has_key('c'): + if 'c' in options: comment = options['c'] - if res[0][0][1].has_key('displayName'): + if 'displayName' in res[0][0][1]: modAttrs = [(ldap.MOD_REPLACE, 'displayName', comment)] else: modAttrs = [(ldap.MOD_ADD, 'displayName', comment)] @@ -7388,7 +7389,7 @@ class servLdap(shareLdap): try: FD = open (fileName, "w+") FD.close() - os.chmod(fileName,0600) + os.chmod(fileName,0o600) FD = open (fileName, "w+") FD.write(data) FD.close() @@ -7444,7 +7445,7 @@ outdated. If the backup is obsolete, use cl-backup-server.")) # В случае создания сервера репликации из файла backup c # другого компьютера replServices = [] - if options.has_key("repl"): + if "repl" in options: # Находим имена сервисов репликации для этого сервера # и инициализируем переменные replServices = self.getArchReplServices() @@ -7467,9 +7468,9 @@ outdated. If the backup is obsolete, use cl-backup-server.")) return False verbose = False opt = {} - if options.has_key("v"): + if "v" in options: opt['v'] = '' - if options.has_key("a"): + if "a" in options: opt['a'] = '' # Сервисы для которых не будет задаваться вопрос о доступных сетях # при включенной опции allow @@ -7497,7 +7498,7 @@ outdated. If the backup is obsolete, use cl-backup-server.")) self.printERROR(clProf.getError()) return False else: - if verbose and type(data) == types.TupleType: + if verbose and type(data) == tuple: dirs, files = data return files return True @@ -7552,7 +7553,7 @@ outdated. If the backup is obsolete, use cl-backup-server.")) # Настройка прокси if serviceUpdate in ["all","proxy"]: # Порт для прокси сервера - if options.has_key("p"): + if "p" in options: proxyPort = options['p'] try: numberProxyPort = int(proxyPort) @@ -7561,7 +7562,7 @@ outdated. If the backup is obsolete, use cl-backup-server.")) return False proxyPort = str(numberProxyPort) self.clVars.Set("sr_proxy_port", proxyPort, True) - if options.has_key("host"): + if "host" in options: fullHostName = options['host'] if not "." in fullHostName: fullHostName = "%s.%s" %(fullHostName, @@ -7574,7 +7575,7 @@ outdated. If the backup is obsolete, use cl-backup-server.")) return False history,history_domain,history_path = \ self.getMailHistoryData(options) - if options.has_key("t"): + if "t" in options: mailType = options['t'] if mailType: if not set(mailType.split(",")) <= set(["imap","pop3"]): @@ -7587,7 +7588,7 @@ outdated. If the backup is obsolete, use cl-backup-server.")) self.printERROR(_("Мail type incorrect")) return False self.clVars.Set("sr_mail_type", mailType) - if options.has_key("c"): + if "c" in options: mailCrypt = options['c'] if not mailCrypt in ["none", "tls"]: self.printERROR(_("Мail encryption not 'none' or 'tls'")) @@ -7602,7 +7603,7 @@ outdated. If the backup is obsolete, use cl-backup-server.")) # Устанавливаем основной хост jabber cервиса if not self.createJabberCertificate(): return False - if options.has_key("host"): + if "host" in options: newHostName = options['host'] if not "." in newHostName: newHostName = "%s.%s" %(newHostName, @@ -7618,7 +7619,7 @@ outdated. If the backup is obsolete, use cl-backup-server.")) jabberHosts = ",".join(unicHostsList) self.clVars.Set("sr_jabber_hosts",jabberHosts,True) # Устанавливаем дополнительные хосты jabber cервиса - if options.has_key("hosts"): + if "hosts" in options: hosts = options['hosts'].split(",") jabberHostsList = [self.clVars.Get("sr_jabber_host")] for host in hosts: @@ -7670,7 +7671,7 @@ outdated. If the backup is obsolete, use cl-backup-server.")) self.clVars.Set("ld_%s_pw"%servicePwd, adminPw, True) # Наложение профилей verbose = False - if options.has_key("v"): + if "v" in options: verbose = True # Cервисы которые рестартуют servicesRestart = [] @@ -7685,7 +7686,7 @@ outdated. If the backup is obsolete, use cl-backup-server.")) if service == "samba": # Получаем от пoльзователя доверительные сети # для сервиса Samba - if options.has_key("a") and\ + if "a" in options and\ not service in noInputAllowNetServices: self.servSambaObj.clVars = self.clVars if not self.servSambaObj.getAllowNet(): @@ -7732,7 +7733,7 @@ outdated. If the backup is obsolete, use cl-backup-server.")) if service == "mail": # Получаем от пользователя доверительные сети # для сервиса Mail - if options.has_key("a") and\ + if "a" in options and\ not service in noInputAllowNetServices: self.servMailObj.clVars = self.clVars if not self.servMailObj.getAllowNet(): @@ -7745,7 +7746,7 @@ outdated. If the backup is obsolete, use cl-backup-server.")) if service == "proxy": # Получаем от пользователя доверительные сети # для сервиса Proxy - if options.has_key("a") and\ + if "a" in options and\ not service in noInputAllowNetServices: self.servProxyObj.clVars = self.clVars if not self.servProxyObj.getAllowNet(): @@ -7767,7 +7768,7 @@ outdated. If the backup is obsolete, use cl-backup-server.")) if not files: flagError = True break - if verbose and type(files) == types.ListType: + if verbose and type(files) == list: self.printSUCCESS(_("Updating config from service %s")\ %self.printNameService(service)) for applyFile in files: @@ -7839,7 +7840,7 @@ outdated. If the backup is obsolete, use cl-backup-server.")) if not flagError and serviceUpdate in ["all","jabber"]: # Замена имени хоста для сервиса Jabber в LDAP - if options.has_key("host"): + if "host" in options: if self.clVars.Get("sr_jabber_host") != previousJabberHost: # Установка в LDAP ветке Jabber cервиса нового имени хоста if not self.servJabberObj.setHostName(newHostName, @@ -7961,7 +7962,7 @@ outdated. If the backup is obsolete, use cl-backup-server.")) foundFiles = clProf.scanProfiles(serviceName) if not foundFiles: return [] - foundFiles = filter(lambda x: os.path.exists(x), foundFiles) + foundFiles = [x for x in foundFiles if os.path.exists(x)] return foundFiles def backupNotLdap(self): @@ -8045,7 +8046,7 @@ outdated. If the backup is obsolete, use cl-backup-server.")) # если существуют удаляем файлы в /tmp self.removeTmpFiles() if os.path.exists(bFile): - os.chmod(bFile,0600) + os.chmod(bFile,0o600) self.printSUCCESS(_("Created archive file") + ": " +\ str(bFile)) return True @@ -8306,8 +8307,8 @@ service %s")%service replArchFilesUnix.append(additFile) replArchFilesUnix = self.unicList(replArchFilesUnix) # Удаляем начальный "/" - replArchFilesUnix = map(lambda x:\ - "/".join(filter(lambda y:y ,x.split("/"))),replArchFilesUnix) + replArchFilesUnix = ["/".join(y for y in x.split("/") if y) + for x in replArchFilesUnix] replArchFilesUnix.sort() if "samba" in replServices: # Дополнительные файлы добавляемые в архив @@ -8318,8 +8319,8 @@ service %s")%service replArchFilesSamba.append(additFile) replArchFilesSamba += replArchFilesUnix # Удаляем начальный "/" - replArchFilesSamba = map(lambda x:\ - "/".join(filter(lambda y:y ,x.split("/"))),replArchFilesSamba) + replArchFilesSamba = ["/".join(y for y in x.split("/") if y) + for x in replArchFilesSamba] replArchFilesSamba = self.unicList(replArchFilesSamba) replArchFilesSamba.sort() if "mail" in replServices: @@ -8335,9 +8336,8 @@ service %s")%service additFiles = list(set(additFilesMailUnix)|set(additFiles)) for additFile in additFilesMailUnix: replArchFilesMailUnix.append(additFile) - replArchFilesMailUnix = map(lambda x:\ - "/".join(filter(lambda y:y ,x.split("/"))),\ - replArchFilesMailUnix) + replArchFilesMailUnix = ["/".join(y for y in x.split("/") if y) + for x in replArchFilesMailUnix] replArchFilesMailUnix = self.unicList(replArchFilesMailUnix) replArchFilesMailUnix.sort() if "samba" in replServices: @@ -8346,14 +8346,13 @@ service %s")%service additFiles = list(set(additFilesMailSamba)|set(additFiles)) for additFile in additFilesMailSamba: replArchFilesMailSamba.append(additFile) - replArchFilesMailSamba = map(lambda x:\ - "/".join(filter(lambda y:y ,x.split("/"))),\ - replArchFilesMailSamba) + replArchFilesMailSamba = ["/".join(y for y in x.split("/") if y) + for x in replArchFilesMailSamba] replArchFilesMailSamba=self.unicList(replArchFilesMailSamba) replArchFilesMailSamba.sort() # Удаляем начальный "/" - replArchFilesMail = map(lambda x:\ - "/".join(filter(lambda y:y ,x.split("/"))),replArchFilesMail) + replArchFilesMail = ["/".join(y for y in x.split("/") if y) + for x in replArchFilesMail] replArchFilesMail = self.unicList(replArchFilesMail) replArchFilesMail.sort() for additFile in additFiles: @@ -8424,15 +8423,14 @@ service %s")%service return False # Удаляем dovecot, procmailrc из списка файлов # а также ненужные алиасы - replArchFilesMail = map(lambda x:"/".join(x),\ - filter(lambda x:\ - not 'dovecot' in x and\ - not 'procmailrc' == x[-1] and\ - not 'ldap-aliases-gr.cf' == x[-1] and\ - not 'ldap-aliases.cf' == x[-1] and\ - not 'ldap-recipient-gr.cf' == x[-1] and\ - not 'ldap-recipient.cf' == x[-1],\ - map(lambda x:x.split("/"),replArchFilesMail))) + replArchFilesMail = ["/".join(x) + for x in (y.split("/") for y in replArchFilesMail) + if not 'dovecot' in x and + not 'procmailrc' == x[-1] and + not 'ldap-aliases-gr.cf' == x[-1] and + not 'ldap-aliases.cf' == x[-1] and + not 'ldap-recipient-gr.cf' == x[-1] and + not 'ldap-recipient.cf' == x[-1]] if not self.savePrivateFile (self.replListFileMail, "\n".join(replArchFilesMail)): self.printERROR(_("Can not create list archive files")+\ @@ -8483,7 +8481,7 @@ service %s")%service # если существуют удаляем файлы в /tmp self.removeTmpFiles() if os.path.exists(bFile): - os.chmod(bFile,0600) + os.chmod(bFile,0o600) self.printSUCCESS(_("Created archive file") + ": " +\ str(bFile)) return True @@ -8493,7 +8491,7 @@ service %s")%service return False def backupLdapServer(self, options): - if not options or (options and options.has_key("b")): + if not options or (options and "b" in options): # Создаем объект переменных clVars self.createClVars(self.clVars) # находим установленные сервисы @@ -8508,7 +8506,7 @@ service %s")%service return self.backupServer() else: return self.backupNotLdap() - if options.has_key("r"): + if "r" in options: return self.restoreServer() def startAllSetupServices(self): @@ -8522,7 +8520,7 @@ service %s")%service # заменяем mail на mail_relay if set(["mail","ldap"]) == set(servInstalled) and\ self.clVars.Get("sr_mail_relay_set") == "on": - servInstalled = filter(lambda x: x!="mail",servInstalled) +\ + servInstalled = [x for x in servInstalled if x != "mail"] +\ ["mail_relay"] return self.startServices(servInstalled) @@ -8565,7 +8563,7 @@ service %s")%service self.printERROR(_('Can not execute "%s"')%strCmd) return False # удаляем из элементов переводы строк - archFiles = map(lambda x: "".join(x.split('\n')),textListFiles) + archFiles = ("".join(x.split('\n')) for x in textListFiles) if self.archLdifFile[1:] in archFiles: return True return False @@ -8582,7 +8580,7 @@ service %s")%service self.printERROR(_('Can not execute "%s"')%strCmd) return False # удаляем из элементов переводы строк - archFiles = map(lambda x: "".join(x.split('\n')),textListFiles) + archFiles = ["".join(x.split('\n')) for x in textListFiles] flagError = False # Находим в списке файлов файлы списки для сервисов listReplFiles = list(set([self.replListFileSamba[1:], @@ -8747,8 +8745,8 @@ for running replication")%bFile) allArchFiles = [self.replArchLdifFileMail, self.replListFileMail] # Удаляем начальный '/' - allArchFiles = map(lambda x:\ - "/".join(filter(lambda y:y ,x.split("/"))),allArchFiles) + allArchFiles = ["/".join(y for y in x.split("/") if y) + for x in allArchFiles] # Удаляем временные файлы self.removeTmpFiles() # Сохраняем файл - список извлекаемых файлов (файл ldif) @@ -8785,7 +8783,7 @@ for running replication")%bFile) # Добавляем в базу из ldif self.ldapObj.ldapAdd(ldif) if self.ldapObj.getError(): - print _("LDAP Error") + ": " + self.ldapObj.getError().strip() + print(_("LDAP Error") + ": " + self.ldapObj.getError().strip()) return False # Останавливаем LDAP сервер if not self.stopLdapServer(): @@ -8941,7 +8939,7 @@ for running replication")%bFile) while ldapObj.getError(): try: # Задержка - wait.next() + next(wait) except StopIteration: break # Очистка ошибки @@ -8966,7 +8964,7 @@ for running replication")%bFile) # Принудительная установка forceOptions = False self.createClVars() - if options.has_key("f"): + if "f" in options: forceOptions = True if self.clVars.Get("sr_ldap_set") == "on" and\ not forceOptions: @@ -9052,7 +9050,7 @@ for running replication")%bFile) if not self.ldapObj.getError(): self.ldapObj.ldapAdd(baseLdif) if self.ldapObj.getError(): - print _("LDAP Error") + ": " + self.ldapObj.getError().strip() + print(_("LDAP Error") + ": " + self.ldapObj.getError().strip()) return False self.printOK(_("Added ldif file") + " ...") # Второй проход, @@ -11464,7 +11462,7 @@ service") catDir = os.path.join(pkgDir,category) package = "%s-"%package if not (os.path.exists(catDir) and - filter(lambda x:x.startswith(package),os.listdir(catDir))): + [x for x in os.listdir(catDir) if x.startswith(package)]): self.printERROR(_("Package '%s' is not installed")%pkg) return False return True @@ -11488,7 +11486,7 @@ service") # если установки параметрв не произошло if not datavars.flFromCmdParam(options['s']): # вывод - print _("Bad enviroment parameters") + print(_("Bad enviroment parameters")) return False # если опция отображения параметров if 'e' in options: @@ -11538,9 +11536,9 @@ service") """Записывает в аттрибут self.allServ названия всех сервисов""" sServ = re.compile("\s*([^\s]+)\s*") for par in self.data: - if par.has_key('helpChapter') and\ + if 'helpChapter' in par and\ par['helpChapter'] == _("Services") and\ - par.has_key('help') and self.access(par): + 'help' in par and self.access(par): res = sServ.search(par['help']) if res: self.allServ.append(res.group(1)) @@ -11572,7 +11570,7 @@ class servFtp(shareLdap): """Начальная настройка FTP сервиса""" # Принудительная установка forceOptions = False - if options.has_key("f"): + if "f" in options: forceOptions = True # Создаем объект переменных и начальная проверка if not self.initialChecksSetup(): @@ -11668,7 +11666,7 @@ class servFtp(shareLdap): if not self.ldapObj.getError(): self.ldapObj.ldapAdd(baseLdif) if self.ldapObj.getError(): - print _("LDAP Error") + ": " + self.ldapObj.getError().strip() + print(_("LDAP Error") + ": " + self.ldapObj.getError().strip()) return False # Записываем данные администратора сервиса FTP ldapParser = iniLdapParser() @@ -11708,12 +11706,12 @@ class servFtp(shareLdap): ftpTmpPath = os.path.join(ftpPath,"tmp") if not os.path.exists(ftpTmpPath): os.makedirs(ftpTmpPath) - os.chmod(ftpTmpPath,0777) + os.chmod(ftpTmpPath,0o777) #cоздаем директорию pub ftpPubPath = os.path.join(ftpPath,"pub") if not os.path.exists(ftpPubPath): os.makedirs(ftpPubPath) - os.chmod(ftpPubPath,0755) + os.chmod(ftpPubPath,0o755) #запишем переменные для клиента clientVars = ["cl_remote_ftp"] if not self.saveVarsClient(clientVars): @@ -11754,7 +11752,7 @@ class servFtp(shareLdap): # Изменяемые аттрибуты пользователя modAttrs = [] # Изменяем комментарий к пользователю - if options.has_key('c'): + if 'c' in options: comment = options['c'] modAttrs += [(ldap.MOD_REPLACE, 'sn', comment), (ldap.MOD_REPLACE, 'cn', comment)] @@ -11766,7 +11764,7 @@ class servFtp(shareLdap): userPwdHash = self.getHashPasswd(userPwd, self.userCrypt) if not userPwdHash: return False - if resSearch[0][0][1].has_key('userPassword'): + if 'userPassword' in resSearch[0][0][1]: modAttrs.append((ldap.MOD_REPLACE, 'userPassword', userPwdHash)) else: @@ -11777,9 +11775,9 @@ class servFtp(shareLdap): DN = self.addDN("uid="+uid, self.relUsersDN) if not self.modAttrsDN(DN, modAttrs): return False - if options.has_key('c'): + if 'c' in options: self.printSUCCESS(_("Modified comment (full name)")) - if options.has_key('P') or options.has_key('p'): + if 'P' in options or 'p' in options: self.printSUCCESS(_("Modified FTP user password")) return True @@ -11803,7 +11801,7 @@ class servFtp(shareLdap): userPwdHash = self.getHashPasswd(userPwd, self.userCrypt) if not userPwdHash: return False - if resSearch[0][0][1].has_key('userPassword'): + if 'userPassword' in resSearch[0][0][1]: modAttrs.append((ldap.MOD_REPLACE, 'userPassword', userPwdHash)) else: @@ -11873,7 +11871,7 @@ class servFtp(shareLdap): # Флаг создания группы по умолчанию flagCreateUnixGroup = False # Группа пользователя - if options.has_key('g'): + if 'g' in options: optUnix['g'] = options['g'] else: optUnix['g'] = self.defaultUnixGroup["name"] @@ -11889,7 +11887,7 @@ class servFtp(shareLdap): if not self.servUnixObj.searchUnixGroupName(optUnix['g']): flagCreateUnixGroup = True # Полное имя пользователя - if options.has_key('c'): + if 'c' in options: optUnix['c'] = options['c'] # Если нужно создаем новую Unix группу if flagCreateUnixGroup: @@ -11910,10 +11908,10 @@ class servFtp(shareLdap): self.clVars.Set("ur_name", userName) #Полное имя пользователя fullNameUser = self.servUnixObj.fullNameUser - if options.has_key('c'): + if 'c' in options: fullNameUser = options['c'] else: - if resUnix and resUnix[0][0][1].has_key('cn'): + if resUnix and 'cn' in resUnix[0][0][1]: fullNameUser = resUnix[0][0][1]['cn'][0] self.clVars.Set("ur_fio",fullNameUser) if not userPwd: @@ -11940,7 +11938,7 @@ class servFtp(shareLdap): # Корневая FTP директория ftpDir = self.clVars.Get("sr_ftp_path") # FTP директория пользователя - if options.has_key('d') and options.has_key('m'): + if 'd' in options and 'm' in options: ftpUserDir = options['d'] if ftpUserDir[0] == "/": ftpUserDir = ftpUserDir[1:] @@ -11955,14 +11953,14 @@ class servFtp(shareLdap): self.ldapObj.ldapAdd(userLdif) # не переделывать на else if self.ldapObj.getError(): - print _("LDAP Error") + ": " + self.ldapObj.getError().strip() + print(_("LDAP Error") + ": " + self.ldapObj.getError().strip()) return False flagError = False # FTP директория пользователя - if not options.has_key('d'): + if 'd' not in options: ftpUserDir = os.path.join(ftpDir,"pub/users",userName) # Создаем FTP директорию пользователя - if options.has_key('m'): + if 'm' in options: if not self.createUserDir(uid, gid, ftpUserDir): flagError = True if flagError: @@ -12055,7 +12053,7 @@ class servRepl(shareLdap): clVars.flServer() calculate_ini = self.clVars.Get("cl_env_path") remoteIni = "" - if calculate_ini and type(calculate_ini) == types.ListType: + if calculate_ini and type(calculate_ini) == list: remoteIni = calculate_ini[0] if remoteIni: # проверить сущестование ini файла @@ -12171,8 +12169,8 @@ class servRepl(shareLdap): self.restoreLocalVar) # Получаем от пользователя доверительные сети для сервиса Samba # Переназначаем объект переменных - print _("Replications servers for Samba: %s")\ - % " ".join(replSambaServers) + print(_("Replications servers for Samba: %s")\ + % " ".join(replSambaServers)) self.servSambaObj.clVars = self.clVars if not self.servSambaObj.getAllowNet(): return False @@ -12199,8 +12197,8 @@ class servRepl(shareLdap): self.restoreRemoteClientVar = [] # Получаем от пользователя доверительные сети для сервиса Mail # Переназначаем объект переменных - print _("Replications servers for Mail: %s")\ - % " ".join(replMailServers) + print(_("Replications servers for Mail: %s")\ + % " ".join(replMailServers)) self.servMailObj.clVars = self.clVars if not self.servMailObj.getAllowNet(): return False @@ -12230,8 +12228,8 @@ class servRepl(shareLdap): self.restoreRemoteClientVar = [] # Получаем от пользователя доверительные сети для сервиса Mail # Переназначаем объект переменных - print _("Replications servers for Mail: %s")\ - % " ".join(replMailServers) + print(_("Replications servers for Mail: %s")\ + % " ".join(replMailServers)) self.servMailObj.clVars = self.clVars if not self.servMailObj.getAllowNet(): return False @@ -12247,15 +12245,15 @@ class servRepl(shareLdap): self.restoreLocalVar) # Получаем от пользователя доверительные сети для сервиса Samba # Переназначаем объект переменных - print _("Replications servers for Samba: %s")\ - % " ".join(replSambaServers) + print(_("Replications servers for Samba: %s")\ + % " ".join(replSambaServers)) self.servSambaObj.clVars = self.clVars if not self.servSambaObj.getAllowNet(): return False # Получаем от пользователя доверительные сети для сервиса Mail # Переназначаем объект переменных - print _("Replications servers for Mail: %s")\ - % " ".join(replMailServers) + print(_("Replications servers for Mail: %s")\ + % " ".join(replMailServers)) self.servMailObj.clVars = self.clVars if not self.servMailObj.getAllowNet(): return False @@ -12303,12 +12301,12 @@ class servRepl(shareLdap): # права и владелец /var/calculate/remote if os.path.exists(remotePath): os.chown(remotePath,0,int(cl.gid)) - os.chmod(remotePath,02755) + os.chmod(remotePath,0o2755) # изменяем владельца remote на client if not os.path.exists(remoteEnvFile): fd = os.open(remoteEnvFile, os.O_CREAT) os.close(fd) - os.chmod(remoteEnvFile, 0640) + os.chmod(remoteEnvFile, 0o640) if os.path.exists(remoteEnvFile): os.chown(remoteEnvFile,0,int(cl.gid)) return True @@ -12337,11 +12335,11 @@ class servRepl(shareLdap): os.path.exists(os.path.join(x, self.logOutFile)) or \ os.path.exists(os.path.join(x, self.srvFile)) or\ os.path.exists(os.path.join(x, self.deskFile)) - return filter(filterFunc, - [profileDir] + map(lambda x: os.path.join(profileDir, x),\ - filter(lambda x:\ - os.path.isdir(os.path.join(profileDir, x)) ,\ - os.listdir(profileDir)))) + return [x for x + in [profileDir] + [os.path.join(profileDir, y) + for y in os.listdir(profileDir) + if os.path.isdir(os.path.join(profileDir, y))] + if filterFunc(x)] @adminConnectLdap def deleteLogoutFile(self, userName, logoutFile): @@ -12380,7 +12378,7 @@ class servRepl(shareLdap): uid = int(resPasswd.split(":")[2]) gid = int(resPasswd.split(":")[3]) if uid == None or gid == None: - print _("User %s not found in Unix service") + print(_("User %s not found in Unix service")) return False winProfDir =\ os.path.join(self.clVars.Get("sr_samba_winprof_path"), @@ -12495,7 +12493,7 @@ if %%errorlevel%%==0 NET USE T: \\\\%s\\ftp' %(netbios,netbios,netbios) if not self.ldapObj.getError(): self.ldapObj.ldapAdd(baseLdif) if self.ldapObj.getError(): - print _("LDAP Error") + ": " + self.ldapObj.getError().strip() + print(_("LDAP Error") + ": " + self.ldapObj.getError().strip()) return False return True @@ -12525,7 +12523,7 @@ if %%errorlevel%%==0 NET USE T: \\\\%s\\ftp' %(netbios,netbios,netbios) if not self.ldapObj.getError(): self.ldapObj.ldapAdd(baseLdif) if self.ldapObj.getError(): - print _("LDAP Error") + ": " + self.ldapObj.getError().strip() + print(_("LDAP Error") + ": " + self.ldapObj.getError().strip()) return False # Если ветка Replication/Mail не существует - добавляем ее if not self.isReplMailDNExists(): @@ -12535,7 +12533,7 @@ if %%errorlevel%%==0 NET USE T: \\\\%s\\ftp' %(netbios,netbios,netbios) try: self.conLdap.add_s(self.clVars.Get("ld_repl_mail_dn"), entry) - except ldap.LDAPError, e: + except ldap.LDAPError as e: self.printERROR(_("LDAP Error") + ": " + e[0]['desc'].strip()) self.printERROR(errorMessage) return False @@ -12550,7 +12548,7 @@ if %%errorlevel%%==0 NET USE T: \\\\%s\\ftp' %(netbios,netbios,netbios) try: self.conLdap.add_s(self.clVars.Get("ld_repl_worked_dn"), entry) - except ldap.LDAPError, e: + except ldap.LDAPError as e: self.printERROR(_("LDAP Error") + ": " + e[0]['desc'].strip()) self.printERROR(errorMessage) return False @@ -12613,7 +12611,7 @@ if %%errorlevel%%==0 NET USE T: \\\\%s\\ftp' %(netbios,netbios,netbios) if fullDel: foundUsers = self.searchWorkedUser(userName+"@*") if foundUsers: - deleteUserNames = map(lambda x: x[0][1]["uid"][0], foundUsers) + deleteUserNames = (x[0][1]["uid"][0] for x in foundUsers) for delUser in deleteUserNames: delDN = self.addDN("uid=" + delUser, relWorkedDN) if not self.delDN(delDN): @@ -12683,7 +12681,7 @@ if %%errorlevel%%==0 NET USE T: \\\\%s\\ftp' %(netbios,netbios,netbios) rez = self.searchMailAlias(aliasName) if not rez: return True - if rez[0][0][1].has_key('filtersender'): + if 'filtersender' in rez[0][0][1]: attrDelete = [] relMailDN = self.getRelMailDN() aliasDN = self.addDN("cn=%s"%aliasName, relMailDN) @@ -12709,26 +12707,23 @@ if %%errorlevel%%==0 NET USE T: \\\\%s\\ftp' %(netbios,netbios,netbios) self.clVars.Set('sr_mail_host',fullHostName,True) mailHost = fullHostName # Получаем почтовые алиасы (почтовые адреса на других серверах) - userMails = filter(lambda x:\ - len(x.split("@"))==2 and x.split('@')[1] != mailHost,\ - filter(lambda x: "@" in x, srcMails)) + userMails = [x for x in (y for y in srcMails if "@" in y) + if len(x.split("@")) == 2 and x.split('@')[1] != mailHost] if userMails: # Внешний почтовый адрес пользователя (первый в списке) userMail = userMails[0] # Убирает первый адрес из списка - userMails = list(set(filter(lambda x: x != userMail, - userMails))) + userMails = list(set(x for x in userMails if x != userMail)) attrAppend = [] attrDelete = [] attrReplace = [] if filterHosts: domain = self.clVars.Get('os_net_domain') # Если необходимо добавляем домен к именам хостов - fHosts = map(lambda x: (not '.' in x and x+"."+domain) or x, - filterHosts) + fHosts = [(not '.' in x and x + "." + domain) or x for x in filterHosts] for host in fHosts: attrAppend.append((ldap.MOD_ADD, 'filtersender', host)) - if rez[0][0][1].has_key('filtersender'): + if 'filtersender' in rez[0][0][1]: attrDelete.append((ldap.MOD_DELETE, 'filtersender', None)) email = rez[0][0][1]["mail"][0] altEmails = rez[0][0][1]["mailAlternateAddress"] @@ -12776,21 +12771,19 @@ if %%errorlevel%%==0 NET USE T: \\\\%s\\ftp' %(netbios,netbios,netbios) self.clVars.Set('sr_mail_host',fullHostName,True) mailHost = fullHostName # Получаем почтовые алиасы (почтовые адреса на других серверах) - userMails = filter(lambda x:\ - len(x.split("@"))==2 and x.split('@')[1] != mailHost,\ - filter(lambda x: "@" in x, srcMails)) + userMails = [x for x in (y for y in srcMails if "@" in y) + if len(x.split("@")) == 2 and x.split('@')[1] != mailHost] if userMails: # Внешний почтовый адрес пользователя (первый в списке) userMail = userMails[0] # Убираем первый адрес из списка - userMails = list(set(filter(lambda x: x != userMail, - userMails))) + userMails = list(set(x for x in userMail if x != userMail)) self.clVars.Set("ur_mail", userMail) baseLdif = self.createLdif(ldifFile) if not self.ldapObj.getError(): self.ldapObj.ldapAdd(baseLdif) if self.ldapObj.getError(): - print _("LDAP Error") + ": "+self.ldapObj.getError().strip() + print(_("LDAP Error") + ": "+self.ldapObj.getError().strip()) return False modAttrs = [] relMailDN = self.getRelMailDN() @@ -12801,8 +12794,7 @@ if %%errorlevel%%==0 NET USE T: \\\\%s\\ftp' %(netbios,netbios,netbios) if filterHosts: domain = self.clVars.Get('os_net_domain') # Если необходимо добавляем домен к именам хостов - fHosts = map(lambda x: (not '.' in x and x+"."+domain) or x, - filterHosts) + fHosts = [(not '.' in x and x + "." + domain) or x for x in filterHosts] for host in fHosts: modAttrs.append((ldap.MOD_ADD, 'filtersender', host)) @@ -12825,12 +12817,12 @@ if %%errorlevel%%==0 NET USE T: \\\\%s\\ftp' %(netbios,netbios,netbios) if not self.ldapObj.getError(): self.ldapObj.ldapAdd(baseLdif) if self.ldapObj.getError(): - print _("LDAP Error") + ": " + self.ldapObj.getError().strip() + print(_("LDAP Error") + ": " + self.ldapObj.getError().strip()) return False rez = self.searchWorkedUser(userName) replHost = self.clVars.Get("ld_repl_host") if not replHost: - print _("Variable Error: not set a variable ld_repl_host") + print(_("Variable Error: not set a variable ld_repl_host")) return False if rez: host = rez[0][0][1]['host'][0] @@ -12842,7 +12834,7 @@ if %%errorlevel%%==0 NET USE T: \\\\%s\\ftp' %(netbios,netbios,netbios) if not self.modAttrsDN(DN, modAttrs): return False else: - print _("Can not add user %s in branch 'Replication'")%userName + print(_("Can not add user %s in branch 'Replication'")%userName) return False return True @@ -12916,7 +12908,7 @@ if %%errorlevel%%==0 NET USE T: \\\\%s\\ftp' %(netbios,netbios,netbios) uid = int(resPasswd.split(":")[2]) gid = int(resPasswd.split(":")[3]) if uid == None or gid == None: - print _("User %s not found in Unix service") + print(_("User %s not found in Unix service")) return False linProfDir =\ os.path.join(self.clVars.Get("sr_samba_linprof_path"), @@ -13156,7 +13148,7 @@ remove user %s in the LDAP branch 'Worked'")%str(userName)) if supportSections: sections = list(set(sections)-set(["command"])) sections = set(sections)-set(supportSections) - delSections = map(lambda x: x.split(","), sections) + delSections = (x.split(",") for x in sections) for delSect in delSections: txtConfig.delArea(delSect) # Если включена репликация и нет команды на упаковку @@ -13212,16 +13204,16 @@ remove user %s in the LDAP branch 'Worked'")%str(userName)) errMessages = [] # Опция выключает вывод cообщений на экран verboseMode = True - if options.has_key('s'): + if 's' in options: verboseMode = False login = "" logout = "" makeDir = "" - isLogin = options.has_key('login') - isLogout = options.has_key('logout') - isMakeDir = options.has_key('makedir') + isLogin = 'login' in options + isLogout = 'logout' in options + isMakeDir = 'makedir' in options dictOpt = {"login":isLogin, "logout":isLogout, "makedir":isMakeDir} - firstOpt = filter(lambda x: x[1] ,dictOpt.items()) + firstOpt = [x for x in dictOpt.items() if x[1]] lenOpt = len(firstOpt) if lenOpt == 1: if isLogin: @@ -13332,14 +13324,14 @@ incompatible")) errMessages = [] # Опция выключает вывод cообщений на экран verboseMode = True - if options.has_key('s'): + if 's' in options: verboseMode = False logout = "" makeDir = "" - isLogout = options.has_key('logout') - isMakeDir = options.has_key('makedir') + isLogout = 'logout' in options + isMakeDir = 'makedir' in options dictOpt = {"logout":isLogout, "makedir":isMakeDir} - firstOpt = filter(lambda x: x[1] ,dictOpt.items()) + firstOpt = [x for x in dictOpt.items() if x[1]] lenOpt = len(firstOpt) if lenOpt == 1: if isLogout: @@ -13519,7 +13511,7 @@ remove user %s in the LDAP branch 'Worked'")%str(userName)) if supportSections: sections = list(set(sections)-set(["command"])) sections = set(sections)-set(supportSections) - delSections = map(lambda x: x.split(","), sections) + delSections = (x.split(",") for x in sections) for delSect in delSections: txtConfig.delArea(delSect) # Если включена репликация и нет команды на упаковку @@ -13589,7 +13581,7 @@ remove user %s in the LDAP branch 'Worked'")%str(userName)) _("Samba user %s is not found")%str(userName)) return False # Проверка правильности предыдущего пароля - if resSamba[0][0][1].has_key('sambaNTPassword'): + if 'sambaNTPassword' in resSamba[0][0][1]: if userOldNTHash !=resSamba[0][0][1]['sambaNTPassword'][0]: self.printERROR( _("Invalid previous password for the user %s")\ @@ -13603,7 +13595,7 @@ remove user %s in the LDAP branch 'Worked'")%str(userName)) # Изменение пароля пользователя Unix # Изменяемые аттрибуты пользователя modAttrs = [] - if resUnix[0][0][1].has_key('userPassword'): + if 'userPassword' in resUnix[0][0][1]: modAttrs.append((ldap.MOD_REPLACE, 'userPassword', userPwdHash)) else: @@ -13626,7 +13618,7 @@ remove user %s in the LDAP branch 'Worked'")%str(userName)) ("sambaNTPassword",userNTHash)] resSambaAttr = resSamba[0][0][1] for attr, value in data: - if resSambaAttr.has_key(attr): + if attr in resSambaAttr: modAttrs.append((ldap.MOD_REPLACE, attr, value)) else: if attr!="sambaLMPassword": @@ -13701,7 +13693,7 @@ remove user %s in the LDAP branch 'Worked'")%str(userName)) if os.path.isdir(path): os.chdir(path) users = os.listdir(".") - users = filter(lambda x: os.path.isdir(x), users) + users = [x for x in users if os.path.isdir(x)] for dirName in users: # имя пользователя (исключая суффикс V2) userName = \ @@ -13790,7 +13782,7 @@ calculate-server") return False return True if not self.createUserFile(cronWeeklyFile, replCronFileContent, - 0, 0, 0744): + 0, 0, 0o744): return False return True @@ -13821,9 +13813,9 @@ calculate-server") self.printERROR(_('Can not execute "%s"')%strCmd) return False # Удаляем из элементов переводы строк - listCronLinesSrc = map(lambda x: x.split('\n')[0],listCronLines) + listCronLinesSrc = [x.split('\n')[0] for x in listCronLines] # Удаляем из элементов все начиная с # - listCronLines = map(lambda x: x.split("#")[0].strip(), listCronLinesSrc) + listCronLines = [x.split("#")[0].strip() for x in listCronLinesSrc] listCronLinesOut = [] i = 0 for textCron in listCronLines: @@ -13905,7 +13897,7 @@ use the new version. (openldap > 2.4)")%openLdapVesion) return False listGroupMail = [] for i in resSearch: - if i[0][1].has_key('filtersender'): + if 'filtersender' in i[0][1]: listGroupMail.append((i[0][1]["cn"][0], i[0][1]["mailAlternateAddress"], i[0][1]["filtersender"])) @@ -13921,7 +13913,7 @@ use the new version. (openldap > 2.4)")%openLdapVesion) # Определяем поддерживает ли openldap репликацию if not self.supportReplOpenldap(self.clVars): return False - if options.has_key('off'): + if 'off' in options: if self.clVars.Get("ld_repl_set") == "off": self.printWARNING(_("Replication off for all services")) return True @@ -13993,19 +13985,19 @@ file %s")%bFile) self.clVars.Write("ld_repl_set", "off") # Включаем репликацию self.clVars.Set("ld_repl_set", "on") - if not options.has_key('off') and\ - (not options.has_key('r') or not options['r']): + if 'off' not in options and\ + ('r' not in options or not options['r']): self.printERROR(\ _("Not specified replication servers \ (command line option '-r')")) return False - if options.has_key('off') and options.has_key('r'): + if 'off' in options and 'r' in options: self.printERROR(\ _("You can not use the option to '--off', \ together with option '-r'")) return False replServers = [] - if options.has_key('r'): + if 'r' in options: replServers = options['r'].split(',') # Преобразуем короткие имена в длинные hostName = self.clVars.Get('os_net_hostname') @@ -14032,29 +14024,28 @@ together with option '-r'")) self.printERROR(\ _("Set Replication error, Unix service not setuped")) return False - if options.has_key('r'): + if 'r' in options: replSambaServers = self.clVars.Get("ld_repl_samba_servers") replMailServers = self.clVars.Get("ld_repl_mail_servers") dictServers = {"samba":replSambaServers, "mail":replMailServers, "unix":",".join(replServers)} - listServersRepl = map(lambda x: (x[0],set(x[1].split(","))), - filter(lambda x: x[1], - dictServers.items())) + listServersRepl = [(x[0],set(x[1].split(","))) for x + in dictServers.items() if x[1]] # Все серверы репликации - replAllServers = list(reduce(lambda x,y: ('',x[1]|y[1]), - listServersRepl,("",set()))[1]) + replAllServers = list(reduce(lambda x, y: ('', x[1] | y[1]), + listServersRepl, ("", set()))[1]) # Серверы репликации для ветки Unix - replUnixServers = list(reduce(lambda x,y: ('',x[1]|y[1]), - filter(lambda x: x[0] in ['samba','unix'], - listServersRepl),("",set()))[1]) + replUnixServers = list(reduce(lambda x, y: ('', x[1] | y[1]), + [z for z in listServersRepl if z[0] in ['samba','unix']], + ("", set()))[1]) # Устанавливаем переменную серверы репл. для Unix сервиса self.clVars.Set("ld_repl_unix_servers", ",".join(replUnixServers),True) # Устанавливаем переменную серверы репл. для всех сервисов self.clVars.Set("ld_repl_servers", ",".join(replAllServers),True) - elif options.has_key('off'): + elif 'off' in options: # Выключаем репликацию для сервисов Samba и Mail if self.clVars.Get("ld_repl_mail_set") == "on" and\ self.clVars.Get("ld_repl_mail_servers"): @@ -14079,7 +14070,7 @@ together with option '-r'")) replUnixServers = self.clVars.Get("ld_repl_unix_servers") if replUnixServers: replUnixServers = replUnixServers.split(",") - if options.has_key('off'): + if 'off' in options: # Очищаем cерверы репликации Samba self.clVars.Set("ld_repl_samba_servers", "", True) self.clVars.Delete("ld_repl_samba_servers","local","server") @@ -14093,19 +14084,18 @@ together with option '-r'")) dictServers = {"samba":",".join(replServers), "mail":replMailServers, "unix":",".join(diffReplServers)} - listServersRepl = map(lambda x: (x[0],set(x[1].split(","))), - filter(lambda x: x[1], dictServers.items())) + listServersRepl = [(x[0], set(x[1].split(","))) for x in dictServers.items() if x[1]] # Все серверы репликации replAllServers = list(reduce(lambda x,y: ('',x[1]|y[1]), listServersRepl,("",set()))[1]) # Серверы репликации для ветки Unix - replUnixServers = list(reduce(lambda x,y: ('',x[1]|y[1]), - filter(lambda x: x[0] in ['samba','unix'], - listServersRepl),("",set()))[1]) + replUnixServers = list(reduce(lambda x, y: ('', x[1] | y[1]), + [z for z in listServersRepl if z[0] in ['samba','unix']], + ("", set()))[1]) # Серверы репликации для ветки Samba - replSambaServers = list(reduce(lambda x,y: ('',x[1]|y[1]), - filter(lambda x: x[0] in ['samba'], - listServersRepl),("",set()))[1]) + replSambaServers = list(reduce(lambda x, y: ('', x[1] | y[1]), + [z for z in listServersRepl if z[0] in ['samba']], + ("", set()))[1]) # Устанавливаем переменную серверы репл. для Samba сервиса self.clVars.Set("ld_repl_samba_servers", ",".join(replSambaServers),True) @@ -14124,7 +14114,7 @@ together with option '-r'")) _("Set Replication error, Mail service not setuped")) return False replUnixServers = self.clVars.Get("ld_repl_unix_servers") - if options.has_key('off'): + if 'off' in options: # Очищаем cерверы репликации Mail self.clVars.Set("ld_repl_mail_servers", "", True) self.clVars.Delete("ld_repl_mail_servers","local","server") @@ -14133,15 +14123,15 @@ together with option '-r'")) dictServers = {"samba":replSambaServers, "mail":",".join(replServers), "unix":replUnixServers} - listServersRepl = map(lambda x: (x[0],set(x[1].split(","))), - filter(lambda x: x[1], dictServers.items())) + listServersRepl = [(x[0], set(x[1].split(","))) + for x in dictServers.items() if x[1]] # Все серверы репликации - replAllServers = list(reduce(lambda x,y: ('',x[1]|y[1]), - listServersRepl,("",set()))[1]) + replAllServers = list(reduce(lambda x,y: ('', x[1] | y[1]), + listServersRepl, ("", set()))[1]) # Серверы репликации для ветки Mail - replMailServers = list(reduce(lambda x,y: ('',x[1]|y[1]), - filter(lambda x: x[0] in ['mail'], - listServersRepl),("",set()))[1]) + replMailServers = list(reduce(lambda x,y: ('', x[1] | y[1]), + [z for z in listServersRepl if z[0] in ['mail']], + ("", set()))[1]) # Устанавливаем переменную серверы репл. для Mail сервиса self.clVars.Set("ld_repl_mail_servers", ",".join(replMailServers),True) @@ -14163,7 +14153,7 @@ together with option '-r'")) #Cоединение с Ldap (администратор) if not shareLdap.getLdapObjInFile(self): return False - if options.has_key('r'): + if 'r' in options: # Проверяем существует ли id текущего сервера if not self.clVars.Get("ld_repl_id"): self.printERROR(_("Not found 'serverID' this server")) @@ -14172,7 +14162,7 @@ together with option '-r'")) # Делаем update cервиса Samba в случае опции off и не показываем # реплицируемые серверы if service == "unix" and self.clVars.Get("sr_samba_set") == "on" and\ - options.has_key('off'): + 'off' in options: if not self.servLdapObj.updateServer({},"samba",self.clVars, [],False): return False @@ -14210,9 +14200,8 @@ together with option '-r'")) # Получаем почтовые группы groupsMail = self.getGroupsMail() # объединяет usersMail и groupsMail - usersAndGroupsMail = map(lambda x: (len(x)==2 and\ - (x[0],x[1],[])) or x, reduce(lambda x, y: x+y,\ - map(lambda x: x or [], [usersMail,groupsMail]),[])) + usersAndGroupsMail = [(len(x) == 2 and (x[0], x[1], [])) or x + for x in reduce(lambda x, y: x + y, [z or [] for z in [usersMail,groupsMail]],[])] if usersAndGroupsMail: flagError = False for name, mails, hosts in usersAndGroupsMail: @@ -14258,15 +14247,15 @@ class cl_info(cl_utils2.cl_smartcon, prnServ): strService = self.printNameService(service) # Информация сервиса DHCP # Информация о всех сетях DHCP - if service == "dhcp" and options.has_key("n"): + if service == "dhcp" and "n" in options: dhcpObj = dncpTxt() dataNets = dhcpObj.getDataInAllSubnet() dataList = [] for net, data in dataNets: dataTmp = [] - if data.has_key('net'): + if 'net' in data: dataTmp.append(data['net'][0]) - if data.has_key('mask'): + if 'mask' in data: dataTmp.append(data['mask'][0]) if len(dataTmp) == 2: dataList.append(["%s/%s"%(dataTmp[0],\ @@ -14279,7 +14268,7 @@ class cl_info(cl_utils2.cl_smartcon, prnServ): repObj.printReport() return True # Информация о сети DHCP - if service == "dhcp" and options.has_key("N"): + if service == "dhcp" and "N" in options: # ip сети и сетевая маска /24 net = options["N"] # cоздаем объект DHCP @@ -14339,7 +14328,7 @@ class cl_info(cl_utils2.cl_smartcon, prnServ): return True # Информация о статическом носте DHCP - if service == "dhcp" and options.has_key("H"): + if service == "dhcp" and "H" in options: hostname = options["H"] # Проверка правильности названия хоста if '.' in hostname: @@ -14379,13 +14368,13 @@ class cl_info(cl_utils2.cl_smartcon, prnServ): return True # Информация о всех статических хостах DHCP - if service == "dhcp" and options.has_key("hosts"): + if service == "dhcp" and "hosts" in options: dhcpObj = dncpTxt() dataHosts = dhcpObj.getDataInAllHost() dataList = [] for hostname, data in dataHosts: ip = "" - if data.has_key("fixed-address"): + if "fixed-address" in data: if data["fixed-address"]: ip = data["fixed-address"][0] dataList.append([hostname,ip]) @@ -14398,8 +14387,8 @@ class cl_info(cl_utils2.cl_smartcon, prnServ): return True # Информация о DNS - if service == "dns" and options.has_key("z") or options.has_key("Z") or\ - options.has_key("r"): + if service == "dns" and "z" in options or "Z" in options or\ + "r" in options: # cоздаем объект DNS servDnsObj = servDns() # Проверим установлен ли сервис dns @@ -14407,9 +14396,9 @@ class cl_info(cl_utils2.cl_smartcon, prnServ): return False objTxtZone = dnsTxt() # Удаляет лишние точки в названии - delDot = lambda y: ".".join(filter(lambda x: x, y.split("."))) + delDot = lambda y: ".".join(x for x in y.split(".") if x) # Информация о всех DNS зонах - if service == "dns" and options.has_key("z"): + if service == "dns" and "z" in options: # Зоны в файле namesZonesFile = objTxtZone.getAllNamesZones() if namesZonesFile == False: @@ -14417,15 +14406,13 @@ class cl_info(cl_utils2.cl_smartcon, prnServ): # Зоны в LDAP namesZonesLDAP = servDnsObj.searchAllZonesInLDAP() # Подчиненные зоны - slaveZones = list(set(namesZonesFile)-set(namesZonesLDAP)) + slaveZones = list(set(namesZonesFile) - set(namesZonesLDAP)) # Обратные зоны if namesZonesLDAP: namesZonesLDAP.sort() - reverseZones = filter(lambda x: '.in-addr.arpa' in x,\ - namesZonesLDAP) + reverseZones = [x for x in namesZonesLDAP if '.in-addr.arpa' in x] # Прямые зоны - forwardZones = filter(lambda x: not '.in-addr.arpa' in x,\ - namesZonesLDAP) + forwardZones = [x for x in namesZonesLDAP if '.in-addr.arpa' not in x] # Формирование строки для отчета title=_("Information about the master DNS zones in LDAP") headerList = [_("DNS zone"), @@ -14434,12 +14421,10 @@ class cl_info(cl_utils2.cl_smartcon, prnServ): # Получение домена getDomain = lambda x: not '.in-addr.arpa' in x and x or "" # Получение сети - getNet = lambda x: ".".join(map(lambda x:x,\ - reversed('.in-addr.arpa' in x and ["0/24"] +\ - x.rpartition(".in-addr.arpa")[0].split(".") or []))) - dataList = map(lambda x:\ - [x, getDomain(x), getNet(x)],\ - forwardZones + reverseZones) + getNet = lambda x: ".".join(x for x + in reversed('.in-addr.arpa' in x and ["0/24"] +\ + x.rpartition(".in-addr.arpa")[0].split(".") or [])) + dataList = [[x, getDomain(x), getNet(x)] for x in forwardZones + reverseZones] repObj = report(title, headerList, dataList) repObj.printReport() if slaveZones: @@ -14454,30 +14439,26 @@ class cl_info(cl_utils2.cl_smartcon, prnServ): if xmlNodes: masterIPNode = xmlNodes[0] xmlNodes = xpath.Evaluate( "child::value", masterIPNode) - ips = map(lambda x: x.firstChild.nodeValue.strip(),\ - xmlNodes) + ips = (x.firstChild.nodeValue.strip() for x in xmlNodes) flagAddIPs = True slaveIPs.append(",".join(ips)) if not flagAddIPs: slaveIPs.append("") - reverseZones = filter(lambda x: '.in-addr.arpa' in x,\ - slaveZones) + reverseZones = [x for x in slaveZones if '.in-addr.arpa' in x] # Прямые зоны - forwardZones = filter(lambda x: not '.in-addr.arpa' in x,\ - slaveZones) + forwardZones = [x for x in slaveZones if '.in-addr.arpa' not in x] # Формирование строки для отчета title=_("Information about the slave DNS zones in \ /etc/bind/named.conf") headerList = [_("DNS zone"),_("IP master DNS servers")] - dataList = map(lambda x: [x], forwardZones + reverseZones) - dataList = map(lambda x: dataList[x]+[slaveIPs[x]],\ - range(len(dataList))) + dataList = ([x] for x in forwardZones + reverseZones) + dataList = [dataList[x] + [slaveIPs[x]] for x in range(len(dataList))] repObj = report(title, headerList, dataList) - print "" + print("") repObj.printReport() return True # Информация о DNS зоне - if service == "dns" and options.has_key("Z"): + if service == "dns" and "Z" in options: zoneName = options["Z"] if not zoneName: self.printERROR(_('Incorrect zone name')) @@ -14523,9 +14504,7 @@ class cl_info(cl_utils2.cl_smartcon, prnServ): if xmlNodes: masterIPNode = xmlNodes[0] xmlNodes = xpath.Evaluate( "child::value", masterIPNode) - ipMasterServers = map(lambda x:\ - x.firstChild.nodeValue.strip(),\ - xmlNodes) + ipMasterServers = [x.firstChild.nodeValue.strip() for x in xmlNodes] if not ipMasterServers: self.printERROR(_("The program does not support information \ for %s DNS zone")%zoneName) @@ -14554,12 +14533,12 @@ for %s DNS zone")%zoneName) # Все авторитативные сервера зоны nSRecords = zoneData[0][0][1]['nSRecord'] mXRecords = [] - if zoneData[0][0][1].has_key('mXRecord'): + if 'mXRecord' in zoneData[0][0][1]: mXRecords = zoneData[0][0][1]['mXRecord'] aRecords = [] - if zoneData[0][0][1].has_key('aRecord'): + if 'aRecord' in zoneData[0][0][1]: aRecords = zoneData[0][0][1]['aRecord'] - soaData = map(lambda x: delDot(x), soaRecord.split(" ")) + soaData = [delDot(x) for x in soaRecord.split(" ")] if len(soaData)!=7: self.printERROR(_("Incorrect SOA-record in DNS zone %s")\ %zoneName) @@ -14591,13 +14570,13 @@ for %s DNS zone")%zoneName) [_("Expiry"), expiry], [_("Minimum"), minimum]] if mXRecords: - map(lambda x:dataList.insert(2,["",x]) ,reversed(mXRecords[1:])) + [dataList.insert(2, ["", x]) for x in reversed(mXRecords[1:])] dataList.insert(2,[_("MX-record"), mXRecords[0]]) if aRecords: - map(lambda x:dataList.insert(2,["",x]) ,reversed(aRecords[1:])) + [dataList.insert(2, ["", x]) for x in reversed(aRecords[1:])] dataList.insert(2,[_("A-record"), aRecords[0]]) if nSRecords: - map(lambda x:dataList.insert(2,["",x]), reversed(nSRecords[1:])) + [dataList.insert(2, ["", x]) for x in reversed(nSRecords[1:])] dataList.insert(2,[_("NS-record"), nSRecords[0]]) repObj = report(title, headerList, dataList) repObj.printReport() @@ -14612,10 +14591,10 @@ for %s DNS zone")%zoneName) domainName = "%s.%s"\ %(record[0][1]["relativeDomainName"][0],\ zoneName) - if record[0][1].has_key("aRecord"): + if "aRecord" in record[0][1]: dataAList.append([domainName, record[0][1]["aRecord"][0]]) - if record[0][1].has_key("mXRecord"): + if "mXRecord" in record[0][1]: flagFirst = True flagError = False for mxData in record[0][1]["mXRecord"]: @@ -14638,7 +14617,7 @@ for %s DNS zone")%zoneName) _("Incorrect MX-records in A-record %s")\ %domainName) return False - elif record[0][1].has_key("cNAMERecord"): + elif "cNAMERecord" in record[0][1]: dataCNList.append([domainName, delDot(record[0][1]["cNAMERecord"][0])]) allDataList = [dataAList, dataCNList,dataMXList] @@ -14655,21 +14634,21 @@ for %s DNS zone")%zoneName) headerList = allHeaderList[i] dataList = allDataList[i] repObj = report(title, headerList, dataList) - print "" + print("") repObj.printReport() # Если обратная зона else: dataPTRList = [] # Получение из названия зоны cтроки из 3-х частей IP - getThreeOctetsIP = lambda x: ".".join(map(lambda x:x,\ - reversed('.in-addr.arpa' in x and\ - x.rpartition(".in-addr.arpa")[0].split(".") or []))) + getThreeOctetsIP = lambda x: ".".join(x + for x in reversed('.in-addr.arpa' in x and\ + x.rpartition(".in-addr.arpa")[0].split(".") or [])) threeOctetsIP = getThreeOctetsIP(zoneName) if not threeOctetsIP: - self.printERROR(_("Incorrect zone name %s")%zoneName) + self.printERROR(_("Incorrect zone name %s") % zoneName) return False for record in recordsSearch: - if record[0][1].has_key("pTRRecord"): + if "pTRRecord" in record[0][1]: IP = "%s.%s"%(threeOctetsIP,\ record[0][1]["relativeDomainName"][0]) domainName = delDot(record[0][1]["pTRRecord"][0]) @@ -14681,11 +14660,11 @@ for %s DNS zone")%zoneName) headerList = ("ip", _("Domain")) dataList = dataPTRList repObj = report(title, headerList, dataList) - print "" + print("") repObj.printReport() return True # Информация о DNS записи - if service == "dns" and options.has_key("r"): + if service == "dns" and "r" in options: hostOrIP = options["r"] # Флаг True - hostOrIP является хостом hostInForwardZone = servDnsObj.isForwardName(hostOrIP) @@ -14696,7 +14675,7 @@ for %s DNS zone")%zoneName) headerList = [_("Field"), _("Value")] dataList = [] # Удаляет лишние точки в названии - delDot = lambda y: ".".join(filter(lambda x: x, y.split("."))) + delDot = lambda y: ".".join(x for x in y.split(".") if x) # hostOrIP является именем хоста if hostInForwardZone: domainName = delDot(hostOrIP.lower()) @@ -14713,10 +14692,10 @@ for %s DNS zone")%zoneName) flagF = True for record in dataRecords: dataList.append([_("Domain name"), domainName]) - if record[0][1].has_key("aRecord"): + if "aRecord" in record[0][1]: dataList.append([_("A-record"),\ record[0][1]["aRecord"][0]]) - if record[0][1].has_key("mXRecord"): + if "mXRecord" in record[0][1]: flagFirst = True flagError = False for mxData in record[0][1]["mXRecord"]: @@ -14735,7 +14714,7 @@ for %s DNS zone")%zoneName) %domainName) return False typeRecord = "A" - elif record[0][1].has_key("cNAMERecord"): + elif "cNAMERecord" in record[0][1]: dataList.append([_("CNAME-record"),\ record[0][1]["cNAMERecord"][0]]) typeRecord = "CNAME" @@ -14746,7 +14725,7 @@ for %s DNS zone")%zoneName) if flagF: flagF = False else: - print "" + print("") repObj.printReport() # hostOrIP является ip else: @@ -14769,7 +14748,7 @@ for %s DNS zone")%zoneName) typeRecord = "Unknown" for record in dataRecords: dataList.append(["ip", ip]) - if record[0][1].has_key("pTRRecord"): + if "pTRRecord" in record[0][1]: domainNameDot = record[0][1]["pTRRecord"][0] dataList.append([_("PTR-record"), domainNameDot]) typeRecord = "PTR" @@ -14780,11 +14759,11 @@ for %s DNS zone")%zoneName) if flagF: flagF = False else: - print "" + print("") repObj.printReport() return True # Информация о компьютере - if options.has_key("M"): + if "M" in options: machineName = options["M"] data = self.getMachine(machineName, service) if not data: @@ -14793,7 +14772,7 @@ for %s DNS zone")%zoneName) title=_("Information about machine %s") %machineName + " " +\ _("for service %s") %strService # Информация о пользователе - elif options.has_key("U"): + elif "U" in options: userName = options["U"] data = self.getUser(userName, service) if not data: @@ -14802,7 +14781,7 @@ for %s DNS zone")%zoneName) title=_("Information about user %s") %userName + " " +\ _("for service %s") %strService # Информация о группе - elif options.has_key("G"): + elif "G" in options: groupName = options["G"] data = self.getGroup(groupName, service) if not data: @@ -14812,9 +14791,9 @@ for %s DNS zone")%zoneName) _("for service %s") %strService # Информация о компьютерах - elif options.has_key("m"): + elif "m" in options: fields = "short" - if options.has_key("full"): + if "full" in options: fields = "full" data = self.getAllMachines(fields, service) if not data: @@ -14822,9 +14801,9 @@ for %s DNS zone")%zoneName) headerList, dataList = data title=_("All machines in LDAP for service %s")%strService # Информация о пользователях - elif options.has_key("u"): + elif "u" in options: fields = "short" - if options.has_key("full"): + if "full" in options: fields = "full" data = self.getAllUsers(fields, service) if not data: @@ -14832,9 +14811,9 @@ for %s DNS zone")%zoneName) headerList, dataList = data title=_("All users in LDAP for service %s")%strService # Информация о группах - elif options.has_key("g"): + elif "g" in options: fields = "short" - if options.has_key("full"): + if "full" in options: fields = "full" data = self.getAllGroups(fields, service) if not data: @@ -14842,14 +14821,14 @@ for %s DNS zone")%zoneName) headerList, dataList = data title=_("All groups in LDAP for service %s")%strService - if options.has_key("M") or options.has_key("m") or\ - options.has_key("U") or options.has_key("G") or\ - options.has_key("u") or options.has_key("g"): + if "M" in options or "m" in options or\ + "U" in options or "G" in options or\ + "u" in options or "g" in options: repObj = report(title, headerList, dataList) repObj.printReport() return True - if len(options) == 1 and options.has_key("full"): + if len(options) == 1 and "full" in options: self.printERROR(_("Can not use a single command line option \ 'full'.")) @@ -14865,7 +14844,7 @@ with another option.")) branchData = {'users':'relUsersDN', 'groups':'relGroupsDN', 'computers':'relComputersDN'} - if not branchData.has_key(branch): + if branch not in branchData: self.printERROR("getQueryLDAP service=%s"%service) self.printERROR(_("ERROR: getQueryLDAP incorrect branch=%s")%branch) return False @@ -14879,7 +14858,8 @@ with another option.")) # Если сервис не установлен то ошибка if not servObj.isServiceSetup(service): return False - if not servObj.__dict__.has_key(relAttr): + #TODO debug this: + if relAttr not in servObj.__dict__: self.printERROR("getQueryLDAP service=%s"%service) self.printERROR(_("ERROR: getQueryLDAP incorrect branch=%s")%branch) return False @@ -14903,8 +14883,8 @@ with another option.")) %self.printNameService(service)) return False headers = [_("Field"),_("Value")] - attributes = map(lambda x: x[0], data) - retrAttrs = map(lambda x: x[1], data) + attributes = [x[0] for x in data] + retrAttrs = [x[1] for x in data] retClVars=False searchRes = self.getQueryLDAP(service, "computers", searchAttr, searchStr, retrAttrs) @@ -14958,8 +14938,8 @@ with another option.")) %self.printNameService(service)) return False headers = [_("Field"),_("Value")] - attributes = map(lambda x: x[0], data) - retrAttrs = map(lambda x: x[1], data) + attributes = [x[0] for x in data] + retrAttrs = [x[1] for x in data] retClVars=False searchRes = self.getQueryLDAP(service, "groups", searchAttr, searchStr, retrAttrs) @@ -14970,7 +14950,7 @@ with another option.")) if service == "proxy": for i in searchRes: memberList = i[0][1]['member'] - i[0][1]['member']=map(lambda x: x.partition("=")[2],memberList) + i[0][1]['member'] = [x.partition("=")[2] for x in memberList] if service == "jabber": servObj = servJabber() resMemberSearch = servObj.searchUsersToGroup(groupName) @@ -14981,14 +14961,14 @@ with another option.")) for i in searchRes: i[0][1]['memberUid'] = memberUid data.append((_("Member UID"),"memberUid")) - attributes = map(lambda x: x[0], data) - retrAttrs = map(lambda x: x[1], data) + attributes = [x[0] for x in data] + retrAttrs = [x[1] for x in data] data = [] lenRetrAttrs = len(retrAttrs) # Добавляем первичные группы if service in ("unix", "samba"): memberUid = [] - if searchRes[0][0][1].has_key('memberUid'): + if 'memberUid' in searchRes[0][0][1]: memberUid = searchRes[0][0][1]['memberUid'] groupId = searchRes[0][0][1]['gidNumber'][0] primaryUids = self.getUnixUidPrimGroup(groupId) @@ -15032,8 +15012,8 @@ with another option.")) %self.printNameService(service)) return False headers = [_("Field"), _("Value")] - attributes = map(lambda x: x[0], data) - retrAttrs = map(lambda x: x[1], data) + attributes = [x[0] for x in data] + retrAttrs = [x[1] for x in data] retClVars=False if service in ["mail", "samba"]: retClVars=True @@ -15051,7 +15031,7 @@ with another option.")) if service == "mail": for i in searchRes: i[0][1]['homeDirectory'] = [os.path.join(\ - clVars.Get("sr_mail_path"),i[0][1]['uid'][0])] + clVars.Get("sr_mail_path"), i[0][1]['uid'][0])] data.append((_("Home directory"),"homeDirectory")) # Добавляем директории пользователя для сервиса samba # а так же первичную и дополнительные группы @@ -15099,8 +15079,8 @@ with another option.")) if os.path.exists(winLogonPath): i[0][1]['winLogonPath'] = [winLogonPath] data.append((_("Windows logon"),"winLogonPath")) - attributes = map(lambda x: x[0], data) - retrAttrs = map(lambda x: x[1], data) + attributes = [x[0] for x in data] + retrAttrs = [x[1] for x in data] data = [] lenRetrAttrs = len(retrAttrs) @@ -15166,9 +15146,9 @@ with another option.")) %self.printNameService(service)) return False if fields == "short": - data = filter(lambda x: not x[0] in delData, data) - headers = map(lambda x: x[0], data) - retrAttrs = map(lambda x: x[1], data) + data = [x for x in data if x[0] not in delData] + headers = [x[0] for x in data] + retrAttrs = [x[1] for x in data] machines = [] searchRes = self.getQueryLDAP(service, "computers", searchAttr, searchStr, retrAttrs) @@ -15203,9 +15183,9 @@ with another option.")) %self.printNameService(service)) return False if fields == "short": - data = filter(lambda x: not x[0] in delData, data) - headers = map(lambda x: x[0], data) - retrAttrs = map(lambda x: x[1], data) + data = [x for x in data if x[0] not in delData] + headers = [x[0] for x in data] + retrAttrs = [x[1] for x in data] groups = [] searchRes = self.getQueryLDAP(service, "groups", searchAttr, searchStr, retrAttrs) @@ -15215,15 +15195,14 @@ with another option.")) return (headers , []) for info in searchRes: if service in ("proxy",): - if info[0][1].has_key('member'): + if 'member' in info[0][1]: memberList = info[0][1]['member'] - info[0][1]['member'] = map(lambda x: x.partition("=")[2],\ - memberList) + info[0][1]['member'] = [x.partition("=")[2] for x in memberList] listAttr = [] # Добавляем первичные группы if service in ("unix", "samba"): memberUid = [] - if info[0][1].has_key('memberUid'): + if 'memberUid' in info[0][1]: memberUid = info[0][1]['memberUid'] groupId = info[0][1]['gidNumber'][0] primaryUids = self.getUnixUidPrimGroup(groupId) @@ -15382,9 +15361,9 @@ with another option.")) %self.printNameService(service)) return False if fields == "short": - data = filter(lambda x: not x[0] in delData, data) - headers = map(lambda x: x[0], data) - retrAttrs = map(lambda x: x[1], data) + data = [x for x in data if x[0] not in delData] + headers = [x[0] for x in data] + retrAttrs = [x[1] for x in data] loginsUsers = [] retClVars=False @@ -15407,9 +15386,9 @@ with another option.")) data.append((_("Home directory"),"homeDirectory")) delData.append(_("Home directory")) if fields == "short": - data = filter(lambda x: not x[0] in delData, data) - headers = map(lambda x: x[0], data) - retrAttrs = map(lambda x: x[1], data) + data = [x for x in data if x[0] not in delData] + headers = [x[0] for x in data] + retrAttrs = [x[1] for x in data] for info in searchRes: listAttr = [] for attr in retrAttrs: @@ -15510,11 +15489,12 @@ with another option.")) """Конвертирует количество дней или секунд с 1970, в строку даты""" if dataDays: if len(str(dataDays)) <= 6: - value = long(dataDays)*86400 + value = long(dataDays) * 86400 elif len(str(dataDays)) > 6: value = long(dataDays) - return reduce(lambda x,y: y+"."+x,map(lambda x: (len(str(x))==1 and\ - "0"+str(x)) or str(x), time.localtime(value)[:3])) + return reduce(lambda x,y: y + "." + x, [(len(str(x)) == 1 + and "0" + str(x)) or str(x) + for x in time.localtime(value)[:3]]) return "" def _getUserGroupName(self, userGid, service): @@ -15662,20 +15642,20 @@ class servProxy(shareLdap): def filterProxyServer(self, options): """Фильтр Proxy групп для доступа пользователя""" optPwd = ["p","P"] - listOptPwd = filter(lambda x: x in optPwd, options.keys()) + listOptPwd = [x for x in options.keys() if x in optPwd] if len(listOptPwd) > 1: self.printERROR(_("Command line options '-p' and '-P' are \ incompatible, use one of the options")) return False - if not (options.has_key("s") and options.has_key("b") and\ - (options.has_key("p") or options.has_key("P"))): + if not ("s" in options and "b" in options and\ + ("p" in options or "P" in options)): self.printERROR(_("Not found the options '-s' and '-b' and ('-p' \ or '-P')")) return False adminDn = options['s'] - if options.has_key("p"): + if "p" in options: adminPw = options['p'] - elif options.has_key("P"): + elif "P" in options: pathPasswd = options['P'] if os.path.exists(pathPasswd): try: @@ -15696,7 +15676,7 @@ or '-P')")) try: strInput = sys.stdin.readline() strInput = strInput[:-1] - params = map(lambda x: x, strInput.split(" ")) + params = strInput.split(" ") if params == ['']: sys.stdout.write("ERR\n") sys.stdout.flush() @@ -15724,7 +15704,7 @@ or '-P')")) def searchProxyGroups(self, groupNames): """Ищет группы. Находит все группы - True иначе - False""" - notFindGroup=filter(lambda x: not self.searchGroupToName(x), groupNames) + notFindGroup = [x for x in groupNames if not self.searchGroupToName(x)] if notFindGroup: self.printERROR(_("Groups %s is not found in Proxy service")\ %", ".join(notFindGroup)) @@ -15752,13 +15732,13 @@ or '-P')")) self.clVars.Set("ur_group",groupName) # Комментарий к группе groupGecos = self.servUnixObj.groupGecos - if options.has_key('c'): + if 'c' in options: groupGecos = options['c'] self.clVars.Set("ur_group_comment",groupGecos) # Тип группы groupType = "port" accessPorts = "" - if options.has_key('p'): + if 'p' in options: accessPorts = options['p'] reFalseString = re.compile("[^\d,\-]|^,|^-|,-|-,|,$|-$") if reFalseString.search(accessPorts): @@ -15773,12 +15753,12 @@ is not valid ") %accessPorts) ldifFile = self.ldifFileGroup groupLdif = self.createLdif(ldifFile) if not groupLdif: - print self.getError() + print(self.getError()) return False if not self.ldapObj.getError(): self.ldapObj.ldapAdd(groupLdif) if self.ldapObj.getError(): - print _("LDAP Error") + ": " + self.ldapObj.getError().strip() + print(_("LDAP Error") + ": " + self.ldapObj.getError().strip()) return False self.printSUCCESS(_("Added group '%s' in Proxy service")\ %groupName) @@ -15852,7 +15832,7 @@ is not valid ") %accessPorts) self.clVars.Set("ur_name", userName) #Полное имя пользователя (комментарий) fullNameUser = self.servUnixObj.fullNameUser - if options.has_key('c'): + if 'c' in options: fullNameUser = options['c'] else: # Проверяем установку сервиса не печатая ошибку в случае @@ -15860,7 +15840,7 @@ is not valid ") %accessPorts) if self.isServiceSetup("unix",False): resUnix = self.servUnixObj.searchUnixUser(userName) # Берем комментарий для пользователя из Unix - if resUnix and resUnix[0][0][1].has_key('cn'): + if resUnix and 'cn' in resUnix[0][0][1]: fullNameUser = resUnix[0][0][1]['cn'][0] self.clVars.Set("ur_fio",fullNameUser) ldifFile = self.ldifFileUser @@ -15871,7 +15851,7 @@ is not valid ") %accessPorts) #ldapObj.ldapAdd(userLdif1) # не переделывать на else if self.ldapObj.getError(): - print _("LDAP Error") + ": " + self.ldapObj.getError().strip() + print(_("LDAP Error") + ": " + self.ldapObj.getError().strip()) return False self.printSUCCESS(_("Added user in Proxy service")) return True @@ -15896,13 +15876,12 @@ is not valid ") %accessPorts) # Группа не пуста flagEmptyGroup = False # Если есть пустой member аттрибут (пустая группа) - if filter(lambda x: not x.strip(), searchGroup[0][0][1]['member']): + if [x for x in searchGroup[0][0][1]['member'] if not x.strip()]: flagEmptyGroup = True addUsers = users else: - memberUsers = map(lambda x:x.rpartition("=")[2],\ - searchGroup[0][0][1]["member"]) - addUsers = filter(lambda x: not x in memberUsers, users) + memberUsers = [x.rpartition("=")[2] for x in searchGroup[0][0][1]["member"]] + addUsers = [x for x in users if x not in memberUsers] for userName in addUsers: if flagEmptyGroup: modAttrs.append((ldap.MOD_REPLACE, 'member', "uid="+userName)) @@ -15945,12 +15924,11 @@ is not valid ") %accessPorts) %str(groupName)) return False # Если группа пуста - if filter(lambda x: not x.strip(), searchGroup[0][0][1]['member']): + if [x for x in searchGroup[0][0][1]['member'] if not x.strip()]: self.printERROR( _("Member list of group %s is empty")%str(groupName)) - return False - memberUsers = map(lambda x:x.rpartition("=")[2],\ - searchGroup[0][0][1]["member"]) + memberUsers = [x.rpartition("=")[2] for x + in searchGroup[0][0][1]["member"]] flagError = False for user in users: if not user in memberUsers: @@ -15986,10 +15964,10 @@ is not valid ") %accessPorts) # Изменяемые аттрибуты пользователя modAttrs = [] # Включаем пользователя - if options.has_key('u'): + if 'u' in options: modAttrs += [(ldap.MOD_REPLACE, 'initials', "Yes")] # Выключаем пользователя - elif options.has_key('l'): + elif 'l' in options: modAttrs += [(ldap.MOD_REPLACE, 'initials', "No")] if not options: optPasswd = {"p":""} @@ -15999,7 +15977,7 @@ is not valid ") %accessPorts) userPwdHash = self.getHashPasswd(userPwd, self.userCrypt) if not userPwdHash: return False - if res[0][0][1].has_key('userPassword'): + if 'userPassword' in res[0][0][1]: modAttrs.append((ldap.MOD_REPLACE, 'userPassword', userPwdHash)) else: @@ -16009,10 +15987,10 @@ is not valid ") %accessPorts) DN = self.addDN("uid="+userName, self.relUsersDN) if not self.modAttrsDN(DN, modAttrs): return False - if options.has_key('l'): + if 'l' in options: self.printSUCCESS(_("Locked user") + " " + str(userName) +\ " " +_("of Proxy service")) - if options.has_key('u'): + if 'u' in options: self.printSUCCESS(_("Unlocked user") + " " + str(userName) +\ " " +_("of Proxy service")) if not options: @@ -16031,7 +16009,7 @@ is not valid ") %accessPorts) _("User %s is not found in Proxy service")%str(userName)) return False # Новые группы в которые входит пользователь - if options.has_key('G'): + if 'G' in options: userGroups = options['G'].split(',') if not self.searchProxyGroups(userGroups): return False @@ -16047,7 +16025,7 @@ is not valid ") %accessPorts) return False self.printSUCCESS(_("Replaced list of supplementary group")) # Добавляем группы в которые входит пользователь - elif options.has_key('a'): + elif 'a' in options: userGroups = options['a'].split(',') if not self.searchProxyGroups(userGroups): return False @@ -16062,13 +16040,13 @@ is not valid ") %accessPorts) # Изменяемые аттрибуты пользователя modAttrs = [] # Включаем пользователя - if options.has_key('U'): + if 'U' in options: modAttrs += [(ldap.MOD_REPLACE, 'initials', "Yes")] # Выключаем пользователя - elif options.has_key('L'): + elif 'L' in options: modAttrs += [(ldap.MOD_REPLACE, 'initials', "No")] # Изменяем комментарий к пользователю - if options.has_key('c'): + if 'c' in options: comment = options['c'] modAttrs += [(ldap.MOD_REPLACE, 'sn', comment), (ldap.MOD_REPLACE, 'cn', comment)] @@ -16080,7 +16058,7 @@ is not valid ") %accessPorts) userPwdHash = self.getHashPasswd(userPwd, self.userCrypt) if not userPwdHash: return False - if res[0][0][1].has_key('userPassword'): + if 'userPassword' in res[0][0][1]: modAttrs.append((ldap.MOD_REPLACE, 'userPassword', userPwdHash)) else: @@ -16090,13 +16068,13 @@ is not valid ") %accessPorts) DN = self.addDN("uid="+userName, self.relUsersDN) if not self.modAttrsDN(DN, modAttrs): return False - if options.has_key('P') or options.has_key('p'): + if 'P' in options or 'p' in options: self.printSUCCESS(_("Modified user password")) - if options.has_key('c'): + if 'c' in options: self.printSUCCESS(_("Modified comment")) - if options.has_key('U'): + if 'U' in options: self.printSUCCESS(_("Unlocked user %s")% str(userName)) - if options.has_key('L'): + if 'L' in options: self.printSUCCESS(_("Locked user %s")% str(userName)) return True @@ -16111,7 +16089,7 @@ is not valid ") %accessPorts) %str(groupName)) return False # Добавляем список пользователей в группу - if options.has_key('a'): + if 'a' in options: # добавляемые пользователи в группу users = options['a'].split(',') res = self.addUsersGroupProxy(users, groupName) @@ -16123,7 +16101,7 @@ is not valid ") %accessPorts) " " + str(groupName)) return False # Удаляем список пользователей из группы - if options.has_key('d'): + if 'd' in options: # удаляемые пользователи из группы users = options['d'].split(',') res = self.delUsersGroupProxy(users, groupName) @@ -16135,7 +16113,7 @@ is not valid ") %accessPorts) " " + str(groupName)) return False # Изменяем комментарий к группе - if options.has_key('c'): + if 'c' in options: gecos = options['c'] modAttrs = [(ldap.MOD_REPLACE, 'description', gecos)] groupDN = self.addDN("cn="+groupName, self.relGroupsDN) @@ -16146,7 +16124,7 @@ is not valid ") %accessPorts) " " + str(groupName)) return False # Изменяем имя группы - if options.has_key('n'): + if 'n' in options: newGroupName = options['n'] newFirstDn = "cn=" + newGroupName oldDN = self.addDN("cn=" + groupName, self.relGroupsDN) @@ -16167,8 +16145,8 @@ is not valid ") %accessPorts) self.clVars должен быть определен """ - print _("Enter the allowed ip addresses and network for %s service")\ - %"Proxy" + " (" + _("comma or space delimited") + ")" + print(_("Enter the allowed ip addresses and network for %s service")\ + %"Proxy" + " (" + _("comma or space delimited") + ")") strPrompt = _("allow networks: ") netAllow = self.clVars.Get("sr_proxy_net_allow") strNetAllow = "" @@ -16187,7 +16165,7 @@ is not valid ") %accessPorts) """Начальная настройка Proxy сервиса""" # Принудительная установка forceOptions = False - if options.has_key("f"): + if "f" in options: forceOptions = True # Создаем объект переменных и начальная проверка if not self.initialChecksSetup(): @@ -16204,7 +16182,7 @@ is not valid ") %accessPorts) _("Proxy server is configured")+ ".") return True # Порт для прокси сервера - if options.has_key("p"): + if "p" in options: proxyPort = options['p'] try: numberProxyPort = int(proxyPort) @@ -16227,13 +16205,13 @@ is not valid ") %accessPorts) _("input 'yes'") +", "+ _("if not 'no'") if not self.dialogYesNo(messDialog): return True - if options.has_key("a"): + if "a" in options: # Получаем от пользователя доверительные сети allowNet = self.getAllowNet() if not allowNet: return False else: - if options.has_key("a"): + if "a" in options: # Получаем от пользователя доверительные сети allowNet = self.getAllowNet() if not allowNet: @@ -16253,7 +16231,7 @@ is not valid ") %accessPorts) self.createClVars() # Устанавливаем доступные сети self.clVars.Set("sr_proxy_net_allow", allowNet, True) - if options.has_key("p"): + if "p" in options: self.clVars.Set("sr_proxy_port",proxyPort, True) # Удаляем из автозапуска демона if not self.delDaemonAutostart("squid"): @@ -16268,7 +16246,7 @@ is not valid ") %accessPorts) fullHostName = "%s.%s"%(self.clVars.Get('os_net_hostname'), self.clVars.Get('os_net_domain')) jabberHosts = fullHostName - if options.has_key("host"): + if "host" in options: fullHostName = options['host'] if not "." in fullHostName: fullHostName = "%s.%s" %(fullHostName, @@ -16307,7 +16285,7 @@ is not valid ") %accessPorts) if not self.ldapObj.getError(): self.ldapObj.ldapAdd(baseLdif) if self.ldapObj.getError(): - print _("LDAP Error") + ": " + self.ldapObj.getError().strip() + print(_("LDAP Error") + ": " + self.ldapObj.getError().strip()) return False # Записываем данные администратора сервиса Proxy ldapParser = iniLdapParser() @@ -16431,7 +16409,7 @@ class dncpTxt(cl_profile.dhcp, shareTxt, shareIP): (ip, '\tfixed-address %s;'%ip), (mac,'\thardware ethernet %s;'%mac), (True, '}')] - templateList = map(lambda x: x[1], filter(lambda x: x[0], templateList)) + templateList = [x[1] for x in templateList if x[0]] template = "".join(templateList) return template @@ -16462,7 +16440,7 @@ class dncpTxt(cl_profile.dhcp, shareTxt, shareIP): %(delChar,domainNameServers)), (iprange, '\t%srange %s;'%(delChar, iprange)), (True, '}')] - templateList = map(lambda x: x[1], filter(lambda x: x[0], templateList)) + templateList = [x[1] for x in templateList if x[0]] template = "".join(templateList) return template @@ -16475,9 +16453,10 @@ class dncpTxt(cl_profile.dhcp, shareTxt, shareIP): "child::area/child::caption/child::name", xmlNodeBody) if not namesArea: return [] - return filter(lambda x: x.firstChild and x.firstChild.nodeValue and\ - len(x.firstChild.nodeValue) > 4 and\ - 'host' in x.firstChild.nodeValue[:4], namesArea) + return [x for x in namesArea + if x.firstChild and x.firstChild.nodeValue and\ + len(x.firstChild.nodeValue) > 4 and\ + 'host' in x.firstChild.nodeValue[:4]] def getAllXMLSubnet(self): """Получаем все XML ноды подсетей""" @@ -16488,23 +16467,24 @@ class dncpTxt(cl_profile.dhcp, shareTxt, shareIP): "child::area/child::caption/child::name", xmlNodeBody) if not namesArea: return [] - return filter(lambda x: x.firstChild and x.firstChild.nodeValue and\ - len(x.firstChild.nodeValue) > 6 and\ - 'subnet' in x.firstChild.nodeValue[:6], namesArea) + return [x for x in namesArea + if x.firstChild and x.firstChild.nodeValue and\ + len(x.firstChild.nodeValue) > 6 and\ + 'subnet' in x.firstChild.nodeValue[:6]] def getDataInAllHost(self): """Получить информацию о статических хостах""" if self.getError(): return False allXmlNames = self._getAllXMLStaticHosts() - allXmlAreas = map(lambda x: x.parentNode.parentNode, allXmlNames) + allXmlAreas = [x.parentNode.parentNode for x in allXmlNames] # Информация dataHost = [] iterXmlNames = iter(allXmlNames) for xmlArea in allXmlAreas: #print xmlArea.toprettyxml() # Ност - xmlNodeName = iterXmlNames.next() + xmlNodeName = next(iterXmlNames) strNameNode = xmlNodeName.firstChild.nodeValue # название хоста hostname = strNameNode.partition("host")[2].strip().encode("UTF-8") @@ -16521,13 +16501,13 @@ class dncpTxt(cl_profile.dhcp, shareTxt, shareIP): if self.getError(): return False allXmlNames = self.getAllXMLSubnet() - allXmlAreas = map(lambda x: x.parentNode.parentNode, allXmlNames) + allXmlAreas = [x.parentNode.parentNode for x in allXmlNames] # Информация dataNet = [] iterXmlNames = iter(allXmlNames) for xmlArea in allXmlAreas: # Сеть - xmlNodeName = iterXmlNames.next() + xmlNodeName = next(iterXmlNames) # Название области strNameNode = xmlNodeName.firstChild.nodeValue # ip сети @@ -16565,10 +16545,10 @@ class dncpTxt(cl_profile.dhcp, shareTxt, shareIP): return binList[::-1] listOctMask = ipNetMask.split('.') - if filter(lambda x: not isNumber(x), listOctMask): + if [x for x in listOctMask if not isNumber(x)]: return "" - countOne = lambda z: filter(lambda x:x==1, strToBinList(z)) - numberMask = sum(map(lambda x: sum(countOne(x)), listOctMask)) + countOne = lambda z: [x for x in strToBinList(z) if x == 1] + numberMask = sum(sum(countOne(x)) for x in listOctMask) return str(numberMask) @@ -16584,10 +16564,8 @@ class dncpTxt(cl_profile.dhcp, shareTxt, shareIP): nodesXml = xpath.Evaluate("child::value", node) for nodeFind in nodesXml: if nodeFind.firstChild: - listOpt = map(lambda x: x.encode("UTF-8"),\ - filter(lambda x: x,\ - nodeFind.firstChild.nodeValue.replace("\t",\ - " ").split(" "))) + listOpt = [x.encode("UTF-8") for x + in nodeFind.firstChild.nodeValue.replace("\t"," ").split(" ") if x] dataPars[opt] = listOpt return dataPars @@ -16601,8 +16579,8 @@ class dncpTxt(cl_profile.dhcp, shareTxt, shareIP): if not xmlStaticHosts: return [] slpHostName = 'host%s' %hostName.lower() - return map(lambda x: x.parentNode.parentNode, filter(lambda x:\ - slpHostName == x.firstChild.nodeValue.lower(), xmlStaticHosts)) + return [x.parentNode.parentNode for x in xmlStaticHosts + if slpHostName == x.firstChild.nodeValue.lower()] def getXMLNet(self, net): """Получить XML ноду подсети по ip""" @@ -16614,10 +16592,9 @@ class dncpTxt(cl_profile.dhcp, shareTxt, shareIP): return [] slpNetName = 'subnet%s' %net.lower() lenSlpNetName = len(slpNetName) - return map(lambda x: x.parentNode.parentNode, filter(lambda x:\ - len(x.firstChild.nodeValue)>lenSlpNetName and\ - slpNetName==x.firstChild.nodeValue[:lenSlpNetName].lower(),\ - xmlSubnets)) + return [x.parentNode.parentNode for x in xmlSubnets + if len(x.firstChild.nodeValue) > lenSlpNetName and + slpNetName == x.firstChild.nodeValue[:lenSlpNetName].lower()] def createStaticHost(self, hostname, ip, mac): """Создает статический хост в файле конфигурации dhcp""" @@ -16648,7 +16625,7 @@ class dncpTxt(cl_profile.dhcp, shareTxt, shareIP): netIPList = splNameNewNode.partition("subnet")[2].partition("netmask") netIP = netIPList[0].strip().encode("UTF-8") netMask = netIPList[2].partition("{")[0].strip().encode("UTF-8") - if not filter(lambda x: x, (routers, domainName, dnsIPs, iprange)): + if not any((routers, domainName, dnsIPs, iprange)): self.setError(_("empty modify options")) return False textNet = self.getTextSubnet(netIP, "", routers, domainName, @@ -16668,7 +16645,7 @@ class dncpTxt(cl_profile.dhcp, shareTxt, shareIP): namesArea = xpath.Evaluate("child::caption/child::name", xmlNode) splNameNewNode = namesArea[0].firstChild.nodeValue hostname = splNameNewNode.partition("host")[2].strip().encode("UTF-8") - if not filter(lambda x: x, (ip, mac)): + if not any((ip, mac)): self.setError(_("empty modify options")) return False textHost = self.getTextStaticIP(hostname, ip, mac) @@ -16713,18 +16690,20 @@ class dncpTxt(cl_profile.dhcp, shareTxt, shareIP): def deleteAllNetAndHosts(self): """Удаляет все сети и статические хосты из конфигурационного файла""" # IP всех сетей - delNamesNets = map(lambda x:\ -x.firstChild.nodeValue.partition("subnet")[2].partition("netmask")[0].\ -encode("UTF-8"), filter(lambda x: x.firstChild, self.getAllXMLSubnet())) + delNamesNets = [x.firstChild.nodeValue.partition("subnet")[2].\ + partition("netmask")[0].encode("UTF-8") + for x in self.getAllXMLSubnet() + if x.firstChild] # Имена всех статических хостов - delNamesHosts = map(lambda x:\ - x.firstChild.nodeValue.partition("host")[2].strip().encode("UTF-8"),\ - filter(lambda x: x.firstChild, self._getAllXMLStaticHosts())) + delNamesHosts = [x.firstChild.nodeValue.partition("host")[2].\ + strip().encode("UTF-8") + for x in self._getAllXMLStaticHosts() + if x.firstChild] # Удаление - for term in map(lambda x: self.deleteNet(x), delNamesNets): + for term in (self.deleteNet(x) for x in delNamesNets): if not term: return False - for term in map(lambda x: self.deleteStaticHost(x), delNamesHosts): + for term in (self.deleteStaticHost(x) for x in delNamesHosts): if not term: return False return True @@ -16772,10 +16751,10 @@ encode("UTF-8"), filter(lambda x: x.firstChild, self.getAllXMLSubnet())) delNodesNext.pop() delNodes = delNodesPrev + delNodesNext # Удаляем переводы строк - map(lambda x: xmlNodeBody.removeChild(x), delNodes) + [xmlNodeBody.removeChild(x) for x in delNodes] #print xmlNodeBody.toprettyxml().encode("UTF-8") # Удаляем области - for term in map(lambda x: xmlNodeBody.removeChild(x), deletesNodes): + for term in (xmlNodeBody.removeChild(x) for x in deletesNodes): if not term: self.setError(_('Can not remove static host "%s"')%hostname+\ " " + _("in config file %s")%self.nameConfigFile) @@ -16827,10 +16806,10 @@ encode("UTF-8"), filter(lambda x: x.firstChild, self.getAllXMLSubnet())) delNodesNext.pop() delNodes = delNodesPrev + delNodesNext # Удаляем переводы строк - map(lambda x: xmlNodeBody.removeChild(x), delNodes) + [xmlNodeBody.removeChild(x) for x in delNodes] #print xmlNodeBody.toprettyxml().encode("UTF-8") # Удаляем области - for term in map(lambda x: xmlNodeBody.removeChild(x), deletesNodes): + for term in (xmlNodeBody.removeChild(x) for x in deletesNodes): if not term: self.setError(_('Can not remove subnet "%s"')%net+\ " " + _("in config file %s")%self.nameConfigFile) @@ -16897,8 +16876,9 @@ class dnsTxt(cl_profile.bind,shareTxt): "child::area/child::caption/child::name", xmlNodeBody) if not namesArea: return [] - return filter(lambda x: x.firstChild and x.firstChild.nodeValue and\ - 'zone"' in x.firstChild.nodeValue, namesArea) + return [x for x in namesArea + if x.firstChild and x.firstChild.nodeValue and\ + 'zone"' in x.firstChild.nodeValue] def getXMLZoneToName(self, nameZone): """Получить XML ноду DNS зоны по ее имени""" @@ -16911,10 +16891,10 @@ class dnsTxt(cl_profile.bind,shareTxt): if not xmlZonesNames: return [] nameZoneL = nameZone.lower() - return map(lambda x: x.parentNode.parentNode, filter(lambda x:\ - nameZoneL == \ - x.firstChild.nodeValue.lower().partition('"')[2].partition('"')[0],\ - xmlZonesNames)) + return [x.parentNode.parentNode + for x in xmlZonesNames + if nameZoneL == \ + x.firstChild.nodeValue.lower().partition('"')[2].partition('"')[0]] def getAllNamesZones(self): """Получить все имена нод областей (кроме служебных)""" @@ -16934,8 +16914,8 @@ class dnsTxt(cl_profile.bind,shareTxt): continue retNodesNames.append(\ nodeZone.firstChild.nodeValue.rpartition('"')[0].partition('"')[2]) - retNodesNames = filter(lambda x: x, retNodesNames) - return map(lambda x: x.encode("UTF-8"), retNodesNames) + retNodesNames = [x for x in retNodesNames if x] + return [x.encode("UTF-8") for x in retNodesNames] def deleteZone(self, zoneName): """Удаляет зону из конфигурационного файла bind""" @@ -16980,10 +16960,10 @@ class dnsTxt(cl_profile.bind,shareTxt): delNodesNext.pop() delNodes = delNodesPrev + delNodesNext # Удаляем переводы строк - map(lambda x: xmlNodeBody.removeChild(x), delNodes) + [xmlNodeBody.removeChild(x) for x in delNodes] #print xmlNodeBody.toprettyxml().encode("UTF-8") # Удаляем области - for term in map(lambda x: xmlNodeBody.removeChild(x), deletesNodes): + for term in [xmlNodeBody.removeChild(x) for x in deletesNodes]: if not term: self.setError(_('Can not remove DNS zone "%s"')%zoneName+\ " " + _("in config file %s")%self.nameConfigFile) @@ -17057,7 +17037,7 @@ class dnsTxt(cl_profile.bind,shareTxt): if not delNode in delNodes: delNodes.append(delNode) # Удаляем переводы строк - map(lambda x: xmlNodeBody.removeChild(x), delNodes) + [xmlNodeBody.removeChild(x) for x in delNodes] #print xmlNodeBody.toprettyxml().encode("UTF-8") # Удаляем области for delNode, zoneName in deletesNodes: @@ -17241,12 +17221,11 @@ class servDns(shareLdap): Кроме SOA записи (имя домена @) """ relZonesDN = self.getRelZonesDN(zoneName) - relZoneDN = self.addDN("zoneName=%s"%zoneName,relZonesDN) + relZoneDN = self.addDN("zoneName=%s" % zoneName, relZonesDN) resSearch = self.searchLdapDN("*", relZoneDN,"relativeDomainName") if resSearch: - resSearch = filter(lambda x:\ - not x[0][1]["relativeDomainName"][0]=="@",\ - resSearch) + resSearch = [x for x in resSearch + if not x[0][1]["relativeDomainName"][0] == "@"] return resSearch def searchAllDomainNamesInLDAP(self, domainName): @@ -17268,8 +17247,8 @@ class servDns(shareLdap): """ resSearch = self.searchAllDomainNamesInLDAP(domainName) if resSearch: - resSearch=filter(lambda x: not x[0][1].has_key("cNAMERecord"),\ - resSearch) + resSearch = [x for x in resSearch + if "cNAMERecord" not in x[0][1]] return resSearch def searchCNameInLDAP(self, domainName): @@ -17279,8 +17258,8 @@ class servDns(shareLdap): """ resSearch = self.searchAllDomainNamesInLDAP(domainName) if resSearch: - resSearch=filter(lambda x: x[0][1].has_key("cNAMERecord"),\ - resSearch) + resSearch = [x for x in resSearch + if "cNAMERecord" in x[0][1]] return resSearch def searchIPinForward(self, ip): @@ -17290,9 +17269,8 @@ class servDns(shareLdap): """ resSearch = self._searchLdapDNSub(ip, self.relForwardDN, "aRecord") if resSearch: - resSearch = filter(lambda x:\ - not x[0][1]["relativeDomainName"][0]=="@",\ - resSearch) + resSearch = [x for x in resSearch + if not x[0][1]["relativeDomainName"][0] == "@"] return resSearch def searchHostsForIPinForward(self, ip): @@ -17303,7 +17281,7 @@ class servDns(shareLdap): for aRecord in foundNames: relDomainNames = aRecord[0][1]['relativeDomainName'] zoneName = aRecord[0][1]['zoneName'][0] - domainNames = map(lambda x:"%s.%s"%(x,zoneName),relDomainNames) + domainNames = ["%s.%s" % (x, zoneName) for x in relDomainNames] hostNames += domainNames return hostNames @@ -17312,12 +17290,11 @@ class servDns(shareLdap): Ищет в LDAP """ - hostDot = "%s."%host + hostDot = "%s." % host resSearch = self._searchLdapDNSub(hostDot,self.relReverseDN,"pTRRecord") if resSearch: - resSearch = filter(lambda x:\ - not x[0][1]["relativeDomainName"][0]=="@",\ - resSearch) + resSearch = [x for x in resSearch + if not x[0][1]["relativeDomainName"][0] == "@"] return resSearch def searchIPForHostInReverse(self, host): @@ -17328,7 +17305,7 @@ class servDns(shareLdap): for ptrRecord in foundIPs: lastOctIPs = ptrRecord[0][1]['relativeDomainName'] zoneName = ptrRecord[0][1]['zoneName'][0] - domainNames = map(lambda x:"%s.%s"%(x,zoneName),lastOctIPs) + domainNames = ["%s.%s" % (x, zoneName) for x in lastOctIPs] for name in domainNames: listOctRev = name.rpartition(".in-addr.arpa")[0].split(".") listOctRev.reverse() @@ -17503,15 +17480,15 @@ class servDns(shareLdap): regTime = re.compile("^\d+[smhdwSMHDW]?$") sOATimeParams = [refresh,updateRetry,expiry,minimum] # Проверка корректности значений интервалов времени - incorrectTimeValues = filter(lambda x: not regTime.search(x),\ - sOATimeParams) + incorrectTimeValues = [x for x in sOATimeParams + if not regTime.search(x)] if incorrectTimeValues: self.printERROR(_("Values %s incorrect in SOA-record")\ %", ".join(incorrectTimeValues)) return False # Добавление точки если необходимо в каждое имя DNS сервера # Имена авторитативных DNS серверов для зоны - namesServersDot = map(lambda x: addDot(x), namesServers) + namesServersDot = [addDot(x) for x in namesServers] # Получение текста sOA записи sOARecord = " ".join([nameServerDot,emailAddrDot,serialNumber] +\ sOATimeParams) @@ -17553,9 +17530,9 @@ class servDns(shareLdap): if ip: zoneDomainEntry += [('aRecord',ip)] if mxList: - mxListDot = map(lambda x: addDot(x), mxList) - mxValues = map(lambda x: "%s %s" %(x*10+10, mxListDot[x]),\ - range(len(mxListDot))) + mxListDot = [addDot(x) for x in mxList] + mxValues = ["%s %s" % (x * 10 + 10, mxListDot[x]) + for x in range(len(mxListDot))] zoneDomainEntry += [('mXRecord', mxValues)] if not self.addEntry(zoneDomainDN, zoneDomainEntry, zoneDomainErrorMessage): @@ -17588,14 +17565,14 @@ incompatible with option "--ip" (PTR-record)')) return False # Флаг MX - записи flagDeleteMX = False - if options.has_key('mx'): + if 'mx' in options: flagDeleteMX = True # Удаляет лишние точки в названии - delDot = lambda y: ".".join(filter(lambda x: x, y.split("."))) + delDot = lambda y: ".".join(x for x in y.split(".") if x) domainName = "" ip = "" typeRec = "" - if options.has_key('host'): + if 'host' in options: # Доменное имя (имя включающее домен) typeRec = "a" domainName = delDot(options['host'].lower()) @@ -17604,7 +17581,7 @@ incompatible with option "--ip" (PTR-record)')) if not zoneName: self.printERROR(_("Domain name %s incorrectly")%domainName) return False - elif options.has_key('ip'): + elif 'ip' in options: if flagDeleteMX: self.printERROR(_('Command line option "--mx" (MX-record) \ incompatible with option "--ip" (PTR-record)')) @@ -17631,7 +17608,7 @@ incompatible with option "--ip" (PTR-record)')) if flagDeleteMX: # Удаляем MX запись из A записи if foundDomain: - if not foundDomain[0][0][1].has_key('mXRecord'): + if 'mXRecord' not in foundDomain[0][0][1]: self.printERROR(\ _("Can not found MX-records in A-record %s"%domainName)) return False @@ -17718,10 +17695,10 @@ incompatible with option "--ip" (PTR-record)')) if not self.isServiceSetup("dns"): return False # Удаляет лишние точки в названии - delDot = lambda y: ".".join(filter(lambda x: x, y.split("."))) + delDot = lambda y: ".".join(x for x in y.split(".") if x) # Имя зоны zoneName = "" - if options.has_key('n'): + if 'n' in options: zoneName = delDot(options["n"].lower()) if not zoneName: self.printERROR(_('Incorrect zone name')) @@ -17748,7 +17725,7 @@ incompatible with option "--ip" (PTR-record)')) if not zoneName: self.printERROR(_("Not enough command line option %s")%"-n") return False - if options.has_key('ip') or options.has_key('mx'): + if 'ip' in options or 'mx' in options: # Получение данных зоны из LDAP zoneData = self.searchAllDomainNamesInLDAP("@.%s"%zoneName) if not zoneData: @@ -17756,13 +17733,13 @@ incompatible with option "--ip" (PTR-record)')) %zoneName) return False # Удаление A записи - if options.has_key('ip'): - if not zoneData[0][0][1].has_key('aRecord'): + if 'ip' in options: + if 'aRecord' not in zoneData[0][0][1]: self.printERROR(_("Can not found A-records in zone %s")\ %zoneName) return False - if options.has_key('mx'): - if not zoneData[0][0][1].has_key('mXRecord'): + if 'mx' in options: + if 'mXRecord' not in zoneData[0][0][1]: self.printERROR(\ _("Can not found MX-records in zone %s")\ %zoneName) @@ -17778,8 +17755,8 @@ incompatible with option "--ip" (PTR-record)')) self.printSUCCESS(_("Deleted A-records for zone %s")%zoneName) ret = True # Удаление MX записей - if options.has_key('mx'): - if not zoneData[0][0][1].has_key('mXRecord'): + if 'mx' in options: + if 'mXRecord' not in zoneData[0][0][1]: self.printERROR(_("Can not found MX-records in zone %s")\ %zoneName) return False @@ -17822,19 +17799,18 @@ incompatible with option "--ip" (PTR-record)')) %", ".join(["master","slave"])) return False - if not set(minKeys)<=set(optKeys): + if not set(minKeys) <= set(optKeys): notFoundKeys = list(set(minKeys)-set(optKeys)) - notFoundKeys = map(lambda x: len(x)>1 and '"--%s"'%x or '"-%s"'%x,\ - notFoundKeys) + notFoundKeys (len(x) > 1 and '"--%s"' % x or '"-%s"' % x for x in notFoundKeys) self.printERROR(_("Not enough command line options: %s")\ %", ".join(notFoundKeys)) return False # Удаляет лишние точки в названии - delDot = lambda y: ".".join(filter(lambda x: x, y.split("."))) + delDot = lambda y: ".".join(x for x in y.split(".") if x) # Имя зоны zoneName = "" forwardZone = True - if options.has_key('n'): + if 'n' in options: zoneName = delDot(options["n"].lower()) if not zoneName: self.printERROR(_('Incorrect zone name')) @@ -17851,12 +17827,12 @@ incompatible with option "--ip" (PTR-record)')) else: # Проверка на недопустимые ключи для обратной зоны # ip зоны для обратной зоны недопустим - if options.has_key('ip'): + if 'ip' in options: self.printERROR(_('Command line option "--ip" \ incompatible with reverse DNS zone %s')%zoneName) return False # MX записи для обратной зоны недопустимы - if options.has_key('mx'): + if 'mx' in options: self.printERROR(_('Command line option "--mx" \ incompatible with reverse DNS zone %s')%zoneName) return False @@ -17887,7 +17863,7 @@ incompatible with reverse DNS zone %s')%zoneName) return False # ip зоны zoneIP = "" - if options.has_key('ip'): + if 'ip' in options: zoneIP = options["ip"] if "," in zoneIP or \ not self.isCorrectStringNet(zoneIP, False): @@ -17895,16 +17871,16 @@ incompatible with reverse DNS zone %s')%zoneName) return False # Почтовые серверы для зоны zoneListMX = [] - if options.has_key('mx'): - zoneListMX = map(lambda x: delDot(x.lower()),\ - options['mx'].split(",")) + if 'mx' in options: + zoneListMX = [delDot(x.lower()) for x + in options['mx'].split(",")] zoneListMX = self.unicList(zoneListMX) if not self.checkMXDomains(zoneListMX): return False # Все авторитативные сервера зоны, в случае slаve зоны # ip авторитативных серверов хранения зоны namesServers = [] - if options.has_key('servers'): + if 'servers' in options: namesServers = options['servers'].split(",") # Проверка на ip if not flagZoneMaster: @@ -17935,7 +17911,7 @@ incompatible with reverse DNS zone %s')%zoneName) warningsMX = [] # Авторитативный сервер nameServer = "" - if options.has_key('server'): + if 'server' in options: nameServer = delDot(options["server"].lower()) if self.isCorrectStringNet(nameServer, False): self.printERROR(_('Incorrect autoritative server')) @@ -17959,7 +17935,7 @@ incompatible with reverse DNS zone %s')%zoneName) if nameServer == zoneName or nsZoneName == zoneName or\ (self.searchZoneInLDAP(nsZoneName) and\ not self.searchDomainNameInLDAP(nameServer)): - if not options.has_key('ipserver'): + if 'ipserver' not in options: self.printERROR(_('Not found A-record for "%s" \ (master server DNS)')%nameServer) self.printERROR(_('Not enough command line option \ @@ -17977,7 +17953,7 @@ the primary authoritative server for the zone")) self.printERROR(_("IP address %s incorrectly")%ipserver) return False else: - if options.has_key('ipserver'): + if 'ipserver' in options: if self.searchZoneInLDAP(nsZoneName) and\ self.searchDomainNameInLDAP(nameServer): self.printERROR(_('Command line option "--ipserver" \ @@ -17990,7 +17966,7 @@ this DNS server')%nameServer) # Почтовый адрес администратора зоны # по умолчанию email = "%s@%s"%("root",zoneName) - if options.has_key('email'): + if 'email' in options: email = options['email'] # refresh - интервал времени для обновления зоны # update - интервал времени после неудачного обновления зоны @@ -18003,7 +17979,7 @@ this DNS server')%nameServer) for nameOpt in zoneTimeIntervals.keys(): valueOpt = zoneTimeIntervals[nameOpt] locals()[nameOpt] = valueOpt - if options.has_key(nameOpt): + if nameOpt in options: valueOpt = options[nameOpt] locals()[nameOpt] = valueOpt.upper() if not self.checkTimeValue(locals()[nameOpt]): @@ -18074,8 +18050,7 @@ this DNS server')%nameServer) foundReverseDomain[0][0][1]['relativeDomainName'][0] pTRRecord = foundReverseDomain[0][0][1]['pTRRecord'][0] # Удаляет лишние точки в названии - delDot = lambda y: ".".join(filter(lambda x: x,\ - y.split("."))) + delDot = lambda y: ".".join(x for x in y.split(".") if x) reverseHost = delDot(pTRRecord) listOctRev = \ zoneName.rpartition(".in-addr.arpa")[0].split(".") @@ -18099,8 +18074,7 @@ this DNS server')%nameServer) notCmdKey = list(set(optKeys) - set(minKeys)) if notCmdKey: # Добавляем кавычки и -- - addQ = lambda y: map(lambda x:\ - len(x)>1 and '"--%s"'%x or '"-%s"'%x, y) + addQ = lambda y: [len(x) > 1 and '"--%s"' % x or '"-%s"' % x, y] self.printERROR(_("Incorrect command line options %s")\ %", ".join(addQ(notCmdKey))) return False @@ -18269,10 +18243,10 @@ this DNS server')%nameServer) if not self.isServiceSetup("dns"): return False # Удаляет лишние точки в названии - delDot = lambda y: ".".join(filter(lambda x: x, y.split("."))) + delDot = lambda y: ".".join(x for x in y.split(".") if x) # Имя зоны zoneName = "" - if options.has_key('n'): + if 'n' in options: zoneName = delDot(options["n"].lower()) if not zoneName: self.printERROR(_('Incorrect zone name')) @@ -18304,23 +18278,21 @@ this DNS server')%nameServer) self.printERROR(_("Can not found master zone %s in LDAP")%zoneName) return False # Проверка на mx совместно с mxmod - if options.has_key('mx') and options.has_key('mxmod'): + if 'mx' in options and 'mxmod' in options: self.printERROR('Command line option "-mx" is incompatible \ with option "--mxmod"') return False # MX серверы mxServers = [] - if options.has_key('mx'): - mxServers=map(lambda x: delDot(x.lower()), - options['mx'].split(",")) + if 'mx' in options: + mxServers = [delDot(x.lower()) for x in options['mx'].split(",")] mxServers = self.unicList(mxServers) # Переименование mx записи # modMxServers[0] - cтарая запись # modMxServers[1] - новая запись modMxServers = [] - if options.has_key('mxmod'): - modMxServers=map(lambda x: delDot(x.lower()),\ - options['mxmod'].split(",")) + if 'mxmod' in options: + modMxServers = [delDot(x.lower()) for x in options['mxmod'].split(",")] modMxServers = self.unicList(modMxServers) if len(modMxServers)!=2: self.printERROR(_('Incorrect command line option "--mxmod"')) @@ -18329,7 +18301,7 @@ with option "--mxmod"') return False # ip зоны zoneIP = "" - if options.has_key('ip'): + if 'ip' in options: zoneIP = options["ip"] if "," in zoneIP or \ not self.isCorrectStringNet(zoneIP, False): @@ -18342,19 +18314,19 @@ with option "--mxmod"') return False soaRecord = zoneData[0][0][1]['sOARecord'][0] nSRecords = zoneData[0][0][1]['nSRecord'] - soaData = map(lambda x: delDot(x), soaRecord.split(" ")) + soaData = [delDot(x) for x in soaRecord.split(" ")] if len(soaData)!=7: self.printERROR(_("Incorrect SOA-record in DNS zone %s")%zoneName) return False # Все авторитативные сервера зоны, в случае slаve зоны - namesServers = map(lambda x: delDot(x), nSRecords) - oldNamesServers = map(lambda x: delDot(x), nSRecords) + namesServers = [delDot(x) for x in nSRecords] + oldNamesServers = [delDot(x) for x in nSRecords] # Изменяем ip зоны if zoneIP: addDot = lambda x: (len(x)>0 and x[-1]!="." and "%s."%x) or x relZoneDN = self.getRelZoneDN(zoneName) modAttrs = [] - if zoneData[0][0][1].has_key('aRecord'): + if 'aRecord' in zoneData[0][0][1]: modAttrs =[(ldap.MOD_DELETE, 'aRecord', None)] modAttrs.append((ldap.MOD_ADD, 'aRecord', zoneIP)) DN = self.addDN("relativeDomainName=@", relZoneDN) @@ -18368,7 +18340,7 @@ with option "--mxmod"') # Изменяем MX записи if mxServers or modMxServers: flagFoundMX = False - if zoneData[0][0][1].has_key('mXRecord'): + if 'mXRecord' in zoneData[0][0][1]: flagFoundMX = True # Изменяем почтовый хост на другой почтовый хост if modMxServers: @@ -18377,9 +18349,8 @@ with option "--mxmod"') %zoneName) return False # Находим нужную запись - foundMxServers = map(lambda x: len(x.split(" "))==1\ - and delDot(x) or delDot(x.split(" ")[1]),\ - zoneData[0][0][1]['mXRecord']) + foundMxServer = [len(x.split(" ")) == 1 and delDot(x) or delDot(x.split(" ")[1]) + for x in zoneData[0][0][1]['mXRecord']] oldMxHost = modMxServers[0] newMxHost = modMxServers[1] if not oldMxHost in foundMxServers: @@ -18413,7 +18384,7 @@ with option "--mxmod"') if not self.modMXRecord("@", zoneName, zoneName, flagFoundMX, mxServers): return False - if options.has_key('servers'): + if 'servers' in options: namesServers = options['servers'].split(",") flagErrorNs = False for ns in namesServers: @@ -18428,7 +18399,7 @@ with option "--mxmod"') return False # Авторитативный сервер nameServer = soaData[0] - if options.has_key('server'): + if 'server' in options: nameServer = delDot(options["server"].lower()) if self.isCorrectStringNet(nameServer, False): self.printERROR(_('Incorrect autoritative server')) @@ -18460,7 +18431,7 @@ with option "--mxmod"') splEmail = soaData[1].partition(".") email = "%s@%s"%(splEmail[0], delDot(splEmail[2])) oldEmail = email - if options.has_key('email'): + if 'email' in options: email = options['email'] # Серийный номер зоны serialNumber = str(ctypes.c_uint32(int(soaData[2])).value + 1) @@ -18475,7 +18446,7 @@ with option "--mxmod"') for nameOpt in zoneTimeIntervals.keys(): valueOpt = zoneTimeIntervals[nameOpt] locals()[nameOpt] = valueOpt - if options.has_key(nameOpt): + if nameOpt in options: valueOpt = options[nameOpt] locals()[nameOpt] = valueOpt.upper() if not self.checkTimeValue(locals()[nameOpt]): @@ -18496,13 +18467,13 @@ with option "--mxmod"') sOARecord = " ".join(sOAList) relZoneDN = self.getRelZoneDN(zoneName) modAttrs = [(ldap.MOD_REPLACE, 'sOARecord', sOARecord)] - if options.has_key('server') or options.has_key('servers'): + if 'server' in options or 'servers' in options: # Добавляем мастер сервер в имена авторитативаных серверов if not nameServer in namesServers: namesServers.insert(0, nameServer) modAttrs.append((ldap.MOD_DELETE, 'nSRecord', None)) modAttrs.append((ldap.MOD_ADD, 'nSRecord',\ - map(lambda x: addDot(x), namesServers))) + [addDot(x) for x in namesServers])) DN = self.addDN("relativeDomainName=@", relZoneDN) if not self.modAttrsDN(DN, modAttrs): self.printERROR(_("Can not modify new SOA-record for zone %s \ @@ -18542,15 +18513,15 @@ in LDAP")%zoneName) if "f" in options.keys(): checkDHCPConfig = False # Проверка на имя хоста вместе с ip - if options.has_key('ip') and options.has_key('host'): + if 'ip' in options and 'host' in options: self.printERROR('Command line option "--host" is incompatible \ with option "--ip"') return False # Удаляет лишние точки в названии - delDot = lambda y: ".".join(filter(lambda x: x, y.split("."))) + delDot = lambda y: ".".join(x for x in y.split(".") if x) # модификация другой записи A -> PTR, PTR -> A modOther = True - if options.has_key('automod'): + if 'automod' in options: autoMod = options['automod'] if autoMod == "on": modOther = True @@ -18562,7 +18533,7 @@ incorrect, use "--automod on" or "--automod off"')%autoMod) return False # По умолчанию прямой тип записи typeRec = "a" - if options.has_key('t'): + if 't' in options: # Тип модифицируемой записи typeRec = options['t'].lower() supportTypes = ("a","ptr","cname","mx") @@ -18572,12 +18543,12 @@ incorrect, use "--automod on" or "--automod off"')%autoMod) %", ".join(supportTypes)) return False # Проверка на mx совместно с mxmod - if options.has_key('mx') and options.has_key('mxmod'): + if 'mx' in options and 'mxmod' in options: self.printERROR('Command line option "-mx" is incompatible \ with option "--mxmod"') return False # Добавляем кавычки и -- - addQ = lambda y: map(lambda x: len(x)>1 and '"--%s"'%x or '"-%s"'%x, y) + addQ = lambda y: [len(x) > 1 and '"--%s"' % x or '"-%s"' % x for x in y] # Ключи опций optKeys = options.keys() # Обязательные опции @@ -18636,7 +18607,7 @@ with option "--mxmod"') %addQ([key])[0]) self.printWARNING(_('Valid values are the options %s')\ %addQ([key])[0] + " " + '(%s)'\ - % (" "+_("or")+" ").join(map(lambda x: '"%s"'%x, value))) + % (" "+_("or")+" ").join(('"%s"' % x for x in value))) return False # Проверка лишних опций unnecessaryOpt = list(set(optKeys)-set(requiredOpt+optionalOpt.keys())) @@ -18646,7 +18617,7 @@ with option "--mxmod"') return False mxServers = [] - if options.has_key('mx'): + if 'mx' in options: # Оключаем модификацию обратной зоны modOther = False # Почтовые серверы для доменного имени @@ -18658,14 +18629,13 @@ incompatible with PTR-record (option "-t")')) self.printERROR(_('Command line option "--mx" \ incompatible with CNAME-record (option "-t")')) return False - mxServers=map(lambda x: delDot(x.lower()), - options['mx'].split(",")) + mxServers = [delDot(x.lower()) for x in options['mx'].split(",")] mxServers = self.unicList(mxServers) # Переименование mx записи # modMxServers[0] - cтарая запись # modMxServers[1] - новая запись modMxServers = [] - if options.has_key('mxmod'): + if 'mxmod' in options: # Отключаем модификацию обратной зоны modOther = False # Почтовые cерверы для доменного имени @@ -18677,8 +18647,7 @@ incompatible with PTR-record (option "-t")')) self.printERROR(_('Command line option "--mxmod" \ incompatible with CNAME-record (option "-t")')) return False - modMxServers=map(lambda x: delDot(x.lower()),\ - options['mxmod'].split(",")) + modMxServers = [delDot(x.lower()) for x in options['mxmod'].split(",")] modMxServers = self.unicList(modMxServers) if len(modMxServers)!=2: self.printERROR(_('Incorrect command line option "--mxmod"')) @@ -18686,7 +18655,7 @@ incompatible with CNAME-record (option "-t")')) self.printWARNING("--mxmod old.mail.host,new.mail.host") return False cnameServer = "" - if options.has_key('cname'): + if 'cname' in options: # Оключаем модификацию обратной зоны modOther = False # Доменное имя (имя включающее домен) @@ -18701,7 +18670,7 @@ incompatible with CNAME-record (option "-t")')) newZoneName = "" # Новая запись является CNAME foundNewCnameRecord = False - if options.has_key('host'): + if 'host' in options: # Доменное имя (имя включающее домен) newDomainName = delDot(options['host'].lower()) # Имя хоста, имя зоны @@ -18768,7 +18737,7 @@ incompatible with CNAME-record (option "-t")')) newIP = "" newZoneNameIP = "" newHostNameIP = "" - if options.has_key('ip'): + if 'ip' in options: if typeRec == "cname": self.printERROR('Command line option "-t cname" \ is incompatible with option "--ip"') @@ -19070,7 +19039,7 @@ is incompatible with option "--ip"') %domainName) return False flagFoundMX = False - if foundMain[0][0][1].has_key('mXRecord'): + if 'mXRecord' in foundMain[0][0][1]: flagFoundMX = True # Изменяем почтовый хост на другой почтовый хост if modMxServers: @@ -19080,9 +19049,9 @@ is incompatible with option "--ip"') %domainName) return False # Находим нужную запись - foundMxServers = map(lambda x: len(x.split(" "))==1\ - and delDot(x) or delDot(x.split(" ")[1]),\ - foundMain[0][0][1]['mXRecord']) + foundMxServers = [len(x.split(" ")) == 1\ + and delDot(x) or delDot(x.split(" ")[1]) + for x in foundMain[0][0][1]['mXRecord']] oldMxHost = modMxServers[0] newMxHost = modMxServers[1] if not oldMxHost in foundMxServers: @@ -19343,7 +19312,7 @@ is incompatible with option "--ip"') %domainName) return False flagFoundMX = False - if foundMain[0][0][1].has_key('mXRecord'): + if 'mXRecord' in foundMain[0][0][1]: flagFoundMX = True # Изменяем почтовый хост на другой почтовый хост if modMxServers: @@ -19353,9 +19322,9 @@ is incompatible with option "--ip"') %domainName) return False # Находим нужную запись - foundMxServers = map(lambda x: len(x.split(" "))==1\ - and delDot(x) or delDot(x.split(" ")[1]),\ - foundMain[0][0][1]['mXRecord']) + foundMxServers = [len(x.split(" ")) == 1\ + and delDot(x) or delDot(x.split(" ")[1]) + for x in foundMain[0][0][1]['mXRecord']] oldMxHost = modMxServers[0] newMxHost = modMxServers[1] if not oldMxHost in foundMxServers: @@ -19485,7 +19454,7 @@ is incompatible with option "--ip"') checkDHCPConfig = False # По умолчанию прямой тип записи typeRec = "a" - if options.has_key('t'): + if 't' in options: # Тип добавлямой записи typeRec = options['t'].lower() supportTypes = ("a","ptr","cname") @@ -19500,14 +19469,13 @@ is incompatible with option "--ip"') minKeys = ["host","ip"] if not set(minKeys)<=set(optKeys): notFoundKeys = list(set(minKeys)-set(optKeys)) - notFoundKeys = map(lambda x: len(x)>1 and '"--%s"'%x or '"-%s"'%x,\ - notFoundKeys) + notFoundKeys = [len(x) > 1 and '"--%s"' % x or '"-%s"' % x for x in notFoundKeys] self.printERROR(_("Not enough command line options: %s")\ %", ".join(notFoundKeys)) return False # Флаг автоматического создания PTR записи createPtr = True - if options.has_key('autoptr'): + if 'autoptr' in options: if typeRec == "ptr": self.printERROR(_('Command line option "--autoptr" \ incompatible with type DNS record PTR (option "-t")')) @@ -19526,11 +19494,11 @@ incompatible with type DNS record CNAME (option "-t")')) incorrect, use "--autoptr on" or "--autoptr off"')%autoPtr) return False # Удаляет лишние точки в названии - delDot = lambda y: ".".join(filter(lambda x: x, y.split("."))) + delDot = lambda y: ".".join(x for x in y.split(".") if x) domainName = "" hostName = "" zoneName = "" - if options.has_key('host'): + if 'host' in options: # Доменное имя (имя включающее домен) domainName = delDot(options['host'].lower()) # Имя хоста, имя зоны @@ -19541,12 +19509,12 @@ incorrect, use "--autoptr on" or "--autoptr off"')%autoPtr) cnDomainName = "" cnHostName = "" cnZoneName = "" - if options.has_key('cname'): - if options.has_key('ip'): + if 'cname' in options: + if 'ip' in options: self.printERROR(_('Command line option "--ip" incompatible \ with type DNS record CNAME (option "-t")')) return False - if options.has_key('mx'): + if 'mx' in options: self.printERROR(_('Command line option "--mx" incompatible \ with type DNS record CNAME (option "-t")')) return False @@ -19558,7 +19526,7 @@ with type DNS record CNAME (option "-t")')) self.printERROR(_("Domain name %s incorrectly")%cnDomainName) return False ip = "" - if options.has_key('ip'): + if 'ip' in options: # ip адрес ip = options['ip'] if "," in ip or not self.isCorrectStringNet(ip, False): @@ -19573,14 +19541,13 @@ with type DNS record CNAME (option "-t")')) if not servDhcpObj.isCorrectStaticIP(ip): return False mxServers = [] - if options.has_key('mx'): + if 'mx' in options: # Почтовые серверы для доменного имени if typeRec == "ptr": self.printERROR(_('Command line option "--mx" incompatible \ with type DNS record PTR (option "-t")')) return False - mxServers = map(lambda x: delDot(x.lower()),\ - options['mx'].split(",")) + mxServers = [delDot(x.lower()) for x in options['mx'].split(",")] mxServers = self.unicList(mxServers) ret = False # Флаг создания A записи @@ -19673,7 +19640,7 @@ with type DNS record PTR (option "-t")')) def checkTimeValue(self, timeValue): """Проверяет корректность переменной времени""" # разбиваем строку на символы - charList = map(lambda x: timeValue[x:x+1], range(len(timeValue))) + charList = [timeValue[x:x + 1] for x in range(len(timeValue))] if not charList: return False # Проверяем последний символ на число @@ -19699,12 +19666,10 @@ with type DNS record PTR (option "-t")')) (зона для доменного имени существует, доменного имени в ней нет) """ # Имена серверов которые могут находится в существующих зонах - serversInZones = filter(lambda x:\ - self.searchZoneInLDAP(x.partition(".")[2]),\ - namesServers) - notFoundServers = filter(lambda x:\ - not self.searchDomainNameInLDAP(x),\ - serversInZones) + serversInZones = [x for x in namesServers + if self.searchZoneInLDAP(x.partition(".")[2])] + notFoundServers = [x for x in serversInZones + if not self.searchDomainNameInLDAP(x)] return notFoundServers @@ -19743,14 +19708,14 @@ with type DNS record PTR (option "-t")')) # Проверка существования A записей для MX хостов if not self.checkMXDomains(namesMailServers): return False - namesMailServersDot = map(lambda x: addDot(x), namesMailServers) + namesMailServersDot = [addDot(x) for x in namesMailServers] domainEntry = [('objectclass', ['top','dNSZone']), ('relativeDomainName', [hostName]), ('dNSClass', ['IN']), ('zoneName',[zoneName]), ('aRecord',[ipAddrOrHost])] - mxValues=map(lambda x: "%s %s" %(x*10+10, namesMailServersDot[x]),\ - range(len(namesMailServersDot))) + mxValues= ["%s %s" % (x * 10 + 10, namesMailServersDot[x]) + for x in range(len(namesMailServersDot))] if mxValues: # Добавляем MX записи domainEntry.append(('mXRecord', mxValues)) @@ -19835,8 +19800,8 @@ in LDAP")%zoneName) self.clVars должен быть определен """ - print _("Enter the allowed ip addresses and network for %s service")\ - %"DNS" + " (" + _("comma or space delimited") + ")" + print(_("Enter the allowed ip addresses and network for %s service")\ + %"DNS" + " (" + _("comma or space delimited") + ")") strPrompt = _("allow networks: ") netAllow = self.clVars.Get("sr_dns_net_allow") strNetAllow = "" @@ -19854,12 +19819,11 @@ in LDAP")%zoneName) """Проверка ключа sdb-ldap bind""" pathBind = "/var/db/pkg/net-dns" if os.path.exists(pathBind): - subPathsBind = filter(lambda x: re.search("bind-\d",x),\ - os.listdir(pathBind)) + subPathsBind = [x for x in os.listdir(pathBind) if re.search("bind-\d", x)] if subPathsBind: - pathsUSE = (os.path.join(pathBind,subPathsBind[0],"IUSE"), - os.path.join(pathBind,subPathsBind[0],"USE")) - if filter(lambda x: not os.path.exists(x), pathsUSE): + pathsUSE = (os.path.join(pathBind, subPathsBind[0], "IUSE"), + os.path.join(pathBind, subPathsBind[0], "USE")) + if [x for x in pathsUSE if not os.path.exists(x)]: return False for pathUSE in pathsUSE: flagFound = False @@ -19886,7 +19850,7 @@ net-dns/bind version>=9.6.1')) return False # Принудительная установка forceOptions = False - if options.has_key("f"): + if "f" in options: forceOptions = True # Создаем объект переменных self.createClVars() @@ -19916,13 +19880,13 @@ net-dns/bind version>=9.6.1')) _("input 'yes'") +", "+ _("if not 'no'") if not self.dialogYesNo(messDialog): return True - if options.has_key("a"): + if "a" in options: # Получаем от пользователя доверительные сети allowNet = self.getAllowNet() if not allowNet: return False else: - if options.has_key("a"): + if "a" in options: # Получаем от пользователя доверительные сети allowNet = self.getAllowNet() if not allowNet: @@ -20004,7 +19968,7 @@ net-dns/bind version>=9.6.1')) if not self.ldapObj.getError(): self.ldapObj.ldapAdd(baseLdif) if self.ldapObj.getError(): - print _("LDAP Error") + ": " + self.ldapObj.getError().strip() + print(_("LDAP Error") + ": " + self.ldapObj.getError().strip()) return False # Записываем данные администратора сервиса Proxy ldapParser = iniLdapParser() @@ -20054,10 +20018,8 @@ class servDhcp(shareLdap, shareIP): # Проверка на наличие всех нужных опций if not set(minKeys)<=set(optKeys): notFoundKeys = list(set(minKeys)-set(optKeys)) - notFoundKeys = map(lambda x: len(x)>1 and '"--%s"'%x or '"-%s"'%x,\ - notFoundKeys) - self.printERROR(_("Not enough command line options: %s")\ - %", ".join(notFoundKeys)) + notFoundKeys = [len(x) > 1 and '"--%s"' % x or '"-%s"' % x for x in notFoundKeys] + self.printERROR(_("Not enough command line options: %s") % ", ".join(notFoundKeys)) return False # имя хоста hostname = options["host"] @@ -20127,25 +20089,25 @@ class servDhcp(shareLdap, shareIP): for net, data in dataNets: if netNoMask == net: notFoundOpts = [] - if data.has_key("range"): - ranges = filter(lambda x: x.strip(), data["range"]) + if "range" in data: + ranges = [x for x in data["range"] if x.strip()] if not ranges: notFoundOpts.append(("range", "--range ")) - if data.has_key("optiondomain-name-servers"): + if "optiondomain-name-servers" in data: dnsIPs = data["optiondomain-name-servers"][0].split(",") if not dnsIPs: notFoundOpts.append(("option domain-name-servers", "--dnsip ")) - if data.has_key("optiondomain-name"): - domainNames = map(lambda x: x.strip().replace('"',''),\ - data["optiondomain-name"]) + if "optiondomain-name" in data: + domainNames = [x.strip().replace('"', '') + for x in data["optiondomain-name"]] if not domainNames: notFoundOpts.append(("option domain-name", "--dnames ")) if notFoundOpts: - optionsPr = map(lambda x: "'%s'"%x[0], notFoundOpts) - optionsCmdPr = map(lambda x: x[1], notFoundOpts) + optionsPr = ["'%s'" % x[0] for x in notFoundOpts] + optionsCmdPr = [x[1] for x in notFoundOpts] self.printERROR(_("Can not create DNS zone %s") %net) self.printERROR(\ _('Can not found %s')%",".join(optionsPr) + " "+\ @@ -20190,9 +20152,9 @@ class servDhcp(shareLdap, shareIP): ipNumb = self.getNumberIP(ip) domainNames = [] if isRange(ipNumb, minNumber, maxNumber): - if data.has_key("optiondomain-name"): - domainNames = map(lambda x: x.strip().replace('"',''),\ - data["optiondomain-name"]) + if "optiondomain-name" in data: + domainNames = [x.strip().replace('"','') + for x in data["optiondomain-name"]] break else: self.printERROR(\ @@ -20236,11 +20198,10 @@ class servDhcp(shareLdap, shareIP): minNumber, maxNumber = self.getMinAndMaxIpNumb(net) osNets = self.clVars.Get("os_net_allow") serverNets = osNets.split(',') - dataMinMaxIP = map(lambda x: self.getMinAndMaxIpNumb(x), serverNets) + dataMinMaxIP = [self.getMinAndMaxIpNumb(x) for x in serverNets] # Проверка на попадание в диапазон сети isRange = lambda n, minN, maxN: minN<=n<=maxN - if filter(lambda x: isRange(minNumber,x[0],x[1]) and\ - isRange(maxNumber,x[0],x[1]), dataMinMaxIP): + if [x for x in dataMinMaxIP if isRange(minNumber, x[0], x[1]) and isRange(maxNumber, x[0], x[1])]: return True self.printERROR("Can not found network %s in network interfaces: \ eth0, eth1, ... etc."%net) @@ -20281,7 +20242,7 @@ eth0, eth1, ... etc."%net) _("in config file %s") %dhcpObj.nameConfigFile) return False ip = "" - if options.has_key("ip"): + if "ip" in options: # ip адрес хоста ip = options["ip"] # проверка правильности ip @@ -20302,7 +20263,7 @@ eth0, eth1, ... etc."%net) if not self.modifyDNSHostIP(fullHostName, ip): return False mac = "" - if options.has_key("mac"): + if "mac" in options: # mac адрес хоста mac = options["mac"] if mac: @@ -20351,7 +20312,7 @@ eth0, eth1, ... etc."%net) xmlNodesNet = dhcpObj.getXMLNet(network) # ip роутера router = "" - if options.has_key("router"): + if "router" in options: router = options["router"] # Проверка коректности ip роутера if "," in router or not self.isCorrectStringNet(router, False): @@ -20361,13 +20322,13 @@ eth0, eth1, ... etc."%net) self.printERROR(_("IP address %s incorrectly")%router) return False domainNames = [] - if options.has_key("dnames"): + if "dnames" in options: # доменные имена для поиска - domainNames = map(lambda x: x.lower(), options["dnames"].split(",")) + domainNames = [x.lower() for x in options["dnames"].split(",")] domainNames = self.unicList(domainNames) # проверка доменных имен на ip - incorrectDomains = filter(lambda x:\ - self.isCorrectStringNet(x, False), domainNames) + incorrectDomains = [x for x in domainNames + if self.isCorrectStringNet(x, False)] if incorrectDomains: self.printERROR(_('Incorrect command line option "--dnames"')) self.printWARNING(_("Example") + ":") @@ -20375,7 +20336,7 @@ eth0, eth1, ... etc."%net) return False dhcpObj = dncpTxt() ranges = [] - if options.has_key("range"): + if "range" in options: # Диапазон динамических ip ranges = self.isCorrectIPRangeListAndSort(net, options["range"].split(",")) @@ -20393,7 +20354,7 @@ eth0, eth1, ... etc."%net) return False dnsIP = "" # ip адреса dns серверов - if options.has_key("dnsip"): + if "dnsip" in options: dnsIP = options["dnsip"] # проверка правильности ip if not self.isCorrectStringNet(dnsIP, False) or\ @@ -20423,9 +20384,8 @@ eth0, eth1, ... etc."%net) hostname = self.servDnsObj.clVars.Get("os_net_hostname") if hostname: zone = oldDomainNames[0] - fullServerDNSName = "%s.%s"%(hostname,zone) - if not filter(lambda x: fullServerDNSName==x[0],\ - moveRecords): + fullServerDNSName = "%s.%s" % (hostname,zone) + if not [x for x in moveRecords if fullServerDNSName == x[0]]: foundServ = self.servDnsObj.searchDomainNameInLDAP(\ fullServerDNSName) if foundServ: @@ -20470,8 +20430,8 @@ eth0, eth1, ... etc."%net) # Проверка на наличие всех нужных опций if not set(minKeys)<=set(optKeys): notFoundKeys = list(set(minKeys)-set(optKeys)) - notFoundKeys = map(lambda x: len(x)>1 and '"--%s"'%x or '"-%s"'%x,\ - notFoundKeys) + notFoundKeys = [len(x) > 1 and '"--%s"' % x or '"-%s"' % x + for x in notFoundKeys] self.printERROR(_("Not enough command line options: %s")\ %", ".join(notFoundKeys)) return False @@ -20490,7 +20450,7 @@ eth0, eth1, ... etc."%net) # Находим ip хоста dataHosts = dhcpObj.getDataInAllHost() for host, data in dataHosts: - if hostname == host and data.has_key("fixed-address"): + if hostname == host and "fixed-address" in data: if data["fixed-address"]: ip = data["fixed-address"][0] break @@ -20518,8 +20478,7 @@ eth0, eth1, ... etc."%net) self.printERROR(_("Can not found networks in config file %s")\ %dhcpObj.nameConfigFile) return False - getPar = lambda opt, data: map(lambda x: opt in x[1].keys() and\ - (x[0],x[1][opt]) or (), data) + getPar = lambda opt, data: [opt in x[1].keys() and (x[0], x[1][opt]) or () for x in data] nets = getPar('mask', dataNets) if not nets: self.printERROR(\ @@ -20554,8 +20513,7 @@ eth0, eth1, ... etc."%net) # Проверка на наличие всех нужных опций if not set(minKeys)<=set(optKeys): notFoundKeys = list(set(minKeys)-set(optKeys)) - notFoundKeys = map(lambda x: len(x)>1 and '"--%s"'%x or '"-%s"'%x,\ - notFoundKeys) + notFoundKeys = [len(x) > 1 and '"--%s"' % x or '"-%s"' % x for x in notFoundKeys] self.printERROR(_("Not enough command line options: %s")\ %", ".join(notFoundKeys)) return False @@ -20598,19 +20556,19 @@ eth0, eth1, ... etc."%net) FD = open(self.resolvFile) lines = FD.readlines() FD.close() - linesSearchDomains = filter(lambda x: "search " in x or\ - "search\t" in x, lines) + linesSearchDomains = [x for x in lines if "search " in x or\ + "search\t" in x] if linesSearchDomains: - searchDomains = filter(lambda x: x,\ - linesSearchDomains[0].partition("search")[2].replace("\t",\ - " ").split(" ")) - return map(lambda x: x.rstrip(), searchDomains) + searchDomains = [x for x in linesSearchDomains[0].\ + partition("search")[2].replace("\t",\ + " ").split(" ") if x] + return [x.rstrip() for x in searchDomains] def createResolvFile(self, searchDomains): """Создание и модификация /etc/resolv.conf""" dnsIP = "127.0.0.1" - mode = 0644 - domainNames = map(lambda x: x.lower(), searchDomains.split(",")) + mode = 0o644 + domainNames = [x.lower() for x in searchDomains.split(",")] domainNames = self.unicList(domainNames) searchDomains = " ".join(domainNames) if not os.path.exists(self.resolvFile): @@ -20633,7 +20591,7 @@ eth0, eth1, ... etc."%net) def createHostsFile(self, fullHostName): """Создание и модификация /etc/hosts""" dnsIP = "127.0.0.1" - mode = 0644 + mode = 0o644 hostname, spl, domainName = fullHostName.partition(".") if not domainName: domainName = "local" @@ -20674,8 +20632,7 @@ eth0, eth1, ... etc."%net) # Проверка на наличие всех нужных опций if not set(minKeys)<=set(optKeys): notFoundKeys = list(set(minKeys)-set(optKeys)) - notFoundKeys = map(lambda x: len(x)>1 and '"--%s"'%x or '"-%s"'%x,\ - notFoundKeys) + notFoundKeys = [len(x) > 1 and '"--%s"' % x or '"-%s"' % x for x in notFoundKeys] self.printERROR(_("Not enough command line options: %s")\ %", ".join(notFoundKeys)) return False @@ -20699,12 +20656,12 @@ eth0, eth1, ... etc."%net) return False # доменные имена для поиска domainNames = [] - if options.has_key("dnames"): - domainNames = map(lambda x: x.lower(), options["dnames"].split(",")) + if "dnames" in options: + domainNames = [x.lower() for x in options["dnames"].split(",")] domainNames = self.unicList(domainNames) # проверка доменных имен на ip - incorrectDomains = filter(lambda x:\ - self.isCorrectStringNet(x, False), domainNames) + incorrectDomains = [x for x in domainNames + if self.isCorrectStringNet(x, False)] if incorrectDomains: self.printERROR(_('Incorrect command line option "--dnames"')) self.printWARNING(_("Example") + ":") @@ -20720,7 +20677,7 @@ eth0, eth1, ... etc."%net) return False dnsIP = "" # ip адреса dns серверов - if options.has_key("dnsip"): + if "dnsip" in options: dnsIP = options["dnsip"] # проверка правильности ip if not self.isCorrectStringNet(dnsIP, False) or\ @@ -20754,7 +20711,7 @@ eth0, eth1, ... etc."%net) recData = self.servDnsObj.searchAllDomainNamesInLDAP(fullHostName) ip = "" if recData: - if recData[0][0][1].has_key('aRecord'): + if 'aRecord' in recData[0][0][1]: ip = recData[0][0][1]['aRecord'][0] # Удаляем A запись if not self.servDnsObj.delRecordDnsServer({"host":fullHostName}, @@ -20773,12 +20730,11 @@ eth0, eth1, ... etc."%net) deleteIP = self.servDnsObj.searchIPForHostInReverse(\ fullHostName) if recData: - if recData[0][0][1].has_key('pTRRecord'): + if 'pTRRecord' in recData[0][0][1]: hostList = recData[0][0][1]['pTRRecord'] # Удаляет лишние точки в названии - delDot = lambda y: ".".join(filter(lambda x: x,\ - y.split("."))) - hostList = map(lambda x: delDot(x),hostList) + delDot = lambda y: ".".join(x for x in y.split(".") if x) + hostList = [delDot(x) for x in hostList] if not fullHostName in hostList: deleteIP.append(ip) deleteIP = list(set(deleteIP)) @@ -20806,7 +20762,7 @@ eth0, eth1, ... etc."%net) return False if recData: flagDelARecord = True - if recData[0][0][1].has_key('aRecord'): + if 'aRecord' in recData[0][0][1]: aRecords = recData[0][0][1]['aRecord'] if ip in aRecords: flagCreateARecord = False @@ -20885,14 +20841,13 @@ eth0, eth1, ... etc."%net) # Флаг создания обратной записи flagCreatePTRRecord = True if recData: - if recData[0][0][1].has_key('pTRRecord'): + if 'pTRRecord' in recData[0][0][1]: hostList = recData[0][0][1]['pTRRecord'] # Удаляет лишние точки в названии - delDot = lambda y: ".".join(filter(lambda x: x,\ - y.split("."))) - hostList = map(lambda x: delDot(x),hostList) + delDot = lambda y: ".".join(x for x in y.split(".") if x) + hostList = [delDot(x) for x in hostList] if fullHostName in hostList: - deleteIP = filter(lambda x: x!=ip, deleteIP) + deleteIP = [x for x in deleteIP if x != ip] flagCreatePTRRecord = False else: deleteIP.append(ip) @@ -20943,24 +20898,24 @@ eth0, eth1, ... etc."%net) optKeys = options.keys() minKeys = ["ip", "domain", "host", "s", "b"] # Проверка на наличие всех нужных опций - if not set(minKeys)<=set(optKeys): - notFoundKeys = list(set(minKeys)-set(optKeys)) - notFoundKeys = map(lambda x: len(x)>1 and '"--%s"'%x or '"-%s"'%x,\ - notFoundKeys) + if not set(minKeys) <= set(optKeys): + notFoundKeys = list(set(minKeys) - set(optKeys)) + notFoundKeys = [len(x) > 1 and '"--%s"' % x or '"-%s"' % x + for x in notFoundKeys] self.printERROR(_("Not enough command line options: %s")\ %", ".join(notFoundKeys)) return False optPwd = ["p","P"] - listOptPwd = filter(lambda x: x in optPwd, options.keys()) + listOptPwd = [x for x in options.keys() if x in optPwd] if len(listOptPwd) > 1: self.printERROR(_("Command line options '-p' and '-P' are \ incompatible, use one of the options")) return False adminDn = options['s'] - if options.has_key("p"): + if "p" in options: adminPw = options['p'] - elif options.has_key("P"): + elif "P" in options: pathPasswd = options['P'] if os.path.exists(pathPasswd): try: @@ -20982,7 +20937,7 @@ incompatible, use one of the options")) self.printERROR(_("IP address %s incorrectly")%ip) return False domain = options['domain'] - listDomain = filter(lambda x: x.strip(), domain.split(" ")) + listDomain = [x for x in domain.split(" ") if x.strip()] if not listDomain: self.printERROR(_('Incorrect command line option "--domain"')) return False @@ -21029,7 +20984,7 @@ incompatible, use one of the options")) # Поиск статических DHCP хостов в DNS for hostname, data in dataHosts: ip = "" - if not data.has_key("fixed-address"): + if "fixed-address" not in data: self.printERROR(_("Can not found ip static host %s")\ %hostname+ " " + _("in config file %s")\ %dhcpObj.nameConfigFile) @@ -21052,7 +21007,7 @@ incompatible, use one of the options")) recData = self.servDnsObj.searchAllDomainNamesInLDAP(\ fullDomainName) if recData: - if recData[0][0][1].has_key('aRecord'): + if 'aRecord' in recData[0][0][1]: aRecords = recData[0][0][1]['aRecord'] if ip in aRecords: retData[fullDomainName] = ip @@ -21100,7 +21055,7 @@ incompatible, use one of the options")) domainName = "%s.%s"\ %(record[0][1]["relativeDomainName"][0],\ zoneName) - if record[0][1].has_key("aRecord"): + if "aRecord" in record[0][1]: ip = record[0][1]["aRecord"][0] # ip в диапазоне динамических адресов if isRange(self.getNumberIP(ip), minIpRange, maxIpRange): @@ -21139,7 +21094,7 @@ incompatible, use one of the options")) def moveDNSRecords(self, newZoneName, moveRecords): """Перенос записей в новую зону""" # Удаляет лишние точки в названии - delDot = lambda y: ".".join(filter(lambda x: x, y.split("."))) + delDot = lambda y: ".".join(x for x in y.split(".") if x) flagError = False for hostname, ip in moveRecords: newHostName = ".".join([hostname.partition(".")[0],newZoneName]) @@ -21169,7 +21124,7 @@ incompatible, use one of the options")) # Поиск в новой зоне A записи foundNewARec = self.servDnsObj.searchDomainNameInLDAP(newHostName) if foundNewARec: - if foundNewARec[0][0][1].has_key('aRecord'): + if 'aRecord' in foundNewARec[0][0][1]: if foundNewARec[0][0][1]['aRecord'][0] != otherIP: self.printERROR(_("Record %s exists in DNS service")\ %newHostName) @@ -21253,8 +21208,7 @@ incompatible, use one of the options")) dnsIP = ",".join(dnsIPs) if not self.servDnsObj.searchZoneInLDAP(zoneName): # Находим все ip DNS cервера - IPs = filter(None, - self.servDnsObj.clVars.Get("os_net_ip").split(",")) + IPs = [x for x in self.servDnsObj.clVars.Get("os_net_ip").split(",") if x] if not IPs: self.printERROR(_("Can not found ip in net interfaces")) return False @@ -21269,10 +21223,10 @@ incompatible, use one of the options")) if flagErrorRange: self.printERROR(\ _('Command line option "--range %s" incorrectly')\ - %",".join(ranges)) + % ",".join(ranges)) self.printERROR( _("Invalid range of network addresses for the network %s")\ - %net) + % net) return False flagFoundDnsIp = False for ipDns in dnsIPs: @@ -21285,7 +21239,7 @@ incompatible, use one of the options")) _('Command line option "--dnsip %s" incorrectly')\ %dnsIP) self.printERROR(_("Can not found ip address dns servers in \ -network %s")%net) +network %s") % net) return False ipserver = "" for ipIntr in IPs: @@ -21296,8 +21250,8 @@ network %s")%net) if not ipserver: self.printERROR(\ _("Ip addresses on the interfaces of the system (%s)")\ - %",".join(IPs)+" "+_("does not belong to the network %s")\ - %net) + % ",".join(IPs) + " " + _("does not belong to the network %s")\ + % net) return False # опции добавления DNS зоны optionsDns = {"n":zoneName, @@ -21308,8 +21262,7 @@ network %s")%net) return False # Ищем обратные зоны в DNS listNet24 = self.nets24ToIpAndMask(net) - listStrNet24 = map(lambda x: ".".join(map(lambda y: str(y), x)), - listNet24) + listStrNet24 = [".".join(str(y) for y in x) for x in listNet24] # Получаем имена обратных зон reverseZoneNames = [] for net24 in listStrNet24: @@ -21317,7 +21270,7 @@ network %s")%net) netSpl.pop() netSpl.reverse() # Имя обратной зоны - reverseZoneNames.append("%s.in-addr.arpa" %".".join(netSpl)) + reverseZoneNames.append("%s.in-addr.arpa" % ".".join(netSpl)) # Создаем обратные зоны в тексте конфигурационного файла objTxtZone = dnsTxt() if not objTxtZone.createExclZones(self.servDnsObj.clVars, @@ -21362,8 +21315,8 @@ network %s")%net) for net, data in dataNets: notFoundOpts = [] ranges = [] - if data.has_key("range"): - ranges = filter(lambda x: x.strip(), data["range"]) + if "range" in data: + ranges = [x for x in data["range"] if x.strip()] if not ranges: notFoundOpts.append(("range", "--range ")) @@ -21375,21 +21328,21 @@ network %s")%net) " " + _("in config file %s") %dhcpObj.nameConfigFile) return False dnsIPs = [] - if data.has_key("optiondomain-name-servers"): + if "optiondomain-name-servers" in data: dnsIPs = data["optiondomain-name-servers"][0].split(",") if not dnsIPs: notFoundOpts.append(("option domain-name-servers", "--dnsip ")) domainNames = [] - if data.has_key("optiondomain-name"): - domainNames = map(lambda x: x.strip().replace('"',''),\ - data["optiondomain-name"]) + if "optiondomain-name" in data: + domainNames = [x.strip().replace('"', '') + for x in data["optiondomain-name"]] if not domainNames: notFoundOpts.append(("option domain-name", "--dnames ")) if notFoundOpts: - optionsPr = map(lambda x: "'%s'"%x[0], notFoundOpts) - optionsCmdPr = map(lambda x: x[1], notFoundOpts) + optionsPr = ["'%s'" % x[0] for x in notFoundOpts] + optionsCmdPr = [x[1] for x in notFoundOpts] self.printERROR(_("Can not create DNS zone %s") %net) self.printERROR(\ _('Can not found %s')%",".join(optionsPr) + " "+\ @@ -21411,7 +21364,7 @@ network %s")%net) dataHosts = dhcpObj.getDataInAllHost() for hostname, data in dataHosts: ip = "" - if not data.has_key("fixed-address"): + if "fixed-address" not in data: self.printERROR(_("Can not create static host")) self.printERROR(_("Can not found ip static host %s")\ %hostname+ " " + _("in config file %s")\ @@ -21440,7 +21393,7 @@ network %s")%net) recData = self.servDnsObj.searchAllDomainNamesInLDAP(\ fullDomainName) if recData: - if recData[0][0][1].has_key('aRecord'): + if 'aRecord' in recData[0][0][1]: aRecords = recData[0][0][1]['aRecord'] if not ip in aRecords: flagError = True @@ -21469,14 +21422,13 @@ network %s")%net) # Флаг создания обратной записи flagCreatePTR = True if recData: - if recData[0][0][1].has_key('pTRRecord'): + if 'pTRRecord' in recData[0][0][1]: hostList = recData[0][0][1]['pTRRecord'] # Удаляет лишние точки в названии - delDot = lambda y: ".".join(filter(lambda x: x,\ - y.split("."))) - hostList = map(lambda x: delDot(x),hostList) + delDot = lambda y: ".".join(x for x in y.split(".") if x) + hostList = [delDot(x) for x in hostList] if hostname in hostList: - deleteIP = filter(lambda x: x!=ip, deleteIP) + deleteIP = [x for x in deleteIP if x != ip] flagCreatePTR = False else: deleteIP.append(ip) @@ -21545,8 +21497,8 @@ network %s")%net) if not dhcpObj: dhcpObj = dncpTxt() dataHosts = dhcpObj.getDataInAllHost() - getPar = lambda opt, data: map(lambda x: opt in x[1].keys() and\ - (x[0],x[1][opt]) or (), data) + getPar = lambda opt, data:\ + [opt in x[1].keys() and (x[0],x[1][opt]) or () for x in data] flagCorrect = True staticMACs = getPar('hardwareethernet', dataHosts) for data in staticMACs: @@ -21607,12 +21559,11 @@ network %s")%net) " " + _("for network %s")%net) return False netList = self.nets24ToMinIpAndMaxIp(minNumber, maxNumber) - strNetList = map(lambda x: ".".join(map(lambda y: str(y), x[0:3])), - netList) + strNetList = [".".join(str(y) for y in x[0:3]) for x in netList] # Проверка на статические хосты dataHosts = dhcpObj.getDataInAllHost() - getPar = lambda opt, data: map(lambda x: opt in x[1].keys() and\ - (x[0],x[1][opt]) or (), data) + getPar = lambda opt, data: [opt in x[1].keys() and\ + (x[0],x[1][opt]) or () for x in data] staticIPs = getPar('fixed-address', dataHosts) for data in staticIPs: if not data: @@ -21646,8 +21597,8 @@ network %s")%net) dhcpObj = dncpTxt() dataNets = dhcpObj.getDataInAllSubnet() dataHosts = dhcpObj.getDataInAllHost() - getPar = lambda opt, data: map(lambda x: opt in x[1].keys() and\ - (x[0],x[1][opt]) or (), data) + getPar = lambda opt, data: [opt in x[1].keys() and\ + (x[0], x[1][opt]) or () for x in data] ranges = getPar('range', dataNets) try: numbIp = self.getNumberIP(ip) @@ -21743,8 +21694,8 @@ network %s")%net) dhcpObj = dncpTxt() dataNets = dhcpObj.getDataInAllSubnet() dataHosts = dhcpObj.getDataInAllHost() - getPar = lambda opt, data: map(lambda x: opt in x[1].keys() and\ - (x[0],x[1][opt]) or (), data) + getPar = lambda opt, data: [opt in x[1].keys() and\ + (x[0], x[1][opt]) or () for x in data] ranges = getPar('range', dataNets) if not ranges: self.printERROR(_("Can not found 'range' in config file %s")\ @@ -21819,7 +21770,7 @@ network %s")%net) isNotRange(maxIpRanges, minNumber, maxNumber): return [] # Проверка на коректность сетевых адресов - if filter(lambda x: not self.isCorrectStringNet(x, False), (ipA, ipB)): + if [x for x in (ipA, ipB) if not self.isCorrectStringNet(x, False)]: return [] return [self.getIPinNumber(minIpRanges),self.getIPinNumber(maxIpRanges)] @@ -21838,9 +21789,9 @@ network %s")%net) # Создаем файловый объект fileObj = cl_profile._file() dMode, dUid, dGid = fileObj.getModeFile(cl_log.log.logDir) - if dMode != 0755: + if dMode != 0o755: try: - os.chmod(cl_log.log.logDir,0755) + os.chmod(cl_log.log.logDir,0o755) except: self.printERROR(_("Can not set mode 0755 for %s")\ %cl_log.log.logDir) @@ -21893,7 +21844,7 @@ network %s")%net) # Принудительная установка forceOptions = False minKeys = [] - if options.has_key("f"): + if "f" in options: forceOptions = True minKeys = ["f"] # Создаем объект переменных @@ -21923,8 +21874,7 @@ network %s")%net) # Проверка на наличие всех нужных опций if not set(minKeys)<=set(optKeys): notFoundKeys = list(set(minKeys)-set(optKeys)) - notFoundKeys = map(lambda x: len(x)>1 and '"--%s"'%x or '"-%s"'%x,\ - notFoundKeys) + notFoundKeys = [len(x) > 1 and '"--%s"' % x or '"-%s"' % x for x in notFoundKeys] self.printERROR(_("Not enough command line options: %s")\ %", ".join(notFoundKeys)) return False @@ -21999,26 +21949,26 @@ network %s")%net) return False # Создаем текстовый блок в конфигурационном файле для новой сети netOptions = {} - if options.has_key("net"): + if "net" in options: netOptions["net"] = options["net"] - if options.has_key("router"): + if "router" in options: netOptions["router"] = options["router"] - if options.has_key("dnames"): + if "dnames" in options: netOptions["dnames"] = options["dnames"] - if options.has_key("dnsip"): + if "dnsip" in options: netOptions["dnsip"] = options["dnsip"] - if options.has_key("range"): + if "range" in options: netOptions["range"] = options["range"] if not self.createNetDhcpServer(netOptions, False): return False # Добавляем в статические хосты имя текущего хоста hostname = self.clVars.Get("os_net_hostname") if hostname: - domainNames = map(lambda x: x.lower(), options["dnames"].split(",")) + domainNames = [x.lower() for x in options["dnames"].split(",")] domainNames = self.unicList(domainNames) domain = domainNames[0] fullHostNameServer = "%s.%s"%(hostname,domain) - IPs = filter(None,self.clVars.Get("os_net_ip").split(",")) + IPs = [x for x in self.clVars.Get("os_net_ip").split(",") if x] if not any(IPs): self.printERROR(_("Can not found ip in net interfaces")) return False @@ -22039,7 +21989,7 @@ network %s")%net) # Ищем A запись в DNS recData = self.servDnsObj.searchDomainNameInLDAP(\ fullHostNameServer) - if recData and recData[0][0][1].has_key('aRecord'): + if recData and 'aRecord' in recData[0][0][1]: flagFoundARecord = True if ipServer in recData[0][0][1]['aRecord']: flagCreateDNSRecord = False @@ -22052,13 +22002,12 @@ network %s")%net) # Находим ptr запись в DNS recData = self.servDnsObj.searchAllDomainNamesInLDAP(\ PTRDomainName) - if recData and recData[0][0][1].has_key('pTRRecord'): + if recData and 'pTRRecord' in recData[0][0][1]: if not flagCreateDNSRecord: hostList = recData[0][0][1]['pTRRecord'] # Удаляет лишние точки в названии - delDot = lambda y: ".".join(filter(lambda x: x,\ - y.split("."))) - hostList = map(lambda x: delDot(x),hostList) + delDot = lambda y: ".".join(x for x in y.split(".") if x) + hostList = [delDot(x) for x in hostList] if not fullHostNameServer in hostList: flagCreateDNSRecord = True flagDeletePTRRecord = True @@ -22142,15 +22091,15 @@ class tsOpt(cl_base.opt): tuple(set(self.opt.keys()).intersection(helpObj.relOptions.keys())) #Если есть опции help if len(helpopt) > 0: - print helpObj.getHelp(helpObj.relOptions[helpopt[0]]) + print(helpObj.getHelp(helpObj.relOptions[helpopt[0]])) self.flagHelp = True #Если нет хвостов elif not self.params: if optService or lastOpt: - print helpObj.getHelp(helpObj.relOptions['h']) + print(helpObj.getHelp(helpObj.relOptions['h'])) self.flagHelp = True else: - if self.params.has_key('service'): + if 'service' in self.params: if lastOpt: pass elif not (self.params['service'] in helpObj.allServ): @@ -22163,13 +22112,13 @@ class tsOpt(cl_base.opt): self.handlerErrOpt() self.flagHelp = True # В случае отсутствия опций командной строки - if notOptError and not self.opt and self.params.has_key('service'): + if notOptError and not self.opt and 'service' in self.params: self.printErrorNotOpt() self.flagHelp = True def printErrorNotOpt(self): """Сообщение в случае отсутствия опций""" - print _("Options are absent.") + print(_("Options are absent.")) def handlerOpt(self,option,value): # Обработчик (опция значение) @@ -22184,9 +22133,9 @@ class tsOpt(cl_base.opt): # Обработчик ошибок self.errorOpt = True argv = " ".join(sys.argv[1:]) - print _("Unrecognized option") + ' "' + argv + '"\n' + \ + print(_("Unrecognized option") + ' "' + argv + '"\n' + \ _("Try") + ' "' + sys.argv[0].split("/")[-1] + ' --help" ' +\ -_("for more information.") +_("for more information.")) def handlerParam(self,param): # Обработчик хвостов (значение) diff --git a/setup.py b/setup.py index c32e2de..4491ba7 100755 --- a/setup.py +++ b/setup.py @@ -140,15 +140,18 @@ class cl_install_data(install_data): def run (self): install_data.run(self) data_file = \ - [("/etc/init.d/sortmilter.init","sortmilter",0755), + [("/etc/init.d/sortmilter.init","sortmilter",0o755), ("/etc/conf.d/sortmilter.conf","sortmilter",None)] data_find = \ dict( - map(lambda x:(os.path.basename(x[0]), - [list(reversed(filter(lambda y:y,x[0].split("/")))), - x[1], - x[2]]), - data_file)) + # map(lambda x:(os.path.basename(x[0]), + # [list(reversed(filter(lambda y:y,x[0].split("/")))), + # x[1], + # x[2]]), + # data_file)) + + # [(os.path.basename(x[0]), [list(reversed(filter(lambda y:y,x[0].split("/")))), x[1],x[2]]) for x in data_file]) + [(os.path.basename(x[0]), [list(reversed((y for y in x[0].split("/") if y))), x[1],x[2]]) for x in data_file]) for path in self.get_outputs(): nameFile = os.path.split(path)[1]