def deleteDB(self, dbname, dbuser, dbhost, exit=True): try: # Check if Database exists try: if SSSMysql.check_db_exists(self, dbname): # Drop database if exists Log.debug(self, "dropping database `{0}`".format(dbname)) SSSMysql.execute( self, "drop database `{0}`".format(dbname), errormsg='Unable to drop database {0}'.format(dbname)) except StatementExcecutionError as e: Log.debug(self, "drop database failed") Log.info(self, "Database {0} not dropped".format(dbname)) except MySQLConnectionError as e: Log.debug(self, "Mysql Connection problem occured") if dbuser != 'root': Log.debug(self, "dropping user `{0}`".format(dbuser)) try: SSSMysql.execute( self, "drop user `{0}`@`{1}`".format(dbuser, dbhost)) except StatementExcecutionError as e: Log.debug(self, "drop database user failed") Log.info(self, "Database {0} not dropped".format(dbuser)) try: SSSMysql.execute(self, "flush privileges") except StatementExcecutionError as e: Log.debug(self, "drop database failed") Log.info(self, "Database {0} not dropped".format(dbname)) except Exception as e: Log.error(self, "Error occured while deleting database", exit)
def chown(self, path, user, group, recursive=False): """ Change Owner for files change owner for file with path specified user: username of owner group: group of owner recursive: if recursive is True change owner for all files in directory """ userid = pwd.getpwnam(user)[2] groupid = pwd.getpwnam(user)[3] try: Log.debug(self, "Changing ownership of {0}, Userid:{1},Groupid:{2}" .format(path, userid, groupid)) # Change inside files/directory permissions only if recursive flag # is set if recursive: for root, dirs, files in os.walk(path): for d in dirs: os.chown(os.path.join(root, d), userid, groupid) for f in files: os.chown(os.path.join(root, f), userid, groupid) os.chown(path, userid, groupid) except shutil.Error as e: Log.debug(self, "{0}".format(e)) Log.error(self, "Unable to change owner : {0}".format(path)) except Exception as e: Log.debug(self, "{0}".format(e)) Log.error(self, "Unable to change owner : {0} ".format(path))
def dist_upgrade(self): """ Similar to `apt-get upgrade` """ try: with open("/var/log/sss/sss.log", "a") as f: proc = subprocess.Popen( "DEBIAN_FRONTEND=noninteractive " "apt-get dist-upgrade -o " 'Dpkg::Options::="--force-confdef"' " -o " 'Dpkg::Options::="--force-confold"' " -y ", shell=True, stdin=None, stdout=f, stderr=f, executable="/bin/bash", ) proc.wait() if proc.returncode == 0: return True else: Log.info(self, Log.FAIL + "Oops Something went " "wrong!!") Log.error(self, "Check logs for reason " "`tail /var/log/ss/ss.log` & Try Again!!!") except Exception as e: Log.error(self, "Error while installing packages, " "apt-get exited with error")
def deleteDB(self, dbname, dbuser, dbhost, exit=True): try: # Check if Database exists try: if SSSMysql.check_db_exists(self, dbname): # Drop database if exists Log.debug(self, "dropping database `{0}`".format(dbname)) SSSMysql.execute(self, "drop database `{0}`".format(dbname), errormsg='Unable to drop database {0}' .format(dbname)) except StatementExcecutionError as e: Log.debug(self, "drop database failed") Log.info(self, "Database {0} not dropped".format(dbname)) except MySQLConnectionError as e: Log.debug(self, "Mysql Connection problem occured") if dbuser != 'root': Log.debug(self, "dropping user `{0}`".format(dbuser)) try: SSSMysql.execute(self, "drop user `{0}`@`{1}`" .format(dbuser, dbhost)) except StatementExcecutionError as e: Log.debug(self, "drop database user failed") Log.info(self, "Database {0} not dropped".format(dbuser)) try: SSSMysql.execute(self, "flush privileges") except StatementExcecutionError as e: Log.debug(self, "drop database failed") Log.info(self, "Database {0} not dropped".format(dbname)) except Exception as e: Log.error(self, "Error occured while deleting database", exit)
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 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 remove(self, packages, auto=False, purge=False): all_packages = ' '.join(packages) try: with open('/var/log/sss/sss.log', 'a') as f: if purge: proc = subprocess.Popen( 'apt-get purge -y {0}'.format(all_packages), shell=True, stdin=None, stdout=f, stderr=f, executable="/bin/bash") else: proc = subprocess.Popen( 'apt-get remove -y {0}'.format(all_packages), shell=True, stdin=None, stdout=f, stderr=f, executable="/bin/bash") proc.wait() if proc.returncode == 0: return True else: Log.info(self, Log.FAIL + "Oops Something went " "wrong!!") Log.error( self, "Check logs for reason " "`tail /var/log/sss/sss.log` & Try Again!!!") except Exception as e: Log.error( self, "Error while installing packages, " "apt-get exited with error")
def chown(self, path, user, group, recursive=False): """ Change Owner for files change owner for file with path specified user: username of owner group: group of owner recursive: if recursive is True change owner for all files in directory """ userid = pwd.getpwnam(user)[2] groupid = pwd.getpwnam(user)[3] try: Log.debug( self, "Changing ownership of {0}, Userid:{1},Groupid:{2}".format( path, userid, groupid)) # Change inside files/directory permissions only if recursive flag # is set if recursive: for root, dirs, files in os.walk(path): for d in dirs: os.chown(os.path.join(root, d), userid, groupid) for f in files: os.chown(os.path.join(root, f), userid, groupid) os.chown(path, userid, groupid) except shutil.Error as e: Log.debug(self, "{0}".format(e)) Log.error(self, "Unable to change owner : {0}".format(path)) except Exception as e: Log.debug(self, "{0}".format(e)) Log.error(self, "Unable to change owner : {0} ".format(path))
def remove(self, packages, auto=False, purge=False): all_packages = " ".join(packages) try: with open("/var/log/sss/sss.log", "a") as f: if purge: proc = subprocess.Popen( "apt-get purge -y {0}".format(all_packages), shell=True, stdin=None, stdout=f, stderr=f, executable="/bin/bash", ) else: proc = subprocess.Popen( "apt-get remove -y {0}".format(all_packages), shell=True, stdin=None, stdout=f, stderr=f, executable="/bin/bash", ) proc.wait() if proc.returncode == 0: return True else: Log.info(self, Log.FAIL + "Oops Something went " "wrong!!") Log.error(self, "Check logs for reason " "`tail /var/log/sss/sss.log` & Try Again!!!") except Exception as e: Log.error(self, "Error while installing packages, " "apt-get exited with error")
def install(self, packages): all_packages = " ".join(packages) try: with open("/var/log/sss/sss.log", "a") as f: proc = subprocess.Popen( "DEBIAN_FRONTEND=noninteractive " "apt-get install -o " 'Dpkg::Options::="--force-confdef"' " -o " 'Dpkg::Options::="--force-confold"' " -y {0}".format(all_packages), shell=True, stdin=None, stdout=f, stderr=f, executable="/bin/bash", ) proc.wait() if proc.returncode == 0: return True else: Log.info(self, Log.FAIL + "Oops Something went " "wrong!!") Log.error(self, "Check logs for reason " "`tail /var/log/sss/sss.log` & Try Again!!!") except Exception as e: Log.info(self, Log.FAIL + "Oops Something went " "wrong!!") Log.error(self, "Check logs for reason " "`tail /var/log/sss/sss.log` & Try Again!!!")
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 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 install(self, packages): all_packages = ' '.join(packages) try: with open('/var/log/sss/sss.log', 'a') as f: proc = subprocess.Popen("DEBIAN_FRONTEND=noninteractive " "apt-get install -o " "Dpkg::Options::=\"--force-confdef\"" " -o " "Dpkg::Options::=\"--force-confold\"" " -y {0}".format(all_packages), shell=True, stdin=None, stdout=f, stderr=f, executable="/bin/bash") proc.wait() if proc.returncode == 0: return True else: Log.info(self, Log.FAIL + "Oops Something went " "wrong!!") Log.error( self, "Check logs for reason " "`tail /var/log/sss/sss.log` & Try Again!!!") except Exception as e: Log.info(self, Log.FAIL + "Oops Something went " "wrong!!") Log.error( self, "Check logs for reason " "`tail /var/log/sss/sss.log` & Try Again!!!")
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 dist_upgrade(self): """ Similar to `apt-get upgrade` """ try: with open('/var/log/sss/sss.log', 'a') as f: proc = subprocess.Popen( "DEBIAN_FRONTEND=noninteractive " "apt-get dist-upgrade -o " "Dpkg::Options::=\"--force-confdef\"" " -o " "Dpkg::Options::=\"--force-confold\"" " -y ", shell=True, stdin=None, stdout=f, stderr=f, executable="/bin/bash") proc.wait() if proc.returncode == 0: return True else: Log.info(self, Log.FAIL + "Oops Something went " "wrong!!") Log.error( self, "Check logs for reason " "`tail /var/log/ss/ss.log` & Try Again!!!") except Exception as e: Log.error( self, "Error while installing packages, " "apt-get exited with error")
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 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 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 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 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 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 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 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 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 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 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 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 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 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 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 update(self): """ Similar to `apt-get update` """ try: with open('/var/log/sss/sss.log', 'a') as f: proc = subprocess.Popen('apt-get update', shell=True, stdin=None, stdout=f, stderr=subprocess.PIPE, executable="/bin/bash") proc.wait() output, error_output = proc.communicate() # Check what is error in error_output if "NO_PUBKEY" in str(error_output): # Split the output Log.info(self, "Fixing missing GPG keys, please wait...") error_list = str(error_output).split("\\n") # Use a loop to add misising keys for single_error in error_list: if "NO_PUBKEY" in single_error: key = single_error.rsplit(None, 1)[-1] SSSRepo.add_key(self, key, keyserver="hkp://pgp.mit.edu") proc = subprocess.Popen('apt-get update', shell=True, stdin=None, stdout=f, stderr=f, executable="/bin/bash") proc.wait() if proc.returncode == 0: return True else: Log.info(self, Log.FAIL + "Oops Something went wrong!!") Log.error( self, "Check logs for reason " "`tail /var/log/sss/sss.log` & Try Again!!!") except Exception as e: Log.error(self, "apt-get update exited with error")
def create_symlink(self, paths, errormsg=''): """ Create symbolic links provided in list with first as source and second as destination """ src = paths[0] dst = paths[1] if not os.path.islink(dst): try: Log.debug(self, "Creating Symbolic link, Source:{0}, Dest:{1}" .format(src, dst)) os.symlink(src, dst) except Exception as e: Log.debug(self, "{0}{1}".format(e.errno, e.strerror)) Log.error(self, "Unable to create symbolic link ...\n ") else: Log.debug(self, "Destination: {0} exists".format(dst))
def check_upgrade(self): """ Similar to `apt-get upgrade` """ try: check_update = subprocess.Popen( ["apt-get upgrade -s | grep " '"^Inst" | wc -l'], stdout=subprocess.PIPE, shell=True ).communicate()[0] if check_update == b"0\n": Log.error(self, "No package updates available") Log.info(self, "Following package updates are available:") subprocess.Popen( 'apt-get -s dist-upgrade | grep "^Inst"', shell=True, executable="/bin/bash", stdout=sys.stdout ).communicate() except Exception as e: Log.error(self, "Unable to check for packages upgrades")
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 copyfile(self, src, dest): """ Copies files: src : source path dest : destination path """ try: Log.debug(self, "Copying file, Source:{0}, Dest:{1}".format(src, dest)) shutil.copy2(src, dest) except shutil.Error as e: Log.debug(self, "{0}".format(e)) Log.error(self, 'Unable to copy file from {0} to {1}'.format(src, dest)) except IOError as e: Log.debug(self, "{e}".format(e.strerror)) Log.error(self, "Unable to copy file from {0} to {1}".format(src, dest))
def rm(self, path): """ Remove files """ Log.debug(self, "Removing {0}".format(path)) if SSSFileUtils.isexist(self, path): try: if os.path.isdir(path): shutil.rmtree(path) else: os.remove(path) except shutil.Error as e: Log.debug(self, "{0}".format(e)) Log.error(self, "Unable to remove directory : {0} ".format(path)) except OSError as e: Log.debug(self, "{0}".format(e)) Log.error(self, "Unable to remove file : {0} ".format(path))
def copyfile(self, src, dest): """ Copies files: src : source path dest : destination path """ try: Log.debug(self, "Copying file, Source:{0}, Dest:{1}" .format(src, dest)) shutil.copy2(src, dest) except shutil.Error as e: Log.debug(self, "{0}".format(e)) Log.error(self, 'Unable to copy file from {0} to {1}' .format(src, dest)) except IOError as e: Log.debug(self, "{e}".format(e.strerror)) Log.error(self, "Unable to copy file from {0} to {1}" .format(src, dest))
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 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 rm(self, path): """ Remove files """ Log.debug(self, "Removing {0}".format(path)) if SSSFileUtils.isexist(self, path): try: if os.path.isdir(path): shutil.rmtree(path) else: os.remove(path) except shutil.Error as e: Log.debug(self, "{0}".format(e)) Log.error(self, "Unable to remove directory : {0} " .format(path)) except OSError as e: Log.debug(self, "{0}".format(e)) Log.error(self, "Unable to remove file : {0} " .format(path))
def create_symlink(self, paths, errormsg=''): """ Create symbolic links provided in list with first as source and second as destination """ src = paths[0] dst = paths[1] if not os.path.islink(dst): try: Log.debug( self, "Creating Symbolic link, Source:{0}, Dest:{1}".format( src, dst)) os.symlink(src, dst) except Exception as e: Log.debug(self, "{0}{1}".format(e.errno, e.strerror)) Log.error(self, "Unable to create symbolic link ...\n ") else: Log.debug(self, "Destination: {0} exists".format(dst))
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 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 check_upgrade(self): """ Similar to `apt-get upgrade` """ try: check_update = subprocess.Popen( ['apt-get upgrade -s | grep ' '\"^Inst\" | wc -l'], stdout=subprocess.PIPE, shell=True).communicate()[0] if check_update == b'0\n': Log.error(self, "No package updates available") Log.info(self, "Following package updates are available:") subprocess.Popen("apt-get -s dist-upgrade | grep \"^Inst\"", shell=True, executable="/bin/bash", stdout=sys.stdout).communicate() except Exception as e: Log.error(self, "Unable to check for packages upgrades")
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 chmod(self, path, perm, recursive=False): """ Changes Permission for files path : file path permission to be changed perm : permissions to be given recursive: change permission recursively for all files """ try: Log.debug(self, "Changing permission of {0}, Perm:{1}" .format(path, perm)) if recursive: for root, dirs, files in os.walk(path): for d in dirs: os.chmod(os.path.join(root, d), perm) for f in files: os.chmod(os.path.join(root, f), perm) else: os.chmod(path, perm) except OSError as e: Log.debug(self, "{0}".format(e.strerror)) Log.error(self, "Unable to change owner : {0}".format(path))
def download(self, packages): """Download packages, packges must be list in format of [url, path, package name]""" for package in packages: url = package[0] filename = package[1] pkg_name = package[2] try: directory = os.path.dirname(filename) if not os.path.exists(directory): os.makedirs(directory) Log.info(self, "Downloading {0:20}".format(pkg_name), end=' ') urllib.request.urlretrieve(url, filename) Log.info( self, "{0}".format("[" + Log.ENDC + "Done" + Log.OKGREEN + "]")) except urllib.error.URLError as e: Log.debug(self, "[{err}]".format(err=str(e.reason))) Log.error(self, "Unable to download file, {0}".format(filename)) return False except urllib.error.HTTPError as e: Log.error(self, "Package download failed. {0}".format(pkg_name)) Log.debug(self, "[{err}]".format(err=str(e.reason))) return False except urllib.error.ContentTooShortError as e: Log.debug(self, "{0}{1}".format(e.errno, e.strerror)) Log.error( self, "Package download failed. The amount of the" " downloaded data is less than " "the expected amount \{0} ".format(pkg_name)) return False
def download(self, packages): """Download packages, packges must be list in format of [url, path, package name]""" for package in packages: url = package[0] filename = package[1] pkg_name = package[2] try: directory = os.path.dirname(filename) if not os.path.exists(directory): os.makedirs(directory) Log.info(self, "Downloading {0:20}".format(pkg_name), end=' ') urllib.request.urlretrieve(url, filename) Log.info(self, "{0}".format("[" + Log.ENDC + "Done" + Log.OKGREEN + "]")) except urllib.error.URLError as e: Log.debug(self, "[{err}]".format(err=str(e.reason))) Log.error(self, "Unable to download file, {0}" .format(filename)) return False except urllib.error.HTTPError as e: Log.error(self, "Package download failed. {0}" .format(pkg_name)) Log.debug(self, "[{err}]".format(err=str(e.reason))) return False except urllib.error.ContentTooShortError as e: Log.debug(self, "{0}{1}".format(e.errno, e.strerror)) Log.error(self, "Package download failed. The amount of the" " downloaded data is less than " "the expected amount \{0} ".format(pkg_name)) return False