def _parse_config(self, ctxt):
     config = None
     try:
         config = json.loads(ctxt)
     except:
         self.error('JSON exception decoding ' + ctxt)
     if config == None:
         self.error("JSON error processing settings file:" + ctxt)
     else:
         handlerSettings = config['runtimeSettings'][0]['handlerSettings']
         if 'protectedSettings' in handlerSettings and \
                 "protectedSettingsCertThumbprint" in handlerSettings and \
                 handlerSettings['protectedSettings'] is not None and \
                 handlerSettings["protectedSettingsCertThumbprint"] is not None:
             protectedSettings = handlerSettings['protectedSettings']
             thumb = handlerSettings['protectedSettingsCertThumbprint']
             cert = waagent.LibDir + '/' + thumb + '.crt'
             pkey = waagent.LibDir + '/' + thumb + '.prv'
             f = tempfile.NamedTemporaryFile(delete=False)
             f.close()
             waagent.SetFileContents(f.name,config['runtimeSettings'][0]['handlerSettings']['protectedSettings'])
             cleartxt = None
             if 'NS-BSD' in platform.system():
                 # base64 tool is not available with NSBSD, use openssl
                 cleartxt = waagent.RunGetOutput(self.patching.openssl_path + " base64 -d -A -in " + f.name + " | " + self.patching.openssl_path + " smime  -inform DER -decrypt -recip " + cert + "  -inkey " + pkey)[1]
             else:
                 cleartxt = waagent.RunGetOutput(self.patching.base64_path + " -d " + f.name + " | " + self.patching.openssl_path + " smime  -inform DER -decrypt -recip " + cert + "  -inkey " + pkey)[1]
             jctxt = {}
             try:
                 jctxt = json.loads(cleartxt)
             except:
                 self.error('JSON exception decoding ' + cleartxt)
             handlerSettings['protectedSettings'] = jctxt
             self.log('Config decoded correctly.')
     return config
示例#2
0
 def stop_download(self):
     '''
     kill the process of downloading and its subprocess.
     return code:
         100  - There are no downloading process to stop
         0    - The downloading process is stopped
     '''
     script_file_path = os.path.realpath(sys.argv[0])
     script_file = os.path.basename(script_file_path)
     retcode, output = waagent.RunGetOutput(
         'ps -ef | grep "' + script_file +
         ' -download" | grep -v grep | grep -v sh | awk \'{print $2}\'')
     if retcode > 0:
         self.hutil.log_and_syslog(logging.ERROR, output)
     if output != '':
         retcode, output2 = waagent.RunGetOutput("ps -ef | awk '{if($3==" +
                                                 output.strip() +
                                                 ") {print $2}}'")
         if retcode > 0:
             self.hutil.log_and_syslog(logging.ERROR, output2)
         if output2 != '':
             waagent.Run('kill -9 ' + output2.strip())
         waagent.Run('kill -9 ' + output.strip())
         return 0
     return 100
示例#3
0
def run_get_output(cmd, chk_err=False, log_cmd=True):
    """
    Mimic waagent mothod RunGetOutput in case waagent is not available
    Run shell command and return exit code and output
    """
    if 'Utils.WAAgentUtil' in sys.modules:
        # WALinuxAgent-2.0.14 allows only 2 parameters for RunGetOutput
        # If checking the number of parameters fails, pass 2
        try:
            sig = inspect.signature(waagent.RunGetOutput)
            params = sig.parameters
            waagent_params = len(params)
        except:
            try:
                spec = inspect.getargspec(waagent.RunGetOutput)
                params = spec.args
                waagent_params = len(params)
            except:
                waagent_params = 2
        if waagent_params >= 3:
            exit_code, output = waagent.RunGetOutput(cmd, chk_err, log_cmd)
        else:
            exit_code, output = waagent.RunGetOutput(cmd, chk_err)
    else:
        try:
            output = subprocess.check_output(cmd,
                                             stderr=subprocess.STDOUT,
                                             shell=True)
            exit_code = 0
        except subprocess.CalledProcessError as e:
            exit_code = e.returncode
            output = e.output

    return exit_code, output.encode('utf-8').strip()
    def test_cron(self):
        print 'test_cron'

        enable_time = time.time()
        protect_settings['startTime'] = time.strftime(
            '%H:%M', time.localtime(enable_time + 180))
        delta_time = int(time.strftime('%S',
                                       time.localtime(enable_time + 120)))
        MyPatching.download_duration = 60

        with self.assertRaises(SystemExit) as cm:
            enable()
        self.assertEqual(cm.exception.code, 0)
        self.assertEqual(get_status("Enable"), 'success')
        download_cmd = 'python test_handler.py -download'
        patch_cmd = 'python test_handler.py -patch'
        crontab_content = waagent.GetFileContents('/etc/crontab')
        self.assertTrue(download_cmd in crontab_content)
        self.assertTrue(patch_cmd in crontab_content)

        time.sleep(180 + 5)
        distro = DistInfo()[0]
        if 'SuSE' in distro:
            find_cron = 'grep CRON /var/log/messages'
        elif 'Ubuntu' in distro:
            find_cron = 'grep CRON /var/log/syslog'
        else:
            find_cron = 'cat /var/log/cron'

        if 'SuSE' in distro:
            find_download_time = "grep '" + time.strftime(
                '%Y-%m-%dT%H:%M', time.localtime(enable_time + 120)) + "'"
            find_patch_time = "grep '" + time.strftime(
                '%Y-%m-%dT%H:%M', time.localtime(enable_time + 180)) + "'"

        else:
            day = int(time.strftime('%d', time.localtime(enable_time)))
            find_download_time = "grep '" + str(day) + time.strftime(
                ' %H:%M', time.localtime(enable_time + 120)) + "'"
            find_patch_time = "grep '" + str(day) + time.strftime(
                ' %H:%M', time.localtime(enable_time + 180)) + "'"

        find_download = "grep 'python test_handler.py -download'"
        find_patch = "grep 'python test_handler.py -patch'"
        retcode, output = waagent.RunGetOutput(find_cron + ' | ' +
                                               find_download_time + ' | ' +
                                               find_download)
        self.assertTrue(output)
        retcode, output = waagent.RunGetOutput(find_cron + ' | ' +
                                               find_patch_time + ' | ' +
                                               find_patch)
        self.assertTrue(output)
    def check(self, category):
        """
        Check valid upgrades,
        Return the package list to download & upgrade
        """
        # Perform upgrade or dist-upgrade as appropriate
        if self.dist_upgrade_all:
            self.log_and_syslog(logging.INFO,
                                "Performing dist-upgrade for ALL packages")
            check_cmd = self.check_cmd_distupgrade
        else:
            check_cmd = self.check_cmd

        # If upgrading only required/security patches, append the command suffix
        # Otherwise, assume all packages will be upgraded
        if category == self.category_required:
            check_cmd = check_cmd + self.check_security_suffix
        retcode, output = waagent.RunGetOutput(check_cmd)
        to_download = [
            line.split()[1] for line in output.split('\n')
            if line.startswith('Inst')
        ]

        # Azure repo assumes upgrade may have dependency changes
        if retcode != 0:
            self.log_and_syslog(logging.WARNING,
                                "Failed to get list of upgradeable packages")
        elif self.is_string_none_or_empty(self.dist_upgrade_list):
            self.log_and_syslog(
                logging.INFO,
                "Dist upgrade list not specified, will perform normal patch")
        elif not os.path.isfile(self.dist_upgrade_list):
            self.log_and_syslog(
                logging.WARNING,
                "Dist upgrade list was specified but file [{0}] does not exist"
                .format(self.dist_upgrade_list))
        else:
            self.log_and_syslog(
                logging.INFO, "Running dist-upgrade using {0}".format(
                    self.dist_upgrade_list))
            self.check_azure_cmd = 'apt-get -qq -s dist-upgrade -o Dir::Etc::SourceList={0}'.format(
                self.dist_upgrade_list)
            retcode, azoutput = waagent.RunGetOutput(self.check_azure_cmd)
            azure_to_download = [
                line.split()[1] for line in azoutput.split('\n')
                if line.startswith('Inst')
            ]
            to_download += list(set(azure_to_download) - set(to_download))

        return retcode, to_download
示例#6
0
 def try_package_with_autofix(self, cmd):
     retcode, output = waagent.RunGetOutput(cmd)
     if retcode == 0:
         return retcode, output
     # An error occurred while running the command. Try to recover.
     # Unfortunately apt-get returns code 100 regardless of the error encountered, 
     # so we can't smartly detect the cause of failure
     self.log_and_syslog(logging.WARNING, "Error running command ({0}). Will try to correct package state ({1}). Error was {2}".format(cmd, self.fix_cmd, output))
     retcode, output = waagent.RunGetOutput(self.fix_cmd)
     if retcode != 0:
         self.log_and_syslog(logging.WARNING, "Error correcting package state ({0}). Error was {1}".format(self.fix_cmd, output))
     retcode, output = waagent.RunGetOutput(cmd)
     if retcode != 0:
         self.log_and_syslog(logging.WARNING, "Unable to run ({0}) on second attempt. Giving up. Error was {1}".format(cmd, output))
     return retcode, output
    def _parse_config(self, ctxt):
        config = None
        try:
            config = json.loads(ctxt)
        except:
            self.error('JSON exception decoding ' + ctxt)

        if config == None:
            self.error("JSON error processing settings file:" + ctxt)
        else:
            handlerSettings = config['runtimeSettings'][0]['handlerSettings']
            if handlerSettings.has_key('protectedSettings') and \
                    handlerSettings.has_key("protectedSettingsCertThumbprint") and \
                    handlerSettings['protectedSettings'] is not None and \
                    handlerSettings["protectedSettingsCertThumbprint"] is not None:
                protectedSettings = handlerSettings['protectedSettings']
                thumb = handlerSettings['protectedSettingsCertThumbprint']
                cert = waagent.LibDir + '/' + thumb + '.crt'
                pkey = waagent.LibDir + '/' + thumb + '.prv'
                waagent.SetFileContents('/tmp/kk', protectedSettings)
                cleartxt = None
                cleartxt = waagent.RunGetOutput("base64 -d /tmp/kk | openssl smime  -inform DER -decrypt -recip " + cert + "  -inkey " + pkey)[1]
                os.remove("/tmp/kk")
                if cleartxt == None:
                    self.error("OpenSSh decode error using  thumbprint " + thumb)
                    do_exit(1,operation,'error','1', operation + ' Failed')
                jctxt = ''
                try:
                    jctxt = json.loads(cleartxt)
                except:
                    self.error('JSON exception decoding ' + cleartxt)
                handlerSettings['protectedSettings'] = jctxt
                self.log('Config decoded correctly.')
        return config
示例#8
0
def install_package(package_name):
    if DistroName == "centos" or DistroName == "redhat":
        cmd = "yum -y install " + package_name
    elif DistroName == "ubuntu":
        cmd = "apt-get -y install " + package_name
    elif DistroName == "suse":
        if not os.listdir('/etc/zypp/repos.d'):
            waagent.Run("zypper ar http://download.opensuse.org/distribution/13.2/repo/oss/suse/ opensuse")
            cmd = "zypper -n --gpg-auto-import-keys install --force-resolution -l " + package_name
        else:
            cmd = "zypper -n install --force-resolution -l " + package_name
    else:
        raise Exception("Unsupported Linux Distro.")
    waagent.Log("The command to install {0}: {1}".format(package_name, cmd))
    attempt = 1
    while(True):
        waagent.Log("Installing package {0} (Attempt {1})".format(package_name, attempt))
        retcode, retoutput = waagent.RunGetOutput(cmd)
        if retcode == 0:
            waagent.Log("package {0} installation succeeded".format(package_name))
            break
        else:
            waagent.Log("package {0} installation failed {1}:\n {2}".format(package_name, retcode, retoutput))
            if attempt < 3:
                attempt += 1
                time.sleep(5)
                if DistroName == 'suse' and retcode == 104:
                    waagent.Run("zypper ar http://download.opensuse.org/distribution/13.2/repo/oss/suse/ opensuse")
                    cmd = "zypper -n --gpg-auto-import-keys install --force-resolution -l " + package_name
                continue
            else:
                raise Exception("failed to install package {0}:{1}".format(package_name, retcode))
def check_for_supported_waagent_and_distro_version():
    """
    Checks & returns if the installed waagent and the Linux distro/version are supported by this LAD.
    :rtype: bool
    :return: True iff so.
    """
    for notsupport in ('WALinuxAgent-2.0.5', 'WALinuxAgent-2.0.4', 'WALinuxAgent-1'):
        code, str_ret = waagent.RunGetOutput("grep 'GuestAgentVersion.*" + notsupport + "' /usr/sbin/waagent",
                                             chk_err=False)
        if code == 0 and str_ret.find(notsupport) > -1:
            hutil.log("cannot run this extension on  " + notsupport)
            hutil.do_status_report(g_ext_op_type, "error", '1', "cannot run this extension on  " + notsupport)
            return False

    if g_dist_config is None:
        msg = ("LAD does not support distro/version ({0}); not installed. This extension install/enable operation is "
               "still considered a success as it's an external error.").format(str(platform.dist()))
        hutil.log(msg)
        hutil.do_status_report(g_ext_op_type, "success", '0', msg)
        waagent.AddExtensionEvent(name=hutil.get_name(),
                                  op=g_ext_op_type,
                                  isSuccess=True,
                                  version=hutil.get_extension_version(),
                                  message="Can't be installed on this OS " + str(platform.dist()))
        return False

    return True
示例#10
0
 def check_needs_restart(self):
     self.needs_restart.extend(self.get_pkg_needs_restart())
     patched_files = dict()
     for pkg in self.get_pkg_patched():
         cmd = ' '.join([self.pkg_query_cmd, pkg])
         try:
             retcode, output = waagent.RunGetOutput(cmd)
             patched_files[os.path.basename(pkg)] = [
                 filename for filename in output.split("\n")
                 if os.path.isfile(filename)
             ]
         except Exception:
             self.hutil.log_and_syslog(logging.ERROR, "Failed to " + cmd)
     # for k,v in patched_files.items():
     #     self.hutil.log_and_syslog(logging.INFO, k + ": " + " ".join(v))
     open_deleted_files = list()
     for filename in self.open_deleted_files_after:
         if filename not in self.open_deleted_files_before:
             open_deleted_files.append(filename)
     # self.hutil.log_and_syslog(logging.INFO, "Open deleted files: " + " ".join(open_deleted_files))
     for pkg, files in patched_files.items():
         for filename in files:
             realpath = os.path.realpath(filename)
             if realpath in open_deleted_files and pkg not in self.needs_restart:
                 self.needs_restart.append(pkg)
     msg = "Packages needs to restart: "
     pkgs = " ".join(self.needs_restart)
     if pkgs:
         msg += pkgs
     else:
         msg = "There is no package which needs to restart"
     self.hutil.log_and_syslog(logging.INFO, msg)
def LogRunGetOutPut(cmd, should_log=True):
    if should_log:
        hutil.log("RunCmd "+cmd)
    error, msg = waagent.RunGetOutput(cmd, chk_err=should_log)
    if should_log:
        hutil.log("Return "+str(error)+":"+msg)
    return error, msg
 def info_pkg(self, pkg_name):
     """
     Return details about a package        
     """
     retcode, output = waagent.RunGetOutput(self.status_cmd + ' ' +
                                            pkg_name)
     if retcode != 0:
         self.hutil.error(output)
         return None
     installed_pkg_info_list = output.rpartition(
         'Available Packages')[0].strip().split('\n')
     available_pkg_info_list = output.rpartition(
         'Available Packages')[-1].strip().split('\n')
     pkg_info = dict()
     pkg_info['installed'] = dict()
     pkg_info['available'] = dict()
     for item in installed_pkg_info_list:
         if item.startswith('Name'):
             pkg_info['installed']['name'] = item.split(':')[-1].strip()
         elif item.startswith('Arch'):
             pkg_info['installed']['arch'] = item.split(':')[-1].strip()
         elif item.startswith('Version'):
             pkg_info['installed']['version'] = item.split(':')[-1].strip()
         elif item.startswith('Release'):
             pkg_info['installed']['release'] = item.split(':')[-1].strip()
     for item in available_pkg_info_list:
         if item.startswith('Name'):
             pkg_info['available']['name'] = item.split(':')[-1].strip()
         elif item.startswith('Arch'):
             pkg_info['available']['arch'] = item.split(':')[-1].strip()
         elif item.startswith('Version'):
             pkg_info['available']['version'] = item.split(':')[-1].strip()
         elif item.startswith('Release'):
             pkg_info['available']['release'] = item.split(':')[-1].strip()
     return pkg_info
示例#13
0
    def _parse_config(self, ctxt):
        config = None
        try:
            config = json.loads(ctxt)
        except:
            self.error('JSON exception decoding ' + ctxt)

        if config == None:
            self.error("JSON error processing settings file:" + ctxt)
        else:
            handlerSettings = config['runtimeSettings'][0]['handlerSettings']
            if handlerSettings.has_key('protectedSettings') and \
                    handlerSettings.has_key("protectedSettingsCertThumbprint") and \
                    handlerSettings['protectedSettings'] is not None and \
                    handlerSettings["protectedSettingsCertThumbprint"] is not None:
                protectedSettings = handlerSettings['protectedSettings']
                thumb = handlerSettings['protectedSettingsCertThumbprint']
                cert = waagent.LibDir + '/' + thumb + '.crt'
                pkey = waagent.LibDir + '/' + thumb + '.prv'
                f = tempfile.NamedTemporaryFile(delete=False)
                f.close()
                waagent.SetFileContents(f.name, config['runtimeSettings'][0]['handlerSettings']['protectedSettings'])
                cleartxt = None
                cleartxt = waagent.RunGetOutput(self.patching.base64_path + " -d " + f.name + " | " + self.patching.openssl_path + " smime  -inform DER -decrypt -recip " + cert + "  -inkey " + pkey)[1]
                if cleartxt == None:
                    self.error("OpenSSh decode error using  thumbprint " + thumb)
                    do_exit(1, self.operation,'error','1', self.operation + ' Failed')
                jctxt = ''
                try:
                    jctxt = json.loads(cleartxt)
                except:
                    self.error('JSON exception decoding ' + cleartxt)
                handlerSettings['protectedSettings'] = jctxt
                self.log('Config decoded correctly.')
        return config
示例#14
0
 def report(self):
     """
     TODO: Report the detail status of patching
     """
     for package_patched in self.patched:
         retcode,output = waagent.RunGetOutput(self.status_cmd + ' ' + package_patched)
         output = output.split('\n\n')[0]
         self.hutil.log(output)
示例#15
0
def _is_nodemanager_daemon(pid):
    retcode, output = waagent.RunGetOutput("ps -p {0} -o cmd=".format(pid))
    if retcode == 0:
        waagent.Log("The cmd for process {0} is {1}".format(pid, output))
        pattern = r'(.*[/\s])?{0}\s+[-/]*daemon$'.format(os.path.basename(__file__))
        if re.match(pattern, output):
            return True
    waagent.Log("The process {0} is not HPC Linux node manager daemon".format(pid))
    return False
示例#16
0
 def check_open_deleted_files(self):
     ret = list()
     retcode, output = waagent.RunGetOutput('lsof | grep "DEL"')
     if retcode == 0:
         for line in output.split('\n'):
             if line:
                 filename = line.split()[-1]
                 if filename not in ret:
                     ret.append(filename)
     return ret
    def _parse_config(self, config_txt):
        # pre : config_txt is a text string containing JSON configuration settings
        # post: handlerSettings is initialized with these settings and the config
        #       object is returned.  If an error occurs, None is returned.
        if not config_txt:
            self.error('empty config, nothing to parse')
            return None

        config = None
        try:
            config = json.loads(config_txt)
        except:
            self.error('invalid config, could not parse: ' + str(config_txt))

        if config:
            handlerSettings = config['runtimeSettings'][0]['handlerSettings']

            # skip unnecessary decryption of protected settings for query status
            # operations, to avoid timeouts in case of multiple settings files
            if handlerSettings.has_key('publicSettings'):
                ps = handlerSettings.get('publicSettings')
                op = ps.get(CommonVariables.EncryptionEncryptionOperationKey)
                if op == CommonVariables.QueryEncryptionStatus:
                    return config

            if handlerSettings.has_key('protectedSettings') and \
                    handlerSettings.has_key("protectedSettingsCertThumbprint") and \
                    handlerSettings['protectedSettings'] is not None and \
                    handlerSettings["protectedSettingsCertThumbprint"] is not None:
                thumb = handlerSettings['protectedSettingsCertThumbprint']
                cert = waagent.LibDir + '/' + thumb + '.crt'
                pkey = waagent.LibDir + '/' + thumb + '.prv'
                f = tempfile.NamedTemporaryFile(delete=False)
                f.close()
                waagent.SetFileContents(
                    f.name, config['runtimeSettings'][0]['handlerSettings']
                    ['protectedSettings'])
                cleartxt = None
                cleartxt = waagent.RunGetOutput(
                    self.patching.base64_path + " -d " + f.name + " | " +
                    self.patching.openssl_path +
                    " smime  -inform DER -decrypt -recip " + cert +
                    "  -inkey " + pkey)[1]
                if cleartxt == None:
                    self.error("OpenSSh decode error using thumbprint " +
                               thumb)
                    self.do_exit(1, self.operation, 'error', '1',
                                 self.operation + ' Failed')
                jctxt = ''
                try:
                    jctxt = json.loads(cleartxt)
                except:
                    self.error('JSON exception loading protected settings')
                handlerSettings['protectedSettings'] = jctxt
        return config
示例#18
0
def get_openssl_version():
    cmd_result = waagent.RunGetOutput("openssl version")
    openssl_version = cmd_result[1].split()[1]
    if re.match('^1.0.*', openssl_version):
        return '100'
    elif re.match('^0.9.8*', openssl_version):
        return '098'
    else:
        error_msg = 'This system does not have a supported version of OpenSSL installed. Supported version: 0.9.8*, 1.0.*'
        hutil.error(error_msg)
        raise Exception(error_msg)                
 def check_missing_dependencies(self):
     retcode, output = waagent.RunGetOutput('package-cleanup --problems',
                                            chk_err=False)
     missing_dependency_list = []
     for line in output.split('\n'):
         if 'requires' not in line:
             continue
         words = line.split()
         missing_dependency = words[words.index('requires') + 1]
         if missing_dependency not in missing_dependency_list:
             missing_dependency_list.append(missing_dependency)
     return missing_dependency_list
示例#20
0
def _mount_cgroup():
    if not os.path.isdir('/cgroup'):
        os.mkdir('/cgroup')
    if not os.listdir('/cgroup'):
        retcode, mount_msg = waagent.RunGetOutput('mount -t cgroup cgroup /cgroup')
        waagent.Log("mount /cgroup directory {0}:{1}".format(retcode, mount_msg))
        if retcode == 0:
            waagent.Log("/cgroup directory is successfully mounted.")
        else:
            raise Exception("failed to mount /cgroup directory")
    else:
        waagent.Log("/cgroup directory was already mounted.")
示例#21
0
def get_openssl_version():
    cmd_result = waagent.RunGetOutput("openssl version")
    openssl_version = cmd_result[1].split()[1]
    if re.match('^1.0.*', openssl_version):
        return '100'
    elif re.match('^0.9.8*', openssl_version):
        return '098'
    else:
        error_msg = 'This system does not have a supported version of OpenSSL installed. Supported version: 0.9.8*, 1.0.*'
        hutil.error(error_msg)
        waagent.AddExtensionEvent(name=ExtensionShortName, op='InstallInProgress', isSuccess=True, message="System doesn't have supported OpenSSL version:" + openssl_version)
        hutil.do_exit(51, 'Install', 'error', '51', openssl_version + 'is not supported.')
示例#22
0
 def __init__(self):
     self.hvName = None;
     self.hvVersion = None;
     root_dir = os.path.dirname(__file__)
     cmd = os.path.join(root_dir, "bin/hvinfo")
     ret, output = waagent.RunGetOutput(cmd, chk_err=False)
     print ret
     if ret ==0 and output is not None:
         lines = output.split("\n")
         if len(lines) >= 2:
             self.hvName = lines[0]
             self.hvVersion = lines[1]
def get_mdsd_process():
    mdsd_pids = []
    if not os.path.exists(MDSDPidFile):
        return mdsd_pids

    with open(MDSDPidFile,"r") as pidfile:
        for pid in pidfile.readlines():
            is_still_alive = waagent.RunGetOutput("cat /proc/"+pid.strip()+"/cmdline",chk_err=False)[1]
            if is_still_alive.find('/waagent/') > 0 :
                mdsd_pids.append(pid.strip())
            else:
                hutil.log("return not alive "+is_still_alive.strip())
    return mdsd_pids
示例#24
0
 def log_run_get_output(self, cmd, should_log=True):
     """
     Execute a command in a subshell
     :param str cmd: The command to be executed
     :param bool should_log: If true, log command execution
     :return (int, str): A tuple of (subshell exit code, contents of stdout)
     """
     if should_log:
         self.logger("RunCmd " + cmd)
     error, msg = waagent.RunGetOutput(cmd, chk_err=should_log)
     if should_log:
         self.logger("Return " + str(error) + ":" + msg)
     return int(error), msg
 def log_run_get_output(self, cmd, should_log=True):
     """
     Execute a command in a subshell
     :param str cmd: The command to be executed
     :param bool should_log: True if command execution should be logged. (False preserves privacy of parameters.)
     :return (int, str): A tuple of (subshell exit code, contents of stdout)
     """
     if should_log:
         self.logger("RunCmd " + cmd)
     error, msg = waagent.RunGetOutput(cmd, chk_err=should_log)
     if should_log:
         self.logger("Return " + str(error) + ":" + msg)
     return int(error), str(msg)
 def test_creat_newuser(self):
     settings = {}
     settings['username'] = '******'
     settings['password'] = '******'
     waagent.Run('userdel %s' % settings['username'])
     vmaccess._set_user_account_pub_key(settings, hutil)
     waagent.Run("echo 'exit' > /tmp/exit.sh")
     cmd_result = waagent.RunGetOutput(
         "sshpass -p 'User@123' ssh -o StrictHostKeyChecking=no" +
         " %s@localhost < /tmp/exit.sh" % settings['username'])
     self.assertEqual(cmd_result[0], 0)
     waagent.Run("rm exit.sh -f")
     waagent.Run('userdel %s' % settings['username'])
    def _parse_config(self, config_txt):
        config = None
        try:
            config = json.loads(config_txt)
        except:
            self.error('JSON exception decoding ' + config_txt)

        if config == None:
            self.error("JSON error processing settings file:" + config_txt)
        else:
            handlerSettings = config['runtimeSettings'][0]['handlerSettings']

            # skip unnecessary decryption of protected settings for query status
            # operations, to avoid timeouts in case of multiple settings files
            if handlerSettings.has_key('publicSettings'):
                ps = handlerSettings.get('publicSettings')
                op = ps.get(CommonVariables.EncryptionEncryptionOperationKey)
                if op == CommonVariables.QueryEncryptionStatus:
                    return config

            if handlerSettings.has_key('protectedSettings') and \
                    handlerSettings.has_key("protectedSettingsCertThumbprint") and \
                    handlerSettings['protectedSettings'] is not None and \
                    handlerSettings["protectedSettingsCertThumbprint"] is not None:
                thumb = handlerSettings['protectedSettingsCertThumbprint']
                cert = waagent.LibDir + '/' + thumb + '.crt'
                pkey = waagent.LibDir + '/' + thumb + '.prv'
                f = tempfile.NamedTemporaryFile(delete=False)
                f.close()
                waagent.SetFileContents(
                    f.name, config['runtimeSettings'][0]['handlerSettings']
                    ['protectedSettings'])
                cleartxt = None
                cleartxt = waagent.RunGetOutput(
                    self.patching.base64_path + " -d " + f.name + " | " +
                    self.patching.openssl_path +
                    " smime  -inform DER -decrypt -recip " + cert +
                    "  -inkey " + pkey)[1]
                if cleartxt == None:
                    self.error("OpenSSh decode error using thumbprint " +
                               thumb)
                    self.do_exit(1, self.operation, 'error', '1',
                                 self.operation + ' Failed')
                jctxt = ''
                try:
                    jctxt = json.loads(cleartxt)
                except:
                    self.error('JSON exception loading protected settings')
                handlerSettings['protectedSettings'] = jctxt
        return config
 def test_reset_ssh_key(self):
     settings = {}
     settings['username'] = '******'
     settings['ssh_key'] = waagent.GetFileContents(
         os.path.join(waagent.LibDir, 'TEST.crt'))
     vmaccess._set_user_account_pub_key(settings, hutil)
     waagent.Run("echo 'exit' > /tmp/exit.sh")
     cmd_result = waagent.RunGetOutput(
         "ssh -o StrictHostKeyChecking=no -i %s" %
         os.path.join(waagent.LibDir, 'TEST.prv') +
         " %s@localhost < /tmp/exit.sh" % settings['username'])
     self.assertEqual(cmd_result[0], 0)
     waagent.Run("rm exit.sh -f")
     waagent.Run('userdel %s' % settings['username'])
示例#29
0
 def check(self, category):
     """
     Check valid upgrades,
     Return the package list to download & upgrade
     """
     if category == self.category_all:
         check_cmd = self.check_cmd
     elif category == self.category_required:
         check_cmd = self.check_security_cmd
     retcode, output = waagent.RunGetOutput(check_cmd)
     to_download = [
         line.split()[1] for line in output.split('\n')
         if line.startswith('Inst')
     ]
     return retcode, to_download
 def test_reset_existing_user(self):
     settings = {}
     settings['username'] = '******'
     settings['password'] = '******'
     waagent.Run('userdel %s' % settings['username'])
     waagent.Run('useradd %s' % settings['username'])
     waagent.MyDistro.changePass(settings['username'], "Quattro!")
     vmaccess._set_user_account_pub_key(settings, hutil)
     waagent.Run("echo 'exit' > /tmp/exit.sh")
     cmd_result = waagent.RunGetOutput(
         "sshpass -p 'User@123' ssh -o StrictHostKeyChecking=no" +
         " %s@localhost < /tmp/exit.sh" % settings['username'])
     self.assertEqual(cmd_result[0], 0)
     waagent.Run("rm exit.sh -f")
     waagent.Run('userdel %s' % settings['username'])