def secure_auth(self): """This function Secures authentication""" passwd = ''.join([ random.choice(string.ascii_letters + string.digits) for n in range(6) ]) if not self.app.pargs.user_input: username = input("Provide HTTP authentication user " "name [{0}] :".format(SSSVariables.sss_user)) self.app.pargs.user_input = username if username == "": self.app.pargs.user_input = SSSVariables.sss_user if not self.app.pargs.user_pass: password = getpass.getpass("Provide HTTP authentication " "password [{0}] :".format(passwd)) self.app.pargs.user_pass = password if password == "": self.app.pargs.user_pass = passwd Log.debug( self, "printf username:"******"$(openssl passwd -crypt " "password 2> /dev/null)\n\"" "> /etc/apache2/htpasswd-sss 2>/dev/null") SSSShellExec.cmd_exec(self, "printf \"{username}:" "$(openssl passwd -crypt " "{password} 2> /dev/null)\n\"" "> /etc/apache2/htpasswd-sss 2>/dev/null".format( username=self.app.pargs.user_input, password=self.app.pargs.user_pass), log=False) SSSGit.add(self, ["/etc/apache2"], msg="Adding changed secure auth into Git")
def remove(self, ppa=None, repo_url=None): """ This function used to remove ppa's If ppa is provided adds repo file to /etc/apt/sources.list.d/ command. """ if ppa: SSSShellExec.cmd_exec( self, "add-apt-repository -y " "--remove '{ppa_name}'".format(ppa_name=ppa)) elif repo_url: repo_file_path = ("/etc/apt/sources.list.d/" + SSSVariables().sss_repo_file) try: repofile = open(repo_file_path, "w+") repofile.write(repofile.read().replace(repo_url, "")) repofile.close() except IOError as e: Log.debug(self, "{0}".format(e)) Log.error(self, "File I/O error.") except Exception as e: Log.debug(self, "{0}".format(e)) Log.error(self, "Unable to remove repo")
def setwebrootpermissions(self, webroot): Log.debug(self, "Setting up permissions") try: SSSFileUtils.chown(self, webroot, SSSVariables.sss_php_user, SSSVariables.sss_php_user, recursive=True) except Exception as e: Log.debug(self, str(e)) raise SiteError("problem occured while setting up webroot permissions")
def removeApacheConf(self, domain): if os.path.isfile("/etc/apache2/sites-available/{0}.conf".format(domain)): Log.debug(self, "Removing Apache configuration") SSSFileUtils.rm(self, "/etc/apache2/sites-enabled/{0}.conf".format(domain)) SSSFileUtils.rm(self, "/etc/apache2/sites-available/{0}.conf".format(domain)) SSSService.reload_service(self, "apache2") SSSGit.add(self, ["/etc/apache2"], msg="Deleted {0} ".format(domain))
def add(self, paths, msg="Intializating"): """ Initializes Directory as repository if not already git repo. and adds uncommited changes automatically """ for path in paths: global git git = git.bake("--git-dir={0}/.git".format(path), "--work-tree={0}".format(path)) if os.path.isdir(path): if not os.path.isdir(path + "/.git"): try: Log.debug(self, "SSS Git: git init at {0}".format(path)) git.init(path) except ErrorReturnCode as e: Log.debug(self, "{0}".format(e)) Log.error(self, "Unable to git init at {0}".format(path)) status = git.status("-s") if len(status.splitlines()) > 0: try: Log.debug(self, "SSS Git: git commit at {0}".format(path)) git.add("--all") git.commit("-am {0}".format(msg)) except ErrorReturnCode as e: Log.debug(self, "{0}".format(e)) Log.error(self, "Unable to git commit at {0} ".format(path)) else: Log.debug(self, "SSS Git: Path {0} not present".format(path))
def reload_service(self, service_name): """ Stop service Similar to `service xyz stop` """ try: if service_name in ['php5-fpm']: service_cmd = ( '{0} -t && service {0} reload'.format(service_name)) else: service_cmd = ('service {0} reload'.format(service_name)) Log.info(self, "Reload : {0:10}".format(service_name), end='') retcode = subprocess.getstatusoutput(service_cmd) if retcode[0] == 0: Log.info(self, "[" + Log.ENDC + "OK" + Log.OKGREEN + "]") return True else: Log.debug(self, "{0}".format(retcode[1])) Log.info(self, "[" + Log.FAIL + "Failed" + Log.OKGREEN + "]") return False except OSError as e: Log.debug(self, "{0}".format(e)) Log.error(self, "\nFailed to reload service {0}".format(service_name))
def remove(self, ppa=None, repo_url=None): """ This function used to remove ppa's If ppa is provided adds repo file to /etc/apt/sources.list.d/ command. """ if ppa: SSSShellExec.cmd_exec(self, "add-apt-repository -y " "--remove '{ppa_name}'" .format(ppa_name=ppa)) elif repo_url: repo_file_path = ("/etc/apt/sources.list.d/" + SSSVariables().sss_repo_file) try: repofile = open(repo_file_path, "w+") repofile.write(repofile.read().replace(repo_url, "")) repofile.close() except IOError as e: Log.debug(self, "{0}".format(e)) Log.error(self, "File I/O error.") except Exception as e: Log.debug(self, "{0}".format(e)) Log.error(self, "Unable to remove repo")
def reload_service(self, service_name): """ Stop service Similar to `service xyz stop` """ try: if service_name in ['php5-fpm']: service_cmd = ('{0} -t && service {0} reload' .format(service_name)) else: service_cmd = ('service {0} reload'.format(service_name)) Log.info(self, "Reload : {0:10}".format(service_name), end='') retcode = subprocess.getstatusoutput(service_cmd) if retcode[0] == 0: Log.info(self, "[" + Log.ENDC + "OK" + Log.OKGREEN + "]") return True else: Log.debug(self, "{0}".format(retcode[1])) Log.info(self, "[" + Log.FAIL + "Failed" + Log.OKGREEN+"]") return False except OSError as e: Log.debug(self, "{0}".format(e)) Log.error(self, "\nFailed to reload service {0}" .format(service_name))
def secure_auth(self): """This function Secures authentication""" passwd = ''.join([random.choice (string.ascii_letters + string.digits) for n in range(6)]) if not self.app.pargs.user_input: username = input("Provide HTTP authentication user " "name [{0}] :".format(SSSVariables.sss_user)) self.app.pargs.user_input = username if username == "": self.app.pargs.user_input = SSSVariables.sss_user if not self.app.pargs.user_pass: password = getpass.getpass("Provide HTTP authentication " "password [{0}] :".format(passwd)) self.app.pargs.user_pass = password if password == "": self.app.pargs.user_pass = passwd Log.debug(self, "printf username:"******"$(openssl passwd -crypt " "password 2> /dev/null)\n\"" "> /etc/apache2/htpasswd-sss 2>/dev/null") SSSShellExec.cmd_exec(self, "printf \"{username}:" "$(openssl passwd -crypt " "{password} 2> /dev/null)\n\"" "> /etc/apache2/htpasswd-sss 2>/dev/null" .format(username=self.app.pargs.user_input, password=self.app.pargs.user_pass), log=False) SSSGit.add(self, ["/etc/apache2"], msg="Adding changed secure auth into Git")
def addNewSite(self, site, stype, cache, path, enabled=True, ssl=False, fs='ext4', db='mysql', db_name=None, db_user=None, db_password=None, db_host='localhost', hhvm=0, pagespeed=0): """ Add New Site record information into sss database. """ try: newRec = SiteDB(site, stype, cache, path, enabled, ssl, fs, db, db_name, db_user, db_password, db_host, hhvm, pagespeed) db_session.add(newRec) db_session.commit() except Exception as e: Log.debug(self, "{0}".format(e)) Log.error(self, "Unable to add site to database")
def invoke_editor(self, filepath, errormsg=''): """ Open files using sensible editor """ try: subprocess.call(['sensible-editor', filepath]) except OSError as e: Log.debug(self, "{0}{1}".format(e.errno, e.strerror)) raise CommandExecutionError
def removeApacheConf(self, domain): if os.path.isfile('/etc/apache2/sites-available/{0}.conf'.format(domain)): Log.debug(self, "Removing Apache configuration") SSSFileUtils.rm(self, '/etc/apache2/sites-enabled/{0}.conf'.format(domain)) SSSFileUtils.rm(self, '/etc/apache2/sites-available/{0}.conf'.format(domain)) SSSService.reload_service(self, 'apache2') SSSGit.add(self, ["/etc/apache2"], msg="Deleted {0} ".format(domain))
def remove_symlink(self, filepath): """ Removes symbolic link for the path provided with filepath """ try: Log.debug(self, "Removing symbolic link: {0}".format(filepath)) os.unlink(filepath) except Exception as e: Log.debug(self, "{0}".format(e)) Log.error(self, "Unable to reomove symbolic link ...\n")
def getAllsites(self): """ 1. returns all records from sss database """ try: q = SiteDB.query.all() return q except Exception as e: Log.debug(self, "{0}".format(e)) Log.error(self, "Unable to query database")
def getSiteInfo(self, site): """ Retrieves site record from sss databse """ try: q = SiteDB.query.filter(SiteDB.sitename == site).first() return q except Exception as e: Log.debug(self, "{0}".format(e)) Log.error(self, "Unable to query database for site info")
def check_db_exists(self, db_name): try: if SSSMysql.dbConnection(self, db_name): return True except DatabaseNotExistsError as e: Log.debug(self, str(e)) return False except MySQLConnectionError as e: Log.debug(self, str(e)) raise MySQLConnectionError
def auto_remove(self): """ Similar to `apt-get autoremove` """ try: Log.debug(self, "Running apt-get autoremove") apt_get.autoremove("-y") except ErrorReturnCode as e: Log.debug(self, "{0}".format(e)) Log.error(self, "Unable to apt-get autoremove")
def pre_run_checks(self): # Check Apache configuration Log.info(self, "Running pre-update checks, please wait...") try: Log.debug(self, "checking Apache configuration ...") FNULL = open("/dev/null", "w") ret = subprocess.check_call(["apachectl", "configtest"], stdout=FNULL, stderr=subprocess.STDOUT) except CalledProcessError as e: Log.debug(self, "{0}".format(str(e))) raise SiteError("Apache configuration check failed.")
def updateSiteInfo(self, site, stype='', cache='', webroot='', enabled=True, ssl=False, fs='', db='', db_name=None, db_user=None, db_password=None, db_host=None, hhvm=None, pagespeed=None): """updates site record in database""" try: q = SiteDB.query.filter(SiteDB.sitename == site).first() except Exception as e: Log.debug(self, "{0}".format(e)) Log.error(self, "Unable to query database for site info") if not q: Log.error(self, "{0} does not exist in database".format(site)) # Check if new record matches old if not then only update database if stype and q.site_type != stype: q.site_type = stype if cache and q.cache_type != cache: q.cache_type = cache if q.is_enabled != enabled: q.is_enabled = enabled if ssl and q.is_ssl != ssl: q.is_ssl = ssl if db_name and q.db_name != db_name: q.db_name = db_name if db_user and q.db_user != db_user: q.db_user = db_user if db_user and q.db_password != db_password: q.db_password = db_password if db_host and q.db_host != db_host: q.db_host = db_host if webroot and q.site_path != webroot: q.site_path = webroot if (hhvm is not None) and (q.is_hhvm is not hhvm): q.is_hhvm = hhvm if (pagespeed is not None) and (q.is_pagespeed is not pagespeed): q.is_pagespeed = pagespeed try: q.created_on = func.now() db_session.commit() except Exception as e: Log.debug(self, "{0}".format(e)) Log.error(self, "Unable to update site info in application database.")
def chdir(self, path): """ Change Directory to path specified Path : path for destination directory """ try: Log.debug(self, "Changing directory to {0}".format(path)) os.chdir(path) except OSError as e: Log.debug(self, "{err}".format(err=e.strerror)) Log.error(self, 'Unable to Change Directory {0}'.format(path))
def extract(self, file, path): """Function to extract tar.gz file""" try: tar = tarfile.open(file) tar.extractall(path=path) tar.close() os.remove(file) return True except tarfile.TarError as e: Log.debug(self, "{0}".format(e)) Log.error(self, "Unable to extract file \{0}".format(file)) return False
def extract(self, file, path): """Function to extract tar.gz file""" try: tar = tarfile.open(file) tar.extractall(path=path) tar.close() os.remove(file) return True except tarfile.TarError as e: Log.debug(self, "{0}".format(e)) Log.error(self, 'Unable to extract file \{0}'.format(file)) return False
def chdir(self, path): """ Change Directory to path specified Path : path for destination directory """ try: Log.debug(self, "Changing directory to {0}" .format(path)) os.chdir(path) except OSError as e: Log.debug(self, "{err}".format(err=e.strerror)) Log.error(self, 'Unable to Change Directory {0}'.format(path))
def mkdir(self, path): """ create directories. path : path for directory to be created Similar to `mkdir -p` """ try: Log.debug(self, "Creating directories: {0}".format(path)) os.makedirs(path) except OSError as e: Log.debug(self, "{0}".format(e.strerror)) Log.error(self, "Unable to create directory {0} ".format(path))
def isexist(self, path): """ Check if file exist on given path """ try: if os.path.exists(path): return (True) else: return (False) except OSError as e: Log.debug(self, "{0}".format(e.strerror)) Log.error(self, "Unable to check path {0}".format(path))
def auto_clean(self): """ Similar to `apt-get autoclean` """ try: orig_out = sys.stdout sys.stdout = open(self.app.config.get("log.logging", "file"), encoding="utf-8", mode="a") apt_get.autoclean("-y") sys.stdout = orig_out except ErrorReturnCode as e: Log.debug(self, "{0}".format(e)) Log.error(self, "Unable to apt-get autoclean")
def mvfile(self, src, dst): """ Moves file from source path to destination path src : source path dst : Destination path """ try: Log.debug(self, "Moving file from {0} to {1}".format(src, dst)) shutil.move(src, dst) except Exception as e: Log.debug(self, "{err}".format(err=e)) Log.error(self, 'Unable to move file from {0} to {1}'.format(src, dst))
def pre_run_checks(self): # Check Apache configuration Log.info(self, "Running pre-update checks, please wait...") try: Log.debug(self, "checking Apache configuration ...") FNULL = open('/dev/null', 'w') ret = subprocess.check_call(["apachectl", "configtest"], stdout=FNULL, stderr=subprocess.STDOUT) except CalledProcessError as e: Log.debug(self, "{0}".format(str(e))) raise SiteError("Apache configuration check failed.")
def mvfile(self, src, dst): """ Moves file from source path to destination path src : source path dst : Destination path """ try: Log.debug(self, "Moving file from {0} to {1}".format(src, dst)) shutil.move(src, dst) except Exception as e: Log.debug(self, "{err}".format(err=e)) Log.error(self, 'Unable to move file from {0} to {1}' .format(src, dst))
def mkdir(self, path): """ create directories. path : path for directory to be created Similar to `mkdir -p` """ try: Log.debug(self, "Creating directories: {0}" .format(path)) os.makedirs(path) except OSError as e: Log.debug(self, "{0}".format(e.strerror)) Log.error(self, "Unable to create directory {0} ".format(path))
def auto_clean(self): """ Similar to `apt-get autoclean` """ try: orig_out = sys.stdout sys.stdout = open(self.app.config.get('log.logging', 'file'), encoding='utf-8', mode='a') apt_get.autoclean("-y") sys.stdout = orig_out except ErrorReturnCode as e: Log.debug(self, "{0}".format(e)) Log.error(self, "Unable to apt-get autoclean")
def grep(self, fnm, sstr): """ Searches for string in file and returns the matched line. """ try: Log.debug(self, "Finding string {0} to file {1}".format(sstr, fnm)) for line in open(fnm, encoding='utf-8'): if sstr in line: return line return False except OSError as e: Log.debug(self, "{0}".format(e.strerror)) Log.error(self, "Unable to Search string {0} in {1}".format(sstr, fnm))
def connect(self): """Makes connection with MySQL server""" try: if os.path.exists('/etc/mysql/conf.d/my.cnf'): connection = pymysql.connect(read_default_file='/etc/mysql/conf.d/my.cnf') else: connection = pymysql.connect(read_default_file='~/.my.cnf') return connection except ValueError as e: Log.debug(self, str(e)) raise MySQLConnectionError except pymysql.err.InternalError as e: Log.debug(self, str(e)) raise MySQLConnectionError
def grep(self, fnm, sstr): """ Searches for string in file and returns the matched line. """ try: Log.debug(self, "Finding string {0} to file {1}" .format(sstr, fnm)) for line in open(fnm, encoding='utf-8'): if sstr in line: return line return False except OSError as e: Log.debug(self, "{0}".format(e.strerror)) Log.error(self, "Unable to Search string {0} in {1}" .format(sstr, fnm))
def connect(self): """Makes connection with MySQL server""" try: if os.path.exists('/etc/mysql/conf.d/my.cnf'): connection = pymysql.connect( read_default_file='/etc/mysql/conf.d/my.cnf') else: connection = pymysql.connect(read_default_file='~/.my.cnf') return connection except ValueError as e: Log.debug(self, str(e)) raise MySQLConnectionError except pymysql.err.InternalError as e: Log.debug(self, str(e)) raise MySQLConnectionError
def remove(self): """Start removal of packages""" apt_packages = [] packages = [] # Default action for stack remove if ((not self.app.pargs.web) and (not self.app.pargs.apache2) and (not self.app.pargs.php) and (not self.app.pargs.mysql)): self.app.pargs.web = True self.app.pargs.apache2 = True self.app.pargs.php = True self.app.pargs.mysql = True if self.app.pargs.all: self.app.pargs.web = True self.app.pargs.apache2 = True self.app.pargs.php = True self.app.pargs.mysql = True if self.app.pargs.web: self.app.pargs.apache2 = True self.app.pargs.php = True self.app.pargs.mysql = True #self.app.pargs.wpcli = True #self.app.pargs.postfix = True if self.app.pargs.apache2: Log.debug(self,"Removing apt_packages variable of Apache") apt_packages = apt_packages + SSSVariables.sss_apache if self.app.pargs.php: Log.debug(self,"Removing apt_packages variable of PHP") apt_packages = apt_packages + SSSVariables.sss_php if self.app.pargs.mysql: Log.debug(self,"Removing apt_packages variable of PHP") apt_packages = apt_packages + SSSVariables.sss_mysql packages = packages + ['/usr/bin/tuning-primer'] if len(packages) or len(apt_packages): sss_prompt = input('Are you sure you to want to' ' remove from server.' '\nPackage configuration will remain' ' on server after this operation.\n' 'Any answer other than ' '"yes" will be stop this' ' operation : ') if sss_prompt == 'YES' or sss_prompt == 'yes': if len(packages): SSSFileUtils.remove(self, packages) SSSAptGet.auto_remove(self) if len(apt_packages): Log.debug(self, "Removing apt_packages") Log.info(self, "Removing packages, please wait...") SSSAptGet.remove(self, apt_packages) SSSAptGet.auto_remove(self) Log.info(self, "Successfully removed packages")
def remove(self): """Start removal of packages""" apt_packages = [] packages = [] # Default action for stack remove if ((not self.app.pargs.web) and (not self.app.pargs.apache2) and (not self.app.pargs.php) and (not self.app.pargs.mysql)): self.app.pargs.web = True self.app.pargs.apache2 = True self.app.pargs.php = True self.app.pargs.mysql = True if self.app.pargs.all: self.app.pargs.web = True self.app.pargs.apache2 = True self.app.pargs.php = True self.app.pargs.mysql = True if self.app.pargs.web: self.app.pargs.apache2 = True self.app.pargs.php = True self.app.pargs.mysql = True #self.app.pargs.wpcli = True #self.app.pargs.postfix = True if self.app.pargs.apache2: Log.debug(self, "Removing apt_packages variable of Apache") apt_packages = apt_packages + SSSVariables.sss_apache if self.app.pargs.php: Log.debug(self, "Removing apt_packages variable of PHP") apt_packages = apt_packages + SSSVariables.sss_php if self.app.pargs.mysql: Log.debug(self, "Removing apt_packages variable of PHP") apt_packages = apt_packages + SSSVariables.sss_mysql packages = packages + ['/usr/bin/tuning-primer'] if len(packages) or len(apt_packages): sss_prompt = input('Are you sure you to want to' ' remove from server.' '\nPackage configuration will remain' ' on server after this operation.\n' 'Any answer other than ' '"yes" will be stop this' ' operation : ') if sss_prompt == 'YES' or sss_prompt == 'yes': if len(packages): SSSFileUtils.remove(self, packages) SSSAptGet.auto_remove(self) if len(apt_packages): Log.debug(self, "Removing apt_packages") Log.info(self, "Removing packages, please wait...") SSSAptGet.remove(self, apt_packages) SSSAptGet.auto_remove(self) Log.info(self, "Successfully removed packages")
def deleteSiteInfo(self, site): """Delete site record in database""" try: q = SiteDB.query.filter(SiteDB.sitename == site).first() except Exception as e: Log.debug(self, "{0}".format(e)) Log.error(self, "Unable to query database") if not q: Log.error(self, "{0} does not exist in database".format(site)) try: db_session.delete(q) db_session.commit() except Exception as e: Log.debug(self, "{0}".format(e)) Log.error(self, "Unable to delete site from application database.")
def stop(self): """Stop services""" services = [] if not (self.app.pargs.apache2 or self.app.pargs.php or self.app.pargs.mysql or self.app.pargs.memcache): self.app.pargs.apache2 = True self.app.pargs.php = True self.app.pargs.mysql = True if self.app.pargs.apache2: if SSSAptGet.is_installed(self, 'apache2'): services = services + ['apache2'] else: Log.info(self, 'Apache is not installed') if self.app.pargs.php: if SSSAptGet.is_installed(self, 'php7.0-fpm'): services = services + ['php7.0-fpm'] else: Log.info(self, "PHP7-FPM is not installed") if self.app.pargs.mysql: if ((SSSVariables.sss_mysql_host is "localhost") or (SSSVariables.sss_mysql_host is "127.0.0.1")): if (SSSAptGet.is_installed(self, 'mysql-server') or SSSAptGet.is_installed(self, 'percona-server-server-5.6') or SSSAptGet.is_installed(self, 'mariadb-server')): services = services + ['mysql'] else: Log.info(self, "MySQL is not installed") else: Log.warn( self, "Remote MySQL found, " "Unable to check MySQL service status") if self.app.pargs.memcache: if SSSAptGet.is_installed(self, 'memcached'): services = services + ['memcached'] else: Log.info(self, "Memcache is not installed") for service in services: Log.debug(self, "Stopping service: {0}".format(service)) SSSService.stop_service(self, service)
def cmd_exec(self, command, errormsg='', log=True): """Run shell command from Python""" try: log and Log.debug(self, "Running command: {0}".format(command)) with subprocess.Popen([command], stdout=subprocess.PIPE, stderr=subprocess.PIPE, shell=True) as proc: (cmd_stdout_bytes, cmd_stderr_bytes) = proc.communicate() (cmd_stdout, cmd_stderr) = (cmd_stdout_bytes.decode('utf-8', "replace"), cmd_stderr_bytes.decode('utf-8', "replace")) if proc.returncode == 0: return True else: Log.debug( self, "Command Output: {0}, \nCommand Error: {1}".format( cmd_stdout, cmd_stderr)) return False except OSError as e: Log.debug(self, str(e)) raise CommandExecutionError except Exception as e: Log.debug(self, str(e)) raise CommandExecutionError
def cmd_exec(self, command, errormsg='', log=True): """Run shell command from Python""" try: log and Log.debug(self, "Running command: {0}".format(command)) with subprocess.Popen([command], stdout=subprocess.PIPE, stderr=subprocess.PIPE, shell=True) as proc: (cmd_stdout_bytes, cmd_stderr_bytes) = proc.communicate() (cmd_stdout, cmd_stderr) = (cmd_stdout_bytes.decode('utf-8', "replace"), cmd_stderr_bytes.decode('utf-8', "replace")) if proc.returncode == 0: return True else: Log.debug(self, "Command Output: {0}, \nCommand Error: {1}" .format(cmd_stdout, cmd_stderr)) return False except OSError as e: Log.debug(self, str(e)) raise CommandExecutionError except Exception as e: Log.debug(self, str(e)) raise CommandExecutionError
def searchreplace(self, fnm, sstr, rstr): """ Search replace strings in file fnm : filename sstr: search string rstr: replace string """ try: Log.debug(self, "Doning search and replace, File:{0}," "Source string:{1}, Dest String:{2}" .format(fnm, sstr, rstr)) for line in fileinput.input(fnm, inplace=True): print(line.replace(sstr, rstr), end='') fileinput.close() except Exception as e: Log.debug(self, "{0}".format(e)) Log.error(self, "Unable to search {0} and replace {1} {2}" .format(fnm, sstr, rstr))
def remove(self, filelist): """remove files from given path""" for file in filelist: if os.path.isfile(file): Log.info(self, "Removing {0:65}".format(file), end=' ') os.remove(file) Log.info(self, "{0}".format("[" + Log.ENDC + "Done" + Log.OKGREEN + "]")) Log.debug(self, 'file Removed') if os.path.isdir(file): try: Log.info(self, "Removing {0:65}".format(file), end=' ') shutil.rmtree(file) Log.info(self, "{0}".format("[" + Log.ENDC + "Done" + Log.OKGREEN + "]")) except shutil.Error as e: Log.debug(self, "{err}".format(err=str(e.reason))) Log.error(self, 'Unable to Remove file ')
def get_service_status(self, service_name): try: is_exist = subprocess.getstatusoutput('which {0}' .format(service_name)) if is_exist[0] == 0 or service_name in ['php7.0-fpm']: retcode = subprocess.getstatusoutput('service {0} status' .format(service_name)) if retcode[0] == 0: return True else: Log.debug(self, "{0}".format(retcode[1])) return False else: return False except OSError as e: Log.debug(self, "{0}{1}".format(e.errno, e.strerror)) Log.error(self, "Unable to get services status of {0}" .format(service_name)) return False
def searchreplace(self, fnm, sstr, rstr): """ Search replace strings in file fnm : filename sstr: search string rstr: replace string """ try: Log.debug( self, "Doning search and replace, File:{0}," "Source string:{1}, Dest String:{2}".format(fnm, sstr, rstr)) for line in fileinput.input(fnm, inplace=True): print(line.replace(sstr, rstr), end='') fileinput.close() except Exception as e: Log.debug(self, "{0}".format(e)) Log.error( self, "Unable to search {0} and replace {1} {2}".format( fnm, sstr, rstr))
def stop(self): """Stop services""" services = [] if not (self.app.pargs.apache2 or self.app.pargs.php or self.app.pargs.mysql or self.app.pargs.memcache): self.app.pargs.apache2 = True self.app.pargs.php = True self.app.pargs.mysql = True if self.app.pargs.apache2: if SSSAptGet.is_installed(self,'apache2'): services = services + ['apache2'] else: Log.info(self,'Apache is not installed') if self.app.pargs.php: if SSSAptGet.is_installed(self, 'php7.0-fpm'): services = services + ['php7.0-fpm'] else: Log.info(self, "PHP7-FPM is not installed") if self.app.pargs.mysql: if ((SSSVariables.sss_mysql_host is "localhost") or (SSSVariables.sss_mysql_host is "127.0.0.1")): if (SSSAptGet.is_installed(self, 'mysql-server') or SSSAptGet.is_installed(self, 'percona-server-server-5.6') or SSSAptGet.is_installed(self, 'mariadb-server')): services = services + ['mysql'] else: Log.info(self, "MySQL is not installed") else: Log.warn(self, "Remote MySQL found, " "Unable to check MySQL service status") if self.app.pargs.memcache: if SSSAptGet.is_installed(self, 'memcached'): services = services + ['memcached'] else: Log.info(self, "Memcache is not installed") for service in services: Log.debug(self, "Stopping service: {0}".format(service)) SSSService.stop_service(self, service)
def remove(self, filelist): """remove files from given path""" for file in filelist: if os.path.isfile(file): Log.info(self, "Removing {0:65}".format(file), end=' ') os.remove(file) Log.info( self, "{0}".format("[" + Log.ENDC + "Done" + Log.OKGREEN + "]")) Log.debug(self, 'file Removed') if os.path.isdir(file): try: Log.info(self, "Removing {0:65}".format(file), end=' ') shutil.rmtree(file) Log.info( self, "{0}".format("[" + Log.ENDC + "Done" + Log.OKGREEN + "]")) except shutil.Error as e: Log.debug(self, "{err}".format(err=str(e.reason))) Log.error(self, 'Unable to Remove file ')
def stop_service(self, service_name): """ Stop service Similar to `service xyz stop` """ try: Log.info(self, "Stop : {0:10}".format(service_name), end='') retcode = subprocess.getstatusoutput( 'service {0} stop'.format(service_name)) if retcode[0] == 0: Log.info(self, "[" + Log.ENDC + "OK" + Log.OKGREEN + "]") return True else: Log.debug(self, "{0}".format(retcode[1])) Log.info(self, "[" + Log.FAIL + "Failed" + Log.OKGREEN + "]") return False except OSError as e: Log.debug(self, "{0}".format(e)) Log.error(self, "\nFailed to stop service : {0}".format(service_name))
def get_service_status(self, service_name): try: is_exist = subprocess.getstatusoutput( 'which {0}'.format(service_name)) if is_exist[0] == 0 or service_name in ['php7.0-fpm']: retcode = subprocess.getstatusoutput( 'service {0} status'.format(service_name)) if retcode[0] == 0: return True else: Log.debug(self, "{0}".format(retcode[1])) return False else: return False except OSError as e: Log.debug(self, "{0}{1}".format(e.errno, e.strerror)) Log.error( self, "Unable to get services status of {0}".format(service_name)) return False