diff --git a/pym/cl_ldap.py b/pym/cl_ldap.py index b53ee9d..0755892 100644 --- a/pym/cl_ldap.py +++ b/pym/cl_ldap.py @@ -1245,9 +1245,10 @@ in a sambaDomainName', os.close(fd) os.chmod(fileName, mode) os.chown(fileName,uid,gid) - FD = open(fileName, "r+") - FD.write(fileTxt) - FD.close() + if fileTxt: + FD = open(fileName, "r+") + FD.write(fileTxt) + FD.close() return True @@ -7519,9 +7520,12 @@ outdated. If the backup is obsolete, use cl-backup.")) return False if not flagError and "dhcp" in servInstalled and\ serviceUpdate in ["all","dhcp"]: + # Создаем файл вывода ошибок скрипта dhcp + if not self.servDhcpObj.createLogFile(): + flagError = True # Создаем DNS зоны на основании информации в # конфигурационном файле сервиса DHCP (dhcpd.conf) - if not self.servDhcpObj.upgrageDNSZones(): + if not flagError and not self.servDhcpObj.upgrageDNSZones(): flagError = True if not flagError and serviceUpdate in ["all","unix","samba","mail"]: # создаем объект репликации @@ -18716,6 +18720,9 @@ in LDAP")%zoneName) class servDhcp(shareLdap): """Методы сервиса DHCP""" + # Название файла для вывода ошибок + errorLogFile = "dhcp-error.log" + def __init__(self): shareLdap.__init__(self) # Объект сервиса DNS @@ -19448,8 +19455,17 @@ eth0, eth1, ... etc."%net) return False return True - def addDNSRecordServer(self, options): + def addDNSRecordServer(self, options, logObj=False): """Добавляет подключившийся к DHCP компьютер в DNS сервис""" + # Если есть объект логгирования + if logObj: + # Переопределяем методы печати ошибок + printERROR = lambda x:\ + cl_utils2.cl_smartcon.printERROR(self, x) or\ + logObj.writeError(x) + self.printERROR = printERROR + self.servDnsObj.printERROR = printERROR + optKeys = options.keys() minKeys = ["ip", "domain", "host", "s", "b"] # Проверка на наличие всех нужных опций @@ -20109,6 +20125,83 @@ network %s")%net) else: return [] + def getUserUidAndGid(self, userName): + """Находит в системе uid и gid пользователя + + userName - имя пользователя и имя группы пользователя + """ + groupName = userName + import pwd + try: + uid = pwd.getpwnam(userName)[2] + except: + self.printERROR(_("Can not found user %s in this system")%userName) + return () + try: + import grp + gid = grp.getgrnam(groupName)[2] + except: + self.printERROR(_("Can not found user %s in this system")%groupName) + return () + return (uid, gid) + + def createLogFile(self): + """Создание файла лога или если нужно изменение владельца файла лога""" + import cl_log + # Полное имя файла лога (путь плюс имя файла) + logFullFile = os.path.join(cl_log.log.logDir, self.errorLogFile) + if not os.path.exists(cl_log.log.logDir): + try: + os.makedirs(cl_log.log.logDir) + except: + self.printError(_("Can not create %s")%cl_log.log.logDir) + return False + else: + # Создаем файловый объект + fileObj = cl_profile._file() + dMode, dUid, dGid = fileObj.getModeFile(cl_log.log.logDir) + if dMode != 0755: + try: + os.chmod(cl_log.log.logDir,0755) + except: + self.printERROR(_("Can not set mode 0755 in %s")\ + %cl_log.log.logDir) + return False + if dUid !=0 or dGid !=0: + try: + os.chown(cl_log.log.logDir, 0, 0) + except: + self.printERROR(\ + _("Can not change owner (root:root) in %s")\ + %cl_log.log.logDir) + return False + uidAndGid = self.getUserUidAndGid("dhcp") + if not uidAndGid: + return False + uid, gid = uidAndGid + if os.path.exists(logFullFile): + # Создаем файловый объект + fileObj = cl_profile._file() + fMode, fUid,fGid = fileObj.getModeFile(logFullFile) + # Если необходимо меняем владельца + if (fUid, fGid)!=(uid, gid): + try: + os.chown(logFullFile, uid, gid) + except: + self.printERROR(_("Can not change owner (dhcp:dhcp) in %s")\ + %logFullFile) + return False + else: + try: + self.createUserFile(logFullFile, "", uid, gid) + except: + self.printERROR(_("Can not create %s")%logFullFile) + return False + if not os.access(logFullFile, os.W_OK): + self.printERROR(_("Can not access in %s")%logFullFile) + return False + return True + def setupDhcpServer(self, options): """Начальная настройка DHCP сервиса""" # Принудительная установка @@ -20174,6 +20267,9 @@ network %s")%net) else: if not bakupObj.backupNotLdap(): return False + # Создаем файл вывода ошибок скрипта dhcp + if not self.createLogFile(): + return False # Удаляем переменные сервиса в ini файлах self.deleteServiceVarsInFile("dhcp") # Если существует конфигурационный файл diff --git a/scripts/dhcp b/scripts/dhcp index 0de8d50..1f6189e 100644 --- a/scripts/dhcp +++ b/scripts/dhcp @@ -20,6 +20,8 @@ import os sys.path.insert(0,os.path.abspath('/usr/lib/calculate/calculate-lib/pym')) sys.path.insert(0,os.path.abspath('/usr/lib/calculate/calculate-server/pym')) import cl_base +# Логгирование +import cl_log tr = cl_base.lang() tr.setGlobalDomain('cl_server') tr.setLanguage(sys.modules[__name__]) @@ -30,7 +32,31 @@ if __name__ == "__main__": flagError = True if not optObj.flagHelp: obj = cl_ldap.servDhcp() - if obj.addDNSRecordServer(optObj.opt): + logFile = obj.errorLogFile + logFullFile = os.path.join(cl_log.log.logDir,logFile) + user = "dhcp" + uidAndGid = obj.getUserUidAndGid(user) + if not uidAndGid: + sys.exit(1) + uid, gid = uidAndGid + if os.getuid() == 0: + # Меняем владельца процесса на dhcp + try: + os.setgid(gid) + os.setuid(uid) + except: + print _("ERROR: Can not set owner") + \ + " (dhcp:dhcp uid=%s,gid=%s) "%(uid, gid) +\ + _("the this process") + sys.exit(1) + if os.getuid() != uid: + print _("ERROR: Owner this process not dhcp or root") + sys.exit(1) + if os.access(logFullFile, os.W_OK): + logObj = cl_log.log(logFile) + else: + logObj = False + if obj.addDNSRecordServer(optObj.opt, logObj): flagError = False if flagError: sys.exit(1)