def run_command_get_output(cmd, chk_err=True, log_cmd=True):
    """
    Wrapper for subprocess.check_output.
    Execute 'cmd'.  Returns return code and STDOUT, trapping expected exceptions.
    Reports exceptions to Error if chk_err parameter is True
    """
    if log_cmd:
        logger.log_if_verbose(cmd)
    try:
        output = subprocess.check_output(cmd,
                                         stderr=subprocess.STDOUT,
                                         shell=False)
    except subprocess.CalledProcessError as e:
        if chk_err and log_cmd:
            logger.error('CalledProcessError.  Error Code is ' +
                         str(e.returncode))
            logger.error('CalledProcessError.  Command string was ' + str(cmd))
            logger.error('CalledProcessError.  Command result was ' +
                         (e.output[:-1]).decode('latin-1'))
        return e.returncode, e.output.decode('latin-1')
    except EnvironmentError as e:
        if chk_err and log_cmd:
            logger.error('CalledProcessError.  Error message is ' + str(e))
            return e.errno, str(e)
    # noinspection PyUnboundLocalVariable
    return 0, output.decode('latin-1')
def run_send_stdin(cmd, cmd_input, chk_err=True, log_cmd=True):
    """
    Wrapper for subprocess.Popen.
    Execute 'cmd', sending 'input' to STDIN of 'cmd'.
    Returns return code and STDOUT, trapping expected exceptions.
    Reports exceptions to Error if chk_err parameter is True
    """
    if log_cmd:
        logger.log_if_verbose(str(cmd) + str(cmd_input))
    subprocess_executed = False
    try:
        me = subprocess.Popen(cmd,
                              shell=False,
                              stdin=subprocess.PIPE,
                              stderr=subprocess.STDOUT,
                              stdout=subprocess.PIPE)
        output = me.communicate(cmd_input)
        subprocess_executed = True
    except EnvironmentError as e:
        if chk_err and log_cmd:
            logger.error('CalledProcessError.  Error Code is ' + str(e.errno))
            logger.error('CalledProcessError.  Command was ' + str(cmd))
            logger.error('CalledProcessError.  Command result was ' + str(e))
            return 1, str(e)
    if subprocess_executed and me.returncode != 0 and chk_err and log_cmd:
        logger.error('CalledProcessError.  Error Code is ' +
                     str(me.returncode))
        logger.error('CalledProcessError.  Command was ' + str(cmd))
        logger.error('CalledProcessError.  Command result was ' +
                     output[0].decode('latin-1'))
    return me.returncode, output[0].decode('latin-1')
Example #3
0
    def parse(xml_text, configuration, is_deprovision=False):
        """
        Parse xml tree, retrieving user and ssh key information.
        Return self.
        """
        ofv_env = OvfEnv()
        logger.log_if_verbose(re.sub("<UserPassword>.*?<", "<UserPassword>*<", xml_text))
        dom = xml.dom.minidom.parseString(xml_text)
        if len(dom.getElementsByTagNameNS(ofv_env.OvfNs, "Environment")) != 1:
            logger.error("Unable to parse OVF XML.")
        section = None
        newer = False
        for p in dom.getElementsByTagNameNS(ofv_env.WaNs, "ProvisioningSection"):
            for n in p.childNodes:
                if n.localName == "Version":
                    verparts = get_node_text_data(n).split('.')
                    major = int(verparts[0])
                    minor = int(verparts[1])
                    if major > ofv_env.MajorVersion:
                        newer = True
                    if major != ofv_env.MajorVersion:
                        break
                    if minor > ofv_env.MinorVersion:
                        newer = True
                    section = p
        if newer:
            logger.warning(
                "Newer provisioning configuration detected. Please consider updating waagent.")
        if section is None:
            logger.error(
                "Could not find ProvisioningSection with major version=" + str(ofv_env.MajorVersion))
            return None
        ofv_env.ComputerName = get_node_text_data(section.getElementsByTagNameNS(ofv_env.WaNs, "HostName")[0])
        ofv_env.UserName = get_node_text_data(section.getElementsByTagNameNS(ofv_env.WaNs, "UserName")[0])
        if is_deprovision:
            return ofv_env
        try:
            ofv_env.UserPassword = get_node_text_data(section.getElementsByTagNameNS(ofv_env.WaNs, "UserPassword")[0])
        except (KeyError, ValueError, AttributeError, IndexError):
            pass

        try:
            cd_section = section.getElementsByTagNameNS(ofv_env.WaNs, "CustomData")
            if len(cd_section) > 0:
                ofv_env.CustomData = get_node_text_data(cd_section[0])
                if len(ofv_env.CustomData) > 0:
                    ext_utils.set_file_contents(constants.LibDir + '/CustomData', bytearray(
                        translate_custom_data(ofv_env.CustomData, configuration)))
                    logger.log('Wrote ' + constants.LibDir + '/CustomData')
                else:
                    logger.error('<CustomData> contains no data!')
        except Exception as e:
            logger.error(str(e) + ' occured creating ' + constants.LibDir + '/CustomData')
        disable_ssh_passwd = section.getElementsByTagNameNS(ofv_env.WaNs, "DisableSshPasswordAuthentication")
        if len(disable_ssh_passwd) != 0:
            ofv_env.DisableSshPasswordAuthentication = (get_node_text_data(disable_ssh_passwd[0]).lower() == "true")
        for pkey in section.getElementsByTagNameNS(ofv_env.WaNs, "PublicKey"):
            logger.log_if_verbose(repr(pkey))
            fp = None
            path = None
            for c in pkey.childNodes:
                if c.localName == "Fingerprint":
                    fp = get_node_text_data(c).upper()
                    logger.log_if_verbose(fp)
                if c.localName == "Path":
                    path = get_node_text_data(c)
                    logger.log_if_verbose(path)
            ofv_env.SshPublicKeys += [[fp, path]]
        for keyp in section.getElementsByTagNameNS(ofv_env.WaNs, "KeyPair"):
            fp = None
            path = None
            logger.log_if_verbose(repr(keyp))
            for c in keyp.childNodes:
                if c.localName == "Fingerprint":
                    fp = get_node_text_data(c).upper()
                    logger.log_if_verbose(fp)
                if c.localName == "Path":
                    path = get_node_text_data(c)
                    logger.log_if_verbose(path)
            ofv_env.SshKeyPairs += [[fp, path]]
        return ofv_env