Python subprocess.getstatusoutput() Examples

The following are 30 code examples for showing how to use subprocess.getstatusoutput(). These examples are extracted from open source projects. You can vote up the ones you like or vote down the ones you don't like, and go to the original project or source file by following the links above each example.

You may check out the related API usage on the sidebar.

You may also want to check out all available functions/classes of the module subprocess , or try the search function .

Example 1
Project: MySQL-AutoXtraBackup   Author: ShahriyarR   File: partial.py    License: MIT License 6 votes vote down vote up
def check_innodb_file_per_table(self):
        """
        Function for checking MySQL innodb_file_per_table option.
        It is needed for "Transportable Tablespace" concept.
        :return: True/False
        """
        statement = "select @@global.innodb_file_per_table"
        run_command = self.create_mysql_client_command(statement=statement)

        logger.info("Checking if innodb_file_per_table is enabled")
        status, output = subprocess.getstatusoutput(run_command)

        if status == 0 and int(output[-1]) == 1:
            logger.info("OK: innodb_file_per_table is enabled!")
            return True
        elif status == 0 and int(output[-1]) == 0:
            logger.info("OK: innodb_file_per_table is disabled!")
            return False
        else:
            logger.error("FAILED: InnoDB file per-table Check")
            logger.error(output)
            raise RuntimeError("FAILED: InnoDB file per-table Check") 
Example 2
Project: MySQL-AutoXtraBackup   Author: ShahriyarR   File: partial.py    License: MIT License 6 votes vote down vote up
def check_mysql_version(self):
        """
        Function for checking MySQL version.
        Version must be >= 5.6 for using "Transportable Tablespace" concept.
        :return: True/False
        """
        statement = "select @@version"
        run_command = self.create_mysql_client_command(statement=statement)

        logger.info("Checking MySQL version")
        status, output = subprocess.getstatusoutput(run_command)

        if status == 0 and ('5.6' in output):
            logger.info("You have correct version of MySQL")
            return True
        elif status == 0 and ('5.7' in output):
            logger.info("You have correct version of MySQL")
            return True
        elif status == 0 and ('5.7' not in output) and ('5.6' not in output):
            logger.error("Your MySQL server is not supported. MySQL version must be >= 5.6")
            raise RuntimeError("Your MySQL server is not supported. MySQL version must be >= 5.6")
        else:
            logger.error("FAILED: MySQL version check")
            logger.error(output)
            raise RuntimeError("FAILED: MySQL version check") 
Example 3
Project: MySQL-AutoXtraBackup   Author: ShahriyarR   File: prepare.py    License: MIT License 6 votes vote down vote up
def start_mysql_func(self, start_tool=None, options=None):
        # Starting MySQL
        logger.info("Starting MySQL server: ")
        if start_tool is None:
            args = self.start_mysql
        else:
            args = start_tool

        if options is not None:
            start_command = "{} {}".format(args, options)
        else:
            start_command = args
        status, output = subprocess.getstatusoutput(start_command)
        if status == 0:
            logger.info("Starting MySQL ...")
            logger.info(output)
            return True
        else:
            logger.error("Error occurred while starting MySQL!")
            logger.error(output)
            raise RuntimeError("Error occurred while starting MySQL!") 
Example 4
Project: MySQL-AutoXtraBackup   Author: ShahriyarR   File: clone_build_start_server.py    License: MIT License 6 votes vote down vote up
def clone_pxb(self):
        # Clone PXB from github based on branch values from config file.
        pxb_branches = self.pxb_branches.split()
        for branch in pxb_branches:
            clone_cmd = "git clone {} -b {} {}/PXB-{}"
            if not os.path.exists("{}/PXB-{}".format(self.testpath, branch)):
                logger.debug("Started to clone PXB...")
                status, output = subprocess.getstatusoutput(
                    clone_cmd.format(self.pxb_gitcmd, branch, self.testpath, branch))
                if status == 0:
                    logger.debug("PXB-{} cloned ready to build".format(branch))
                else:
                    logger.error("Cloning PXB-{} failed".format(branch))
                    logger.error(output)
                    return False
        return True 
Example 5
Project: MySQL-AutoXtraBackup   Author: ShahriyarR   File: clone_build_start_server.py    License: MIT License 6 votes vote down vote up
def build_pxb(self):
        # Building pxb from source
        # For this purpose will use build_{}_pxb.sh scripts from this folder
        pxb_branches = self.pxb_branches.split()
        saved_path = os.getcwd()
        dir_path = os.path.dirname(os.path.realpath(__file__))
        for branch in pxb_branches:
            pxb_path = "{}/PXB-{}".format(self.testpath, branch)
            os.chdir(pxb_path)
            build_cmd = "{}/build_pxb.sh {} {}".format(dir_path, self.testpath, branch)
            status, output = subprocess.getstatusoutput(build_cmd)
            if status == 0:
                logger.debug("PXB build succeeded")
                os.chdir(saved_path)
            else:
                logger.error("PXB build failed")
                logger.error(output)
                os.chdir(saved_path)
                return False

        return True 
Example 6
Project: MySQL-AutoXtraBackup   Author: ShahriyarR   File: clone_build_start_server.py    License: MIT License 6 votes vote down vote up
def prepare_startup(self, basedir_path):
        # Method for calling startup.sh file from percona-qa folder
        saved_path = os.getcwd()
        os.chdir(basedir_path)

        startup_cmd = "{}/percona-qa/startup.sh"
        logger.debug("Started to run startup.sh file...")
        status, output = subprocess.getstatusoutput(startup_cmd.format(self.testpath))
        if status == 0:
            logger.debug("Running startup.sh succeeded")
            os.chdir(saved_path)
            return True
        else:
            logger.error("Running startup.sh failed")
            logger.error(output)
            os.chdir(saved_path)
            return False 
Example 7
Project: MySQL-AutoXtraBackup   Author: ShahriyarR   File: clone_build_start_server.py    License: MIT License 6 votes vote down vote up
def prepare_start_dynamic(basedir_path):
        # Method for calling start_dynamic.sh from basedir.
        # It will generate start_dynamic executables in basedir.
        saved_path = os.getcwd()
        dir_path = os.path.dirname(os.path.realpath(__file__))
        os.chdir(basedir_path)
        start_dynamic = "{}/start_dynamic.sh".format(dir_path)
        logger.debug("Running start_dynamic.sh here...")
        status, output = subprocess.getstatusoutput(start_dynamic)
        if status == 0:
            logger.debug("Running start_dynamic.sh succeeded")
            os.chdir(saved_path)
            return True
        else:
            logger.error("Running start_dynamic.sh failed")
            logger.error(output)
            os.chdir(saved_path)
            return False 
Example 8
Project: MySQL-AutoXtraBackup   Author: ShahriyarR   File: clone_build_start_server.py    License: MIT License 6 votes vote down vote up
def wipe_server_all(basedir_path, options=None):
        # Method for calling "all" script which is created inside PS basedir
        saved_path = os.getcwd()
        os.chdir(basedir_path)
        logger.debug("Using all_no_cl script here...")
        if options is not None:
            all_cmd = "./all_no_cl {}"
            status, output = subprocess.getstatusoutput(all_cmd.format(options))
        else:
            all_cmd = "./all_no_cl"
            status, output = subprocess.getstatusoutput(all_cmd)
        if status == 0:
            logger.debug("Server wiped for fresh start!")
            os.chdir(saved_path)
            return True
        else:
            logger.error("All script run failed")
            logger.error(output)
            os.chdir(saved_path)
            return False 
Example 9
Project: MySQL-AutoXtraBackup   Author: ShahriyarR   File: clone_build_start_server.py    License: MIT License 6 votes vote down vote up
def extract_xb_archive(self, file_name):
        # General method for extracting XB archives
        # It will create target folder inside test path
        extract_cmd = "tar -xf {}/{} -C {}"
        if os.path.isfile("{}/{}".format(self.testpath, file_name)):
            if not os.path.isdir("{}/target/{}".format(self.testpath, file_name[:-7])):
                status, output = subprocess.getstatusoutput(extract_cmd.format(self.testpath, file_name, self.testpath))
                if status == 0:
                    logger.debug("Extracted from {}".format(file_name))
                    return True
                else:
                    logger.error("Failed to extract from {}".format(file_name))
                    logger.error(output)
                    return False
            else:
                logger.debug("The 'target' folder already there...")
                return True
        else:
            logger.debug("Could not find {}".format(file_name))
            return False 
Example 10
Project: MySQL-AutoXtraBackup   Author: ShahriyarR   File: runner_test_mode.py    License: MIT License 6 votes vote down vote up
def create_slave_shutdown_file(basedir, num):
        """
        Static method for creating shutdown file for slave
        :param basedir: Basedir path
        :param num: The number for slave
        :return: True on success
        :raise: RuntimeError on fail
        """
        with open("{}/stop_node{}".format(basedir, num), 'w+') as stop_file:
            shutdown_slave = "{}/bin/mysqladmin -uroot -S{}/sock{}.sock shutdown".format(basedir, basedir, num)
            stop_file.write(shutdown_slave)
            # give u+x to this file
            chmod = "chmod u+x {}/stop_node{}".format(basedir, num)
            status, output = subprocess.getstatusoutput(chmod)

            if status == 0:
                logger.debug("chmod succeeded for {}/stop_node{}".format(basedir, num))
                return True
            else:
                raise RuntimeError("Failed to chmod {}/stop_node{}".format(basedir, num)) 
Example 11
Project: bluescan   Author: fO-000   File: sdp_scan.py    License: GNU General Public License v3.0 6 votes vote down vote up
def scan(self, addr:str):
        print(INFO, 'Scanning...')
        exitcode, output = subprocess.getstatusoutput('sdptool records --xml ' + addr)
        if exitcode != 0:
            sys.exit(exitcode)

        # print('[DEBUG] output:', output)
        self.parse_sdptool_output(output)
        
        # services = find_service(address=addr)
        # # print(services)
        # # print('!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!')
        # for service in services:
        #     print('Name:', service['name'] )
        #     print('ProtocolDescriptorList', service['protocol'])
        #     print('channel/PSM', service['port'])
        #     print('ServiceClassIDList:', service['service-classes'])
        #     print('Profiles:', service['profiles'])
        #     print('Description:', service['description'])
        #     print('Provider:', service['provider'])
        #     print('ServiceID', service['service-id'])
        #     print() 
Example 12
Project: codimension   Author: SergeySatskiy   File: versions.py    License: GNU General Public License v3.0 6 votes vote down vote up
def getPlantUMLVersion():
    """Provides the plantUML version"""
    if JAR_PATH is None:
        return "n/a", None

    try:
        status, output = getstatusoutput('java -jar ' + JAR_PATH + ' -version')
        if status != 0:
            return "n/a", None

        for line in output.splitlines():
            # PlantUML version 1.2019.05 (Sat Apr 20 11:45:36 GMT-05:00 2019)
            line = line.strip()
            if line.startswith('PlantUML version'):
                return line.split('version', 1)[1].strip(), JAR_PATH
    except:
        return "n/a", None
    return "could not determine", JAR_PATH 
Example 13
Project: rucio   Author: rucio   File: srm.py    License: Apache License 2.0 6 votes vote down vote up
def connect(self):
        """
        Establishes the actual connection to the referred RSE.
        As a quick and dirty impelementation we just use this method to check if the lcg tools are available.
        If we decide to use gfal, init should be done here.

        :raises RSEAccessDenied: Cannot connect.
        """

        status, lcglscommand = getstatusoutput('which lcg-ls')
        if status:
            raise exception.RSEAccessDenied('Cannot find lcg tools')
        endpoint_basepath = self.path2pfn(self.attributes['prefix'])
        status, result = getstatusoutput('%s -vv $LCGVO -b --srm-timeout 60 -D srmv2 -l %s' % (lcglscommand, endpoint_basepath))
        if status:
            if result == '':
                raise exception.RSEAccessDenied('Endpoint not reachable. lcg-ls failed with status code %s but no further details.' % (str(status)))
            else:
                raise exception.RSEAccessDenied('Endpoint not reachable : %s' % str(result)) 
Example 14
Project: hpe-solutions-openshift   Author: HewlettPackard   File: operator_install.py    License: Apache License 2.0 6 votes vote down vote up
def get_token(oc_path):
    """
    Get authentication token from OC command line tool

    Returns:
    The bearer token to the init_setup function

    """
    global USER_NAME, PASSWORD, IP
    print("Logging into your OpenShift Cluster")
    status, _ = subprocess.getstatusoutput(oc_path + "oc login "+IP+" -u "+USER_NAME+" -p "+ \
        PASSWORD +" --insecure-skip-tls-verify=true")
    if status == 0:
        print("Successfully logged into the OpenShift Cluster")
    else:
        print("Could not login, please enter correct login credentials")
        exit(1)
    token = subprocess.getoutput(oc_path + "oc whoami -t")

    return token

#General Function for get calls 
Example 15
Project: hpe-solutions-openshift   Author: HewlettPackard   File: operator_install.py    License: Apache License 2.0 6 votes vote down vote up
def validate_kibana(installer_ip, port):
    """
    Validate kibana operator by checking the status of the operator and GUI console

    """
    status, output = subprocess.getstatusoutput("systemctl status kibana")
    if status == 0:
        print("Kibana is Active")
        output = "CLOSED"
        print("Waiting for Kibana GUI to load..")
        while output != "OPEN":
            #pingtest.py program is used to ping IP address along with the PORT number \
            # and verify if its open or closed
            _, output = subprocess.getstatusoutput("python pingtest.py "+installer_ip+" "+ port+" 2> /dev/null && \
                echo OPEN || echo CLOSED")
        print("Kibana GUI is available for use on the installer IP.. ")
    else:
        print("Kibana is not running..")

#function to deploy logstash operator 
Example 16
Project: mass-apk-installer   Author: binary-signal   File: adb.py    License: BSD 3-Clause "New" or "Revised" License 6 votes vote down vote up
def exec_command(self, cmd, return_stdout=False, case_sensitive=False, silence_errors=False) -> Optional[str]:
        """Low level function to send shell commands to running adb-server process.

        :raises AdbError
        """

        cmd = f"{self._path} {cmd}"
        log.info("Executing " + cmd)
        return_code, output = subprocess.getstatusoutput(cmd)

        if return_code:
            if silence_errors:
                log.error(output)
                return None

            if output is None:
                log.warning(f"command returned error code {return_code}, but no output, {cmd}")
                raise AdbError(f"Command returned error code {cmd}")

            raise AdbError(output + f" {cmd}")

        if return_stdout:
            return output.lower() if case_sensitive else output

        return None 
Example 17
Project: WordOps   Author: WordOps   File: services.py    License: MIT License 6 votes vote down vote up
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 + Log.OKGREEN + "OK" +
                         Log.ENDC + Log.OKBLUE + "]")
                return True
            else:
                Log.debug(self, "{0}".format(retcode[1]))
                Log.info(self, "[" + Log.FAIL + "Failed" + Log.OKBLUE + "]")
                return False
        except OSError as e:
            Log.debug(self, "{0}".format(e))
            Log.error(self, "\nFailed to stop service : {0}"
                      .format(service_name)) 
Example 18
Project: WordOps   Author: WordOps   File: services.py    License: MIT License 6 votes vote down vote up
def get_service_status(self, service_name):

        try:
            is_exist = subprocess.getstatusoutput('command -v {0}'
                                                  .format(service_name))
            if is_exist[0] == 0 or service_name in ['php7.2-fpm',
                                                    'php7.3-fpm',
                                                    'php7.4-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 
Example 19
Project: python3_ios   Author: holzschu   File: setupext.py    License: BSD 3-Clause "New" or "Revised" License 6 votes vote down vote up
def check(self):
        if sys.platform == 'win32':
            check_include_file(get_include_dirs(), 'png.h', 'png')
            return 'Using unknown version found on system.'

        status, output = subprocess.getstatusoutput("libpng-config --version")
        if status == 0:
            version = output
        else:
            version = None

        try:
            return self._check_for_pkg_config(
                'libpng', 'png.h',
                min_version='1.2', version=version)
        except CheckFailed as e:
            if has_include_file(get_include_dirs(), 'png.h'):
                return str(e) + ' Using unknown version found on system.'
            raise 
Example 20
Project: alibuild   Author: alisw   File: analytics.py    License: GNU General Public License v3.0 5 votes vote down vote up
def generate_analytics_id():
  getstatusoutput("mkdir -p  ~/.config/alibuild")
  err, output = getstatusoutput("uuidgen >  ~/.config/alibuild/analytics-uuid")
  # If an error is found while generating the unique user ID, we disable
  # the analytics on the machine.
  if err:
    debug("Could not generate unique ID for user. Disabling analytics")
    getstatusoutput("touch ~/.config/alibuild/disable-analytics")
    return False
  return True 
Example 21
Project: alibuild   Author: alisw   File: analytics.py    License: GNU General Public License v3.0 5 votes vote down vote up
def enable_analytics():
  if exists(expanduser("~/.config/alibuild/disable-analytics")):
    unlink(expanduser("~/.config/alibuild/disable-analytics"))
  if not exists(expanduser("~/.config/alibuild/analytics-uuid")):
    generate_analytics_id()

# We do it in getstatusoutput because python makedirs can actually fail
# if one of the intermediate directories is not writeable. 
Example 22
Project: alibuild   Author: alisw   File: analytics.py    License: GNU General Public License v3.0 5 votes vote down vote up
def disable_analytics():
  getstatusoutput("mkdir -p ~/.config/alibuild && touch ~/.config/alibuild/disable-analytics")
  return False 
Example 23
Project: alibuild   Author: alisw   File: doctor.py    License: GNU General Public License v3.0 5 votes vote down vote up
def systemInfo():
  _,out = getstatusoutput("env")
  debug("Environment:\n"+out)
  _,out = getstatusoutput("uname -a")
  debug("uname -a: "+out)
  _,out = getstatusoutput("mount")
  debug("Mounts:\n"+out)
  _,out = getstatusoutput("df")
  debug("Disk free:\n"+out)
  for f in ["/etc/lsb-release", "/etc/redhat-release", "/etc/os-release"]:
    err,out = getstatusoutput("cat "+f)
    if not err:
      debug(f+":\n"+out) 
Example 24
Project: alibuild   Author: alisw   File: build.py    License: GNU General Public License v3.0 5 votes vote down vote up
def gzip():
  return getstatusoutput("which pigz")[0] and "gzip" or "pigz" 
Example 25
Project: alibuild   Author: alisw   File: build.py    License: GNU General Public License v3.0 5 votes vote down vote up
def getDirectoryHash(d):
  if exists(join(d, ".git")):
    err, out = getstatusoutput("GIT_DIR=%s/.git git rev-parse HEAD" % d)
    dieOnError(err, "Impossible to find reference for %s " % d)
  else:
    err, out = getstatusoutput("pip --disable-pip-version-check show alibuild | grep -e \"^Version:\" | sed -e 's/.* //'")
    dieOnError(err, "Impossible to find reference for %s " % d)
  return out

# Helper class which does not do anything to sync 
Example 26
Project: alibuild   Author: alisw   File: utilities.py    License: GNU General Public License v3.0 5 votes vote down vote up
def getVersion():
  try:
    import pkg_resources  # part of setuptools
    return pkg_resources.require("alibuild")[0].version
  except:
    cmd = "GIT_DIR=\'%s/.git\' git describe --tags" % dirname(dirname(__file__))
    err, version = getstatusoutput(cmd)
    return version if not err else "Unknown version." 
Example 27
Project: alibuild   Author: alisw   File: utilities.py    License: GNU General Public License v3.0 5 votes vote down vote up
def __call__(self):
    m = re.search(r'^dist:(.*)@([^@]+)$', self.url)
    fn,gh = m.groups()
    err,d = getstatusoutput(format("GIT_DIR=%(dist)s/.git git show %(gh)s:%(fn)s.sh",
                                   dist=self.configDir, gh=gh, fn=fn.lower()))
    if err:
      raise RuntimeError(format("Cannot read recipe %(fn)s from reference %(gh)s.\n" +
                                "Make sure you run first (this will not alter your recipes):\n" +
                                "  cd %(dist)s && git remote update -p && git fetch --tags",
                                dist=self.configDir, gh=gh, fn=fn))
    return d 
Example 28
Project: alibuild   Author: alisw   File: utilities.py    License: GNU General Public License v3.0 5 votes vote down vote up
def dockerStatusOutput(cmd, dockerImage=None, executor=getstatusoutput):
  if dockerImage:
    DOCKER_WRAPPER = """docker run %(di)s bash -c 'eval "$(echo %(c)s | base64 --decode)"'"""
    try:
      encodedCommand = base64.b64encode(bytes(cmd,  encoding="ascii")).decode()
    except TypeError:
      encodedCommand = base64.b64encode(cmd)
    cmd = format(DOCKER_WRAPPER,
                 di=dockerImage,
                 c=encodedCommand)
  return executor(cmd) 
Example 29
Project: MySQL-AutoXtraBackup   Author: ShahriyarR   File: partial.py    License: MIT License 5 votes vote down vote up
def check_database_exists_on_mysql(self, database_name):
        """
        Function check if this database already exists in MySQL Server.(.frm and .ibd files are exist)
        In other words database is not dropped. If there is no such database, there is an input for creation.
        :param database_name: Specified database name
        :return: True/False
        """
        statement = "SELECT count(*) FROM INFORMATION_SCHEMA.SCHEMATA WHERE SCHEMA_NAME = '%s'" % database_name
        run_command = self.create_mysql_client_command(statement=statement)

        logger.info("Checking if database exists in MySQL")
        status, output = subprocess.getstatusoutput(run_command)
        if status == 0 and int(output[-1]) == 1:
            logger.info("Database exists!")
            return True
        if status == 0 and int(output[-1]) == 0:
            logger.info("There is no such database!")
            logger.info("Create Specified Database in MySQL Server, before restoring single table")
            answer = input("We can create it for you do you want? (yes/no): ")
            if answer == 'yes':
                create_db = "create database %s" % database_name
                run_command = self.create_mysql_client_command(statement=create_db)
                logger.info("Creating specified database")
                status, output = subprocess.getstatusoutput(run_command)
                if status == 0:
                    logger.info("OK: {} database created".format(database_name))
                    return True
                else:
                    logger.error("FAILED: to create database!")
                    logger.error(output)
                    raise RuntimeError("FAILED: to create database!")
            else:  # if you type non-yes word
                logger.error("Exited!")
                return False

        else:
            logger.error("FAILED: Check for database")
            logger.error(output)
            raise RuntimeError("FAILED: Check for database") 
Example 30
Project: MySQL-AutoXtraBackup   Author: ShahriyarR   File: partial.py    License: MIT License 5 votes vote down vote up
def run_mysqlfrm_utility(path_to_frm_file):
        command = '/usr/bin/mysqlfrm --diagnostic %s' % path_to_frm_file
        logger.info("Running mysqlfrm tool")
        status, output = subprocess.getstatusoutput(command)
        if status == 0:
            logger.info("OK: Success to run mysqlfrm")
            return output
        else:
            logger.error("FAILED: run mysqlfrm")
            logger.error(output)
            raise RuntimeError("FAILED: run mysqlfrm")