Изменены методы вылолняющие внешние команды

develop
Самоукин Алексей 15 years ago
parent 51ca4f3b43
commit 9116708959

@ -26,9 +26,8 @@ class fillVars(object, cl_base.glob_attr):
password - пароль
encrypt - алгоритм шифрования, например '{SSHA}'
"""
runStr='%s slappasswd -s %s -h %s'%\
(self.path_env, password, encrypt)
res=self._runos(runStr)
runStr='slappasswd -s %s -h %s' %(password, encrypt)
res = self._runos(runStr)
if res:
return res.strip()
print "Error generate hash (slappasswd)"

@ -405,7 +405,7 @@ in a sambaDomainName',
servInstalled = []
# доступные сервисы
services = ('ldap', 'unix', 'samba', 'mail',
'jabber', 'ftp', 'proxy', 'dns')
'jabber', 'ftp', 'proxy', 'dns', 'dhcp')
for serv in services:
if self.clVars.Get("sr_%s_set"%serv) == "on":
servInstalled.append(serv)
@ -558,59 +558,51 @@ in a sambaDomainName',
"""Прописывает демона в автозагрузку"""
execStr = "rc-update add %s default" %daemon
textLine = self.execProg(execStr)
if "added to runlevel" in textLine or\
"already installed in runlevel" in textLine:
return True
else:
if textLine == False:
self.printERROR(_("ERROR") + ": " + execStr)
self.printERROR(_("Can not add at default runlevel"))
self.printERROR(_("Can not add '%s' at default runlevel")%daemon)
return False
else:
return True
def delDaemonAutostart(self, daemon):
"""Удаляет демона из автозагрузки"""
execStr = "rc-update del %s default" %daemon
textLine = self.execProg(execStr)
if "removed from the following runlevels" in textLine or\
"not found in any of the specified runlevels" in textLine:
return True
#Для openrc
elif "removed from runlevel" in textLine or\
"is not in the runlevel" in textLine:
return True
else:
if textLine == False:
self.printERROR(_("ERROR") + ": " + execStr)
self.printERROR(_("Not deleted from default runlevel"))
self.printERROR(_("Can not deleted '%s' from default runlevel")\
%daemon)
return False
else:
return True
def runLdapServer(self):
"""Запускает LDAP сервер"""
textLines = self.execProg("/etc/init.d/slapd start", False, False)
if textLines and type(textLines) == types.ListType and\
"ok" in textLines[-1] or textLines and "ok" in textLines:
return True
else:
textLines = self.execProg("/etc/init.d/slapd start")
if textLines == False:
self.printNotOK(_("Starting LDAP")+ " ...")
return False
else:
return True
def restartLdapServer(self):
"""Запускает LDAP сервер"""
textLines = self.execProg("/etc/init.d/slapd restart", False, False)
if textLines and type(textLines) == types.ListType and\
"ok" in textLines[-1] or textLines and "ok" in textLines:
return True
else:
textLines = self.execProg("/etc/init.d/slapd restart")
if textLines == False:
self.printNotOK(_("Restarting LDAP")+ " ...")
return False
else:
return True
def stopLdapServer(self):
"""Останавливает LDAP сервер"""
textLines = self.execProg("/etc/init.d/slapd stop", False, False)
if textLines and type(textLines) == types.ListType and\
"ok" in textLines[-1] or textLines and "ok" in textLines:
return True
else:
textLines = self.execProg("/etc/init.d/slapd stop")
if textLines == False:
self.printNotOK(_("Stopping LDAP")+ " ...")
return False
else:
return True
def getALLServices(self):
"""Получаем все сервисы которые описаны в профилях"""
@ -691,10 +683,8 @@ in a sambaDomainName',
flagError = False
for daemon in daemons:
if not self.getRunDaemons([daemon]):
textLines = self.execProg("/etc/init.d/%s start" %(daemon),
False, False)
if not (textLines and type(textLines) == types.ListType and\
"ok" in textLines[-1] or textLines and "ok" in textLines):
textLines = self.execProg("/etc/init.d/%s start" %(daemon))
if textLines == False:
self.printERROR( _("Daemon %s was not started") %daemon)
flagError = True
break
@ -803,66 +793,55 @@ in a sambaDomainName',
# В случае почтового релея
elif service == "mail_relay":
if self.getRunDaemons(["postfix"]):
textLines = self.execProg("/etc/init.d/postfix stop", False,
False)
if not (textLines and type(textLines) == types.ListType and\
"ok" in textLines[-1] or textLines and\
"ok" in textLines):
textLines = self.execProg("/etc/init.d/postfix stop")
if textLines == False:
self.printERROR( "Postfix" + " " +
_("service is not stopped"))
flagError = True
break
elif service == "mail":
if self.getRunDaemons(["postfix"]):
textLines = self.execProg("/etc/init.d/postfix stop", False,
False)
if not (textLines and type(textLines) == types.ListType\
and "ok" in textLines[-1] or textLines and\
"ok" in textLines):
textLines = self.execProg("/etc/init.d/postfix stop")
if textLines == False:
self.printERROR( "Postfix" + " " +
_("service is not stopped"))
flagError = True
break
if self.getRunDaemons(["dovecot"]):
textLines = self.execProg("/etc/init.d/dovecot stop", False,
False)
if not (textLines and type(textLines) == types.ListType and\
"ok" in textLines[-1] or textLines and\
"ok" in textLines):
self.printERROR(str("Dovecot") + " " +
textLines = self.execProg("/etc/init.d/dovecot stop")
if textLines == False:
self.printERROR("Dovecot" + " " +
_("service is not stopped"))
flagError = True
break
elif service == "jabber":
if self.getRunService("jabber"):
textLines = self.execProg("/etc/init.d/ejabberd stop",False,
False)
if not (textLines and type(textLines) == types.ListType and\
"ok" in textLines[-1] or textLines and\
"ok" in textLines):
textLines = self.execProg("/etc/init.d/ejabberd stop")
if textLines == False:
self.printERROR( "Ejabberd" + " " +
_("service is not stopped"))
flagError = True
break
listProcess = self.execProg("ps ax",False,False)
strCmd = "ps ax"
listProcess = self.execProg(strCmd,False,False)
if listProcess == False:
self.printERROR(_('Can not execute "%s"')%strCmd)
return False
killPid = []
for process in listProcess:
if "erlang" in process:
killPid.append(process.split(" ")[0])
if killPid and " ".join(killPid).strip():
textLine = self.execProg("kill %s" %" ".join(killPid))
if not (textLine == None):
if textLine == False:
self.printERROR(_("Can not 'kill %s'")\
%" ".join(killPid))
flagError = True
break
elif service == "ftp":
if self.getRunDaemons(["proftpd"]):
textLines = self.execProg("/etc/init.d/proftpd stop",False,
False)
if not (textLines and type(textLines) == types.ListType and\
"ok" in textLines[-1] or textLines and\
"ok" in textLines):
textLines = self.execProg("/etc/init.d/proftpd stop")
if textLines == False:
self.printERROR( "Proftpd" + " " +
_("service is not stopped"))
flagError = True
@ -910,30 +889,24 @@ in a sambaDomainName',
break
elif service == "dns":
if self.getRunDaemons(["named"]):
textLines = self.execProg("/etc/init.d/named stop",False,
False)
if not (textLines and type(textLines) == types.ListType and\
"ok" in textLines[-1] or textLines and\
"ok" in textLines):
textLines = self.execProg("/etc/init.d/named stop")
if textLines == False:
self.printERROR( "DNS" + " " +
_("service is not stopped"))
flagError = True
break
elif self.getRunService(service):
stopService = service
textLines = self.execProg("/etc/init.d/%s stop" %(stopService),
False, False)
if not (textLines and type(textLines) == types.ListType and\
"ok" in textLines[-1] or textLines and "ok" in textLines):
textLines = self.execProg("/etc/init.d/%s stop" %(stopService))
if textLines == False:
self.printERROR( str(service) + " " +
_("service is not stopped"))
flagError = True
break
if flagLdap:
if self.getRunService('ldap'):
textLines = self.execProg("/etc/init.d/slapd stop",False,False)
if not (textLines and type(textLines) == types.ListType and\
"ok" in textLines[-1] or textLines and "ok" in textLines):
textLines = self.execProg("/etc/init.d/slapd stop")
if textLines == False:
self.printERROR( "LDAP" + " " +
_("service is not stopped"))
flagError = True
@ -979,7 +952,11 @@ in a sambaDomainName',
# Проверка на запуск демона postfix
if daemon == 'postfix':
flagRun = False
listProcess = self.execProg("ps ax",False,False)
strCmd = "ps ax"
listProcess = self.execProg(strCmd, False, False)
if not listProcess:
self.printERROR(_('Can not execute "%s"')%strCmd)
return False
for process in listProcess:
if "postfix/master" in process:
flagRun = True
@ -1594,17 +1571,22 @@ This command is not allowed."))
return False
return True
def execProg(self, cmdStrProg, inStr=False, retFull=True):
def execProg(self, cmdStrProg, inStr=False, retFull=True, envProg={}):
"""Выполняет внешнюю программу
Параметры:
cmdStrProg внешняя программа
inStr данные передаваемые программе на страндартный вход.
Возвращаемые параметры:
строка которую выведет внешняя программа
строка которую выведет внешняя программа или False в случае ошибки
"""
return cl_utils.runOsCommand(cmdStrProg, inStr, retFull)
env_path = {"PATH":cl_utils.getpathenv()}
env = {}
env.update(os.environ.items() + env_path.items() + envProg.items())
retCode,programOut = cl_utils.runOsCommand(cmdStrProg,inStr,retFull,env)
if not retCode:
return programOut
return False
def createLdif(self, ldifFile):
"""Cоздает ldif из ldif - профиля"""
@ -2919,7 +2901,7 @@ service"))
homeDirOld = res[0][0][1]['homeDirectory'][0]
homeDirNew = homeDir
textLine = self.execProg("mv %s %s" %(homeDirOld, homeDirNew))
if not (textLine == None):
if textLine == False:
self.printERROR(_("Can not move home directory"))
modAttrs = [(ldap.MOD_REPLACE, 'homeDirectory',
homeDirOld)]
@ -4650,23 +4632,21 @@ if you want to continue to run the program again"))
"PASS":self.clVars.Get("ld_mail_pw")})
self.printOK(_("Added ldif file") + " ...")
textLine = self.execProg("newaliases")
if not (textLine == None):
if textLine == False:
self.printERROR(_("Can not create Postfix aliases"))
return False
textLines = self.execProg("/etc/init.d/postfix start",False,False)
if textLines and type(textLines) == types.ListType and\
"ok" in textLines[-1] or textLines and "ok" in textLines:
self.printOK(_("Starting") + " " + "Postfix" + " ...")
else:
textLines = self.execProg("/etc/init.d/postfix start")
if textLines == False:
self.printNotOK(_("Starting") + " " + "Postfix" + " ...")
return False
textLines = self.execProg("/etc/init.d/dovecot start", False, False)
if textLines and type(textLines) == types.ListType and\
"ok" in textLines[-1] or textLines and "ok" in textLines:
self.printOK(_("Starting") + " " + "Dovecot" + " ...")
else:
self.printOK(_("Starting") + " " + "Postfix" + " ...")
textLines = self.execProg("/etc/init.d/dovecot start")
if textLines == False:
self.printNotOK(_("Starting") + " " + "Dovecot" + " ...")
return False
else:
self.printOK(_("Starting") + " " + "Dovecot" + " ...")
# Устанавливаем автозапуск демона
if not self.setDaemonAutostart("postfix"):
return False
@ -5467,17 +5447,17 @@ in Unix service") %str(jabberId))
"PASS":self.clVars.Get("ld_jabber_pw")})
self.printOK(_("Added ldif file") + " ...")
# создаем сертификат если есть используем прежний
self.execProg("/bin/bash /etc/jabber/self-cert.sh")
if not os.path.exists("/etc/jabber/ssl.pem"):
self.execProg("/bin/bash /etc/jabber/self-cert.sh")
if not os.path.exists("/etc/jabber/ssl.pem"):
self.printERROR(_("Can not create Jabber certificate"))
return False
textLines = self.execProg("/etc/init.d/ejabberd start", False, False)
if textLines and type(textLines) == types.ListType and\
"ok" in textLines[-1] or textLines and "ok" in textLines:
self.printOK(_("Starting") + " " + "Ejabberd" + " ...")
else:
if textLines == False:
self.printNotOK(_("Starting") + " " + "Ejabberd" + " ...")
return False
else:
self.printOK(_("Starting") + " " + "Ejabberd" + " ...")
# Устанавливаем автозапуск демона
if not self.setDaemonAutostart("ejabberd"):
return False
@ -5738,17 +5718,9 @@ the calculate-server")
if not self.backupDelUser(userName, 'samba/netlogon',
userNetlogonDir):
return False
textLine = self.execProg("smbpasswd -x %s" %(delUser), False, False)
textLine = self.execProg("smbpasswd -x %s" %(delUser))
flagError = False
if textLine:
if type(textLine) == types.ListType:
listLine = []
for line in textLine:
listLine.append(line.rstrip())
textLine = " ".join(listLine)
else:
flagError = True
if not "Deleted user %s" %(delUser) in textLine:
if textLine == False:
flagError = True
# Удаляем пользователя из Samba групп
if not flagError:
@ -5876,7 +5848,7 @@ the calculate-server")
else:
textLine = self.execProg("smbpasswd -a -n %s" %(userName))
if "Added" in str(textLine):
if textLine != False:
flagError = False
if options.has_key('G'):
@ -6508,12 +6480,12 @@ Samba and Unix services") %", ".join(exclGroup)
return True
# добавляем Samba машину
textLine = self.execProg("smbpasswd -a -m %s" %machineLogin)
if "Added" in str(textLine):
self.printSUCCESS(_("Added machine in Samba service"))
return True
else:
if textLine == False:
self.printERROR(_("Can not add machine"))
return False
else:
self.printSUCCESS(_("Added machine in Samba service"))
return True
else:
# добавляем LDAP машину
if not self.servUnixObj.addMachineLdapServer(machineLogin,
@ -6521,12 +6493,12 @@ Samba and Unix services") %", ".join(exclGroup)
return False
# добавляем Samba машину
textLine = self.execProg("smbpasswd -a -m %s" %machineLogin)
if "Added" in str(textLine):
self.printSUCCESS(_("Added machine in Samba service"))
return True
else:
if textLine == False:
self.printERROR(_("Can not add machine"))
return False
else:
self.printSUCCESS(_("Added machine in Samba service"))
return True
def getSambaSid(self):
"""Получаем Samba SID из LDAP"""
@ -6679,7 +6651,7 @@ Samba and Unix services") %", ".join(exclGroup)
_("Samba admin password is not found"))
return False
textLine = self.execProg("smbpasswd -w %s" %(pswd))
if not "stored" in textLine:
if textLine == False:
self.printERROR(_("ERROR") + ": " +\
_("Can not add Samba admin password"))
return False
@ -6713,13 +6685,12 @@ Samba and Unix services") %", ".join(exclGroup)
print _("LDAP Error") + ": " + self.ldapObj.getError().strip()
return False
self.printOK(_("Added ldif file") + " ...")
textLines = self.execProg("/etc/init.d/samba restart", False, False)
if textLines and type(textLines) == types.ListType and\
"ok" in textLines[-1] or textLines and "ok" in textLines:
self.printOK(_("Starting") + " Samba ...")
else:
textLines = self.execProg("/etc/init.d/samba restart")
if textLines == False:
self.printNotOK(_("Starting") + " Samba ...")
return False
else:
self.printOK(_("Starting") + " Samba ...")
# Добавляем статические Samba группы и изменяем настройки
if not self.upgradeService():
return False
@ -6837,21 +6808,21 @@ Samba and Unix services") %", ".join(exclGroup)
# отключаем samba account
if options.has_key('l'):
textLine = self.execProg("smbpasswd -d %s" %(userName))
if "Disabled user %s" %userName in textLine:
self.printSUCCESS(_("Disabled Samba user %s")%str(userName))
else:
if textLine == False:
self.printERROR(_("Can not disable Samba user")+ " "+\
str(userName))
return False
else:
self.printSUCCESS(_("Disabled Samba user %s")%str(userName))
# включаем Samba account
if options.has_key('u'):
textLine = self.execProg("smbpasswd -e %s" %(userName))
if "Enabled user %s" %userName in textLine:
self.printSUCCESS(_("Enabled Samba user %s")%str(userName))
else:
if textLine == False:
self.printERROR(_("Can not enable Samba user")+ " "+\
str(userName))
return False
else:
self.printSUCCESS(_("Enabled Samba user %s")%str(userName))
if not options or options.has_key('s'):
optPasswd = {"p":""}
userPwd = self.getUserPassword(optPasswd, "p", False)
@ -6865,7 +6836,7 @@ Samba and Unix services") %", ".join(exclGroup)
return False
textLine = self.execProg("smbpasswd -a -s %s" %(userName),
"%s\n%s\n" %(userPwd,userPwd))
if not (textLine == None):
if textLine == False:
self.printERROR(_("Can not change Samba user password"))
return False
else:
@ -6890,21 +6861,21 @@ Samba and Unix services") %", ".join(exclGroup)
# отключаем Samba account
if options.has_key('L'):
textLine = self.execProg("smbpasswd -d %s" %(userName))
if "Disabled user %s" %userName in textLine:
self.printSUCCESS(_("Disabled Samba user %s")%str(userName))
else:
if textLine == False:
self.printERROR(_("Can not disable Samba user")+ " "+\
str(userName))
str(userName))
return False
else:
self.printSUCCESS(_("Disabled Samba user %s")%str(userName))
# включаем samba account
elif options.has_key('U'):
textLine = self.execProg("smbpasswd -e %s" %(userName))
if "Enabled user %s" %userName in textLine:
self.printSUCCESS(_("Enabled Samba user %s")%str(userName))
else:
if textLine == False:
self.printERROR(_("Can not enable Samba user")+ " "+\
str(userName))
return False
else:
self.printSUCCESS(_("Enabled Samba user %s")%str(userName))
# модифицируем пароль
if options.has_key('P') or options.has_key('p'):
pwDialog = [_("New SMB password"),
@ -6919,7 +6890,7 @@ Samba and Unix services") %", ".join(exclGroup)
return False
textLine = self.execProg("smbpasswd -s %s" %(userName),
"%s\n%s\n" %(userPwd,userPwd))
if not (textLine == None):
if textLine == False:
self.printERROR(_("Can not modify Samba user password"))
return False
self.printSUCCESS(_("Modified Samba user password"))
@ -6971,7 +6942,7 @@ Samba and Unix services") %", ".join(exclGroup)
class servLdap(shareLdap):
"""Методы севисa Ldap"""
notLdapServices = ["dhcp"]
# Базовый ldif файл
ldifFileBase = "/usr/lib/calculate/calculate-server/ldif/base.ldif"
# Для backup
@ -7526,6 +7497,93 @@ outdated. If the backup is obsolete, use cl-backup."))
clProf = cl_profile.profile(self.clVars)
return clProf.scanProfiles(serviceName)
def backupNotLdapServer(self):
"""Сохраняет только настройки установленных сервисов"""
# создаем директорию backup-а
if not os.path.exists(self.backupDirectory):
try:
os.makedirs(self.backupDirectory)
except os.IOError:
self.printERROR(_("Can not create directory") + ": " +\
str(self.backupDirectory))
return False
# генерируем название файла архива
strData = time.strftime("%Y%m%d%H%M%S",time.localtime(time.time()))
backupFile = "%s.tar.bz2" %strData
# если существуют удаляем файлы в /tmp
self.removeTmpFiles()
# находим установленные сервисы
servInstalled = self.getServiceSetup()
if not servInstalled:
self.printERROR("unable to create a backup")
self.printERROR("Services are not installed")
return False
listIncorrectServices = list(set(servInstalled)-\
set(self.notLdapServices))
if listIncorrectServices:
self.printERROR(_("LDAP service is not setup"))
self.printERROR(_("Services %s need LDAP service")\
%", ".join(listIncorrectServices))
self.printERROR(_("Can not create backup file"))
return False
# Все файлы которые нужно заархивировать
allArchFiles = []
flagError = False
for serviceName in servInstalled:
archFiles = self.scanServiceDirs(serviceName)
if archFiles == False:
flagError = True
break
allArchFiles += archFiles
if flagError:
self.printERROR("Error create list archive files")
return False
scanPrivDirs = []
# Cоздаем файловый объект
fileObj = cl_profile._file()
# Добавляем calculate.env
iniFiles = self.clVars.Get("cl_env_path")
if iniFiles:
for iniFile in iniFiles:
if os.path.exists(iniFile):
allArchFiles.append(iniFile)
profileDirs = self.clVars.Get("cl_profile_path")
if profileDirs:
profileDirs = profileDirs[1:]
for pDir in profileDirs:
if os.path.exists(pDir):
scanPrivDirs.append(pDir)
# Сканируем директории
if scanPrivDirs:
dirObjs = fileObj.scanDirs(scanPrivDirs)
for dirObj in dirObjs:
for archFile in dirObj.files:
allArchFiles.append(archFile)
allArchFiles = self.unicList(allArchFiles)
# Сохраняем файл список архивируемых файлов
if not self.savePrivateFile (self.tmpListFile,
"\n".join(allArchFiles)):
self.printERROR(_("Can not create list archive files") + ": " +\
str(self.tmpListFile))
return False
bFile = os.path.join(self.backupDirectory, backupFile)
strCmd = "tar --files-from=%s -cjf %s" %(self.tmpListFile, bFile)
retTar = self.execProg(strCmd)
if retTar == False:
self.printERROR(_('Can not execute "%s"')%strCmd)
return False
# если существуют удаляем файлы в /tmp
self.removeTmpFiles()
if os.path.exists(bFile):
os.chmod(bFile,0600)
self.printSUCCESS(_("Created archive file") + ": " +\
str(bFile))
return True
else:
self.printERROR(_("Can not create archive file") + ": " +\
str(bFile))
return False
def backupServer(self):
"""Сохраняет настройки установленных сервисов и базу LDAP"""
# создаем директорию backup-а
@ -7695,7 +7753,7 @@ service %s")%service
replArchFilesMail.append(ldapParser.nameIniFile)
# Добавляем calculate.env
iniFiles = self.clVars.Get("cl_env_path")
if iniFiles and len(iniFiles)>1:
if iniFiles:
for iniFile in iniFiles:
if os.path.exists(iniFile):
allArchFiles.append(iniFile)
@ -7941,8 +7999,11 @@ service %s")%service
str(self.archLdifFile))
return False
bFile = os.path.join(self.backupDirectory, backupFile)
self.execProg("tar --files-from=%s -cjf %s"\
%(self.tmpListFile, bFile))
strCmd = "tar --files-from=%s -cjf %s" %(self.tmpListFile, bFile)
retTar = self.execProg(strCmd)
if retTar == False:
self.printERROR(_('Can not execute "%s"')%strCmd)
return False
# если существуют удаляем файлы в /tmp
self.removeTmpFiles()
if os.path.exists(bFile):
@ -8012,8 +8073,12 @@ service %s")%service
if not bFile:
return False
# Получаем список файлов в архиве
textListFiles = self.execProg("tar -tjf %s" %bFile,False,False)
# <20>даляем из элементов переводы строк
strCmd = "tar -tjf %s" %bFile
textListFiles = self.execProg(strCmd,False,False)
if textListFiles == False:
self.printERROR(_('Can not execute "%s"')%strCmd)
return False
# удаляем из элементов переводы строк
archFiles = map(lambda x: "".join(x.split('\n')),textListFiles)
flagError = False
# Находим в списке файлов файлы списки для сервисов
@ -8059,8 +8124,8 @@ the extension '.env'")%bFile)
str(self.tmpEnvDir))
return False
# Разархивируем env файлы во временную директорию
if not (self.execProg("tar -C %s --files-from=%s -xjf %s"\
%(self.tmpEnvDir,self.tmpListFile, bFile)) == None):
if self.execProg("tar -C %s --files-from=%s -xjf %s"\
%(self.tmpEnvDir,self.tmpListFile, bFile)) == False:
self.printERROR(_("Can not extract archive") + ": " + str(bFile))
return False
# Создаем объект переменных clVars
@ -8140,7 +8205,8 @@ for running replication")%bFile)
if not self.stopServices(self.getALLServices()):
return False
# Удаляем старую базу данных
self.removeLdapDatabase()
if not self.removeLdapDatabase():
return False
# Накладываем профили (берем из папки backup)
if not self.applyProfilesFromService(self.backupDir):
self.printERROR(_("Can not apply profile")+ ": backup")
@ -8193,8 +8259,8 @@ for running replication")%bFile)
ldifFile = self.replArchLdifFileUnix
elif "mail" in replServices:
ldifFile = self.replArchLdifFileMail
if not (self.execProg("tar -C / --files-from=%s -xjf %s"\
%(self.tmpListFile, bFile)) == None):
if self.execProg("tar -C / --files-from=%s -xjf %s"\
%(self.tmpListFile, bFile)) == False:
self.printERROR(_("Can not extract archive") + ": " + str(bFile))
return False
if not os.path.exists(ldifFile):
@ -8232,14 +8298,13 @@ for running replication")%bFile)
self.printERROR(_("Not supported replication service %s")\
%replServices[0])
return False
if not (self.execProg("tar -C / --files-from=%s -xjf %s"\
%(listReplFile, bFile)) == None):
if self.execProg("tar -C / --files-from=%s -xjf %s"\
%(listReplFile, bFile)) == False:
self.printERROR(_("Can not extract archive") + ": "+str(bFile))
return False
else:
# Распаковываем целиком архив
if not (self.execProg("tar -C / -xjf %s"\
%(bFile)) == None):
if self.execProg("tar -C / -xjf %s" %(bFile)) == False:
self.printERROR(_("Can not extract archive") + ": "+str(bFile))
return False
# Удаляем временные файлы
@ -8296,8 +8361,13 @@ for running replication")%bFile)
def removeLdapDatabase(self):
"""Удаляем предыдущую базу данных"""
self.execProg("rm -rf /var/lib/openldap-data/*")
self.printOK(_("Erased LDAP Database") + " ...")
pathDatabase = "/var/lib/openldap-data"
if os.listdir(pathDatabase):
strCmd = "rm -rf %s/*"%pathDatabase
if self.execProg(strCmd) == False:
self.printERROR(_('Can not execute "%s"')%strCmd)
return False
self.printOK(_("Erased LDAP Database") + " ...")
return True
def connectLdapServer(self):
@ -8411,7 +8481,8 @@ for running replication")%bFile)
self.printERROR(_("Can not apply profiles") +":"+ _("first pass"))
return False
# Удаляем старую базу данных
self.removeLdapDatabase()
if not self.removeLdapDatabase():
return False
# Запускаем LDAP сервер
if not self.runLdapServer():
return False
@ -10664,16 +10735,13 @@ class servFtp(shareLdap):
# В случае если сервис Samba установлен перезапускаем его
if self.clVars.Get("sr_samba_set") == "on":
if self.getRunService('samba'):
textLines = self.execProg("/etc/init.d/samba restart",
False, False)
if not (textLines and type(textLines) == types.ListType and\
"ok" in textLines[-1] or textLines and "ok" in textLines):
textLines = self.execProg("/etc/init.d/samba restart")
if textLines == False:
self.printNotOK(_("Restarting") + " Samba ...")
return False
else:
textLines = self.execProg("/etc/init.d/samba start",False,False)
if not (textLines and type(textLines) == types.ListType and\
"ok" in textLines[-1] or textLines and "ok" in textLines):
textLines = self.execProg("/etc/init.d/samba start")
if textLines == False:
self.printNotOK(_("Starting") + " Samba ...")
return False
# Подключаемся к LDAP cерверу
@ -10707,15 +10775,14 @@ class servFtp(shareLdap):
self.printOK(_("Added ldif file") + " ...")
textLines = []
if self.getRunService('ftp'):
textLines = self.execProg("/etc/init.d/proftpd restart",False,False)
else:
textLines = self.execProg("/etc/init.d/proftpd start",False,False)
if textLines and type(textLines) == types.ListType and\
"ok" in textLines[-1] or textLines and "ok" in textLines:
self.printOK(_("Starting") + " " + "Proftpd" + " ...")
textLines = self.execProg("/etc/init.d/proftpd restart")
else:
textLines = self.execProg("/etc/init.d/proftpd start")
if textLines == False:
self.printNotOK(_("Starting") + " " + "Proftpd" + " ...")
return False
else:
self.printOK(_("Starting") + " " + "Proftpd" + " ...")
# Устанавливаем автозапуск демона
if not self.setDaemonAutostart("proftpd"):
return False
@ -11723,7 +11790,7 @@ if %%errorlevel%%==0 NET USE T: \\\\%s\\ftp' %(netbios,netbios,netbios)
if userMails:
# Внешний почтовый адрес пользователя (первый в списке)
userMail = userMails[0]
# Убираем первый адрес из списка
# Убирае<EFBFBD> первый адрес из списка
userMails = list(set(filter(lambda x: x != userMail,
userMails)))
attrAppend = []
@ -12127,7 +12194,11 @@ calculate-server")
"""Отключает в crontab обработку файла replcron"""
replCronFile = os.path.join("/usr/bin",self.replCronFile)
fileNameCron = tempfile.mktemp(".cron")
listCronLines = self.execProg("crontab -l",False,False)
strCmd = "crontab -l"
listCronLines = self.execProg(strCmd,False,False)
if not listCronLines:
self.printERROR(_('Can not execute "%s"')%strCmd)
return False
# Удаляем из элементов переводы строк
listCronLinesSrc = map(lambda x: x.split('\n')[0],listCronLines)
# Удаляем из элементов все начиная с #
@ -12156,7 +12227,7 @@ calculate-server")
"\n",
0,0)
textLine = self.execProg("crontab %s"%fileNameCron)
if not (textLine == None):
if textLine == False:
self.printERROR(_("Can not add crontab file"))
if os.path.exists(fileNameCron):
os.remove(fileNameCron)
@ -14520,13 +14591,12 @@ is not valid ") %accessPorts)
{"DN":self.clVars.Get("ld_proxy_dn"),
"PASS":self.clVars.Get("ld_proxy_pw")})
self.printOK(_("Added ldif file") + " ...")
textLines = self.execProg("/etc/init.d/squid start", False, False)
if textLines and type(textLines) == types.ListType and\
"ok" in textLines[-1] or textLines and "ok" in textLines:
self.printOK(_("Starting") + " " + "Squid" + " ...")
else:
textLines = self.execProg("/etc/init.d/squid start")
if textLines == False:
self.printNotOK(_("Starting") + " " + "Squid" + " ...")
return False
else:
self.printOK(_("Starting") + " " + "Squid" + " ...")
# Устанавливаем автозапуск демона
if not self.setDaemonAutostart("squid"):
return False
@ -16991,7 +17061,7 @@ is incompatible with option "--ip"')
# Изменяемая прямая зона
namesZones.append(zoneName)
# Увеличение серийного номера измененных зон
# Увеличение серийно<EFBFBD>о номера измененных зон
namesZones = list(set(namesZones))
flagError = False
for nameZone in namesZones:
@ -17465,7 +17535,7 @@ in LDAP")%zoneName)
allowNet = self.clVars.Get("os_net_allow")
if not forceOptions:
# предупреждение при выполнении этой программы будут изменены
# конфигурационные файлы сервиса Proxy (программa squid)
# конфигурационные файлы сервиса DNS (программa bind)
self.printWARNING (_("WARNING") + ": " +
_("Executing of the program will change") + " " +
_("the configuration files of DNS service") +" ("+
@ -17570,13 +17640,12 @@ in LDAP")%zoneName)
{"DN":self.clVars.Get("ld_dns_dn"),
"PASS":self.clVars.Get("ld_dns_pw")})
self.printOK(_("Added ldif file") + " ...")
textLines = self.execProg("/etc/init.d/named start", False, False)
if textLines and type(textLines) == types.ListType and\
"ok" in textLines[-1] or textLines and "ok" in textLines:
self.printOK(_("Starting") + " " + "Named" + " ...")
else:
textLines = self.execProg("/etc/init.d/named start")
if textLines == False:
self.printNotOK(_("Starting") + " " + "Named" + " ...")
return False
else:
self.printOK(_("Starting") + " " + "Named" + " ...")
# Устанавливаем автозапуск демона
if not self.setDaemonAutostart("named"):
return False
@ -17590,7 +17659,139 @@ in LDAP")%zoneName)
self.printOK(_("DNS service configured") + " ...")
return True
class servDhcp(shareLdap):
"""Методы сервиса DHCP"""
def __init__(self):
shareLdap.__init__(self)
def setupDhcpServer(self, options):
"""Начальная настройка DHCP сервиса"""
# Принудительная установка
forceOptions = False
if options.has_key("f"):
forceOptions = True
# Создаем объект переменных
self.createClVars()
# В случае если сервер установлен
if self.clVars.Get("sr_dhcp_set") == "on" and not forceOptions:
self.printWARNING (_("WARNING") + ": " +\
_("DHCP server is configured")+ ".")
return True
if not forceOptions:
# предупреждение при выполнении этой программы будут изменены
# конфигурационные файлы сервиса DHCP (программa dhcpd)
self.printWARNING (_("WARNING") + ": " +
_("Executing of the program will change") + " " +
_("the configuration files of DHCP service") +" ("+
_("program dhcpd") + ")." )
# если вы готовы продолжить работу программы нажмите Y если нет n
messDialog = \
_("If you are ready to continue executing the program") + ", "+\
_("input 'yes'") +", "+ _("if not 'no'")
if not self.dialogYesNo(messDialog):
return True
else:
# делаем backup
# Проверим запущен ли ldap
if not self.getRunService("ldap"):
# Запускаем LDAP сервер
if not self.runLdapServer():
return False
bakupObj = servLdap()
bakupObj.backupServer()
# Удаляем переменные сервиса в ini файлах
self.deleteServiceVarsInFile("dns")
# Cоздаем объект переменные
self.createClVars()
# Устанавливаем доступные сети
self.clVars.Set("sr_dns_net_allow", allowNet, True)
# Удаляем из автозапуска демона
if not self.delDaemonAutostart("named"):
return False
# останавливаем сервис DNS
if not self.stopServices(["dns"]):
return False
# Имя устанавливаемого сервиса
self.clVars.Set("cl_pass_service","dns")
self.clVars.Write("sr_dns_set","off")
# Cоздаем объект профиль устанавливая директорию proxy для
# файлов профилей
if not self.applyProfilesFromService('dns'):
return False
# Удаляем ненужные текстовые зоны
objTxtZone = dnsZoneTxt()
delZonesNames = objTxtZone.getAllNamesZones()
relList = map(lambda x: objTxtZone.deleteZone(x), delZonesNames)
flagDelError = False
i = 0
for ret in relList:
if not ret:
flagDelError = True
break
i += 1
if flagDelError:
self.printERROR(\
_('Can not delete DNS zone "%s"')%delZonesNames[i] + " " +\
_("in file %s")%objTxtZone.nameConfigFile)
return False
map(lambda x :\
self.printOK(_('Deleted DNS zone "%s"')%x + " " +\
_("in file %s")%objTxtZone.nameConfigFile)\
,delZonesNames)
# Проверим запущен ли ldap
if not self.getRunService("ldap"):
# Запускаем LDAP сервер
if not self.runLdapServer():
return False
else:
if not self.restartLdapServer():
return False
# Подключаемся к LDAP cерверу
if not shareLdap.getLdapObjInFile(self):
return False
# Находим в LDAP DNS сервис
resSearch = self.searchService()
ret = True
if resSearch:
delDN = self.relDN
ret = self.deleteDN(delDN)
if ret:
self.printOK(_("Remove DNS DN from LDAP Database") + " ...")
else:
self.printERROR(_("Can not remove DNS DN from LDAP Database"))
if not ret:
return False
ldifFile = self.ldifFileBase
baseLdif = self.createLdif(ldifFile)
if not self.ldapObj.getError():
self.ldapObj.ldapAdd(baseLdif)
if self.ldapObj.getError():
print _("LDAP Error") + ": " + self.ldapObj.getError().strip()
return False
# Записываем данные администратора сервиса Proxy
ldapParser = iniLdapParser()
ldapParser.setVar("dns",
{"DN":self.clVars.Get("ld_dns_dn"),
"PASS":self.clVars.Get("ld_dns_pw")})
self.printOK(_("Added ldif file") + " ...")
textLines = self.execProg("/etc/init.d/named start")
if textLines == False:
self.printNotOK(_("Starting") + " " + "Named" + " ...")
return False
else:
self.printOK(_("Starting") + " " + "Named" + " ...")
# Устанавливаем автозапуск демона
if not self.setDaemonAutostart("named"):
return False
# запишем переменные для сервера
allow = self.clVars.Get("sr_dns_net_allow")
self.clVars.Write("sr_dns_net_allow",allow,True,"local")
# запишем переменные для клиента
#
# Запишем, что сервис установлен
self.clVars.Write("sr_dns_set","on")
self.printOK(_("DNS service configured") + " ...")
return True
class tsOpt(cl_base.opt):
"""Класс для обработки параметров и вывода help

@ -204,7 +204,7 @@ class Data:
'value':'/var/calculate/server-backup/deleted'}
#-----------------------------------------------------
#Сервис Unix
# Сервис Unix
#-----------------------------------------------------
#DN администратора сервиса Unix (он, же DN сервиса)
ld_unix_dn = {}
@ -223,7 +223,7 @@ class Data:
'value':'off'}
#-----------------------------------------------------
#Сервис Samba
# Сервис Samba
#-----------------------------------------------------
#DN администратора сервиса Samba (он, же DN сервиса)
ld_samba_dn = {}
@ -262,7 +262,7 @@ class Data:
'value':'off'}
#-----------------------------------------------------
#Сервис Mail
# Сервис Mail
#-----------------------------------------------------
#DN администратора сервиса Mail (он, же DN сервиса)
ld_mail_dn = {}
@ -284,7 +284,7 @@ class Data:
'value':'off'}
#-----------------------------------------------------
#Сервис Jabber
# Сервис Jabber
#-----------------------------------------------------
#DN администратора сервиса Jabber (он, же DN сервиса)
ld_jabber_dn = {}
@ -303,7 +303,7 @@ class Data:
'value':'off'}
#-----------------------------------------------------
#Сервис FTP
# Сервис FTP
#-----------------------------------------------------
# имя компьютера с настроенным сервисом FTP
cl_remote_ftp = {}
@ -328,7 +328,7 @@ class Data:
sr_ftp_path = {'value':'/var/calculate/server-data/ftp'}
#-----------------------------------------------------
#Сервис Proxy
# Сервис Proxy
#-----------------------------------------------------
# имя компьютера с настроенным сервисом Proxy
sr_proxy_host = {}
@ -437,9 +437,9 @@ class Data:
#Настроен или нет сервис Mail как почтовый релей
sr_mail_relay_set = {'mode':"w",
'value':'off'}
#-----------------------------------------------------
#Сервис DNS
# Сервис DNS
#-----------------------------------------------------
# имя компьютера с настроенным сервисом DNS
sr_dns_host = {}
@ -459,4 +459,10 @@ class Data:
#Настроен или нет сервис DNS
sr_dns_set = {'mode':"w",
'value':'off'}
#-----------------------------------------------------
# Сервис DHCP
#-----------------------------------------------------
#Настроен или нет сервис DHCP
sr_dhcp_set = {'mode':"w",
'value':'off'}
Loading…
Cancel
Save