Best Python code snippet using autotest_python
sysctl.py
Source:sysctl.py  
...157                self.set_proc = True158        # Do the work159        if not self.module.check_mode:160            if self.write_file:161                self.write_sysctl()162            if self.write_file and self.args['reload']:163                self.reload_sysctl()164            if self.set_proc:165                self.set_token_value(self.args['name'], self.args['value'])166    def _values_is_equal(self, a, b):167        """Expects two string values. It will split the string by whitespace168        and compare each value. It will return True if both lists are the same,169        contain the same elements and the same order."""170        if a is None or b is None:171            return False172        a = a.split()173        b = b.split()174        if len(a) != len(b):175            return False176        return len([i for i, j in zip(a, b) if i == j]) == len(a)177    def _parse_value(self, value):178        if value is None:179            return ''180        elif isinstance(value, bool):181            if value:182                return '1'183            else:184                return '0'185        elif isinstance(value, basestring):186            if value.lower() in BOOLEANS_TRUE:187                return '1'188            elif value.lower() in BOOLEANS_FALSE:189                return '0'190            else:191                return value.strip()192        else:193            return value194    # ==============================================================195    #   SYSCTL COMMAND MANAGEMENT196    # ==============================================================197    # Use the sysctl command to find the current value198    def get_token_curr_value(self, token):199        if self.platform == 'openbsd':200            # openbsd doesn't support -e, just drop it201            thiscmd = "%s -n %s" % (self.sysctl_cmd, token)202        else:203            thiscmd = "%s -e -n %s" % (self.sysctl_cmd, token)204        rc,out,err = self.module.run_command(thiscmd)205        if rc != 0:206            return None207        else:208            return out209    # Use the sysctl command to set the current value210    def set_token_value(self, token, value):211        if len(value.split()) > 0:212            value = '"' + value + '"'213        if self.platform == 'openbsd':214            # openbsd doesn't accept -w, but since it's not needed, just drop it215            thiscmd = "%s %s=%s" % (self.sysctl_cmd, token, value)216        else:217            thiscmd = "%s -w %s=%s" % (self.sysctl_cmd, token, value)218        rc,out,err = self.module.run_command(thiscmd)219        if rc != 0:220            self.module.fail_json(msg='setting %s failed: %s' % (token, out + err))221        else:222            return rc223    # Run sysctl -p224    def reload_sysctl(self):225        # do it226        if self.platform == 'freebsd':227            # freebsd doesn't support -p, so reload the sysctl service228            rc,out,err = self.module.run_command('/etc/rc.d/sysctl reload')229        elif self.platform == 'openbsd':230            # openbsd doesn't support -p and doesn't have a sysctl service,231            # so we have to set every value with its own sysctl call232            for k, v in self.file_values.items():233                rc = 0234                if k != self.args['name']:235                    rc = self.set_token_value(k, v)236                    if rc != 0:237                        break238            if rc == 0 and self.args['state'] == "present":239                rc = self.set_token_value(self.args['name'], self.args['value'])240        else:241            # system supports reloading via the -p flag to sysctl, so we'll use that242            sysctl_args = [self.sysctl_cmd, '-p', self.sysctl_file]243            if self.args['ignoreerrors']:244                sysctl_args.insert(1, '-e')245            rc,out,err = self.module.run_command(sysctl_args)246        if rc != 0:247            self.module.fail_json(msg="Failed to reload sysctl: %s" % str(out) + str(err))248    # ==============================================================249    #   SYSCTL FILE MANAGEMENT250    # ==============================================================251    # Get the token value from the sysctl file252    def read_sysctl_file(self):253        lines = []254        if os.path.isfile(self.sysctl_file):255            try:256                f = open(self.sysctl_file, "r")257                lines = f.readlines()258                f.close()259            except IOError:260                e = get_exception()261                self.module.fail_json(msg="Failed to open %s: %s" % (self.sysctl_file, str(e)))262        for line in lines:263            line = line.strip()264            self.file_lines.append(line)265            # don't split empty lines or comments266            if not line or line.startswith(("#", ";")):267                continue268            k, v = line.split('=',1)269            k = k.strip()270            v = v.strip()271            self.file_values[k] = v.strip()272    # Fix the value in the sysctl file content273    def fix_lines(self):274        checked = []275        self.fixed_lines = []276        for line in self.file_lines:277            if not line.strip() or line.strip().startswith(("#", ";")):278                self.fixed_lines.append(line)279                continue280            tmpline = line.strip()281            k, v = line.split('=',1)282            k = k.strip()283            v = v.strip()284            if k not in checked:285                checked.append(k)286                if k == self.args['name']:287                    if self.args['state'] == "present":288                        new_line = "%s=%s\n" % (k, self.args['value'])289                        self.fixed_lines.append(new_line)290                else:291                    new_line = "%s=%s\n" % (k, v)292                    self.fixed_lines.append(new_line)293        if self.args['name'] not in checked and self.args['state'] == "present":294            new_line = "%s=%s\n" % (self.args['name'], self.args['value'])295            self.fixed_lines.append(new_line)296    # Completely rewrite the sysctl file297    def write_sysctl(self):298        # open a tmp file299        fd, tmp_path = tempfile.mkstemp('.conf', '.ansible_m_sysctl_', os.path.dirname(self.sysctl_file))300        f = open(tmp_path,"w")301        try:302            for l in self.fixed_lines:303                f.write(l.strip() + "\n")304        except IOError:305            e = get_exception()306            self.module.fail_json(msg="Failed to write to file %s: %s" % (tmp_path, str(e)))307        f.flush()308        f.close()309        # replace the real one310        self.module.atomic_move(tmp_path, self.sysctl_file)311# ==============================================================...check_sysctl.py
Source:check_sysctl.py  
...24"""25import volatility.obj as obj26import volatility.plugins.mac.common as common27# based on sysctl_sysctl_debug_dump_node28class mac_check_sysctl(common.AbstractMacCommand):29    """ Checks for unknown sysctl handlers """30    def _process_sysctl_list(self, sysctl_list, r = 0):31        if type(sysctl_list) == obj.Pointer:32            sysctl_list = sysctl_list.dereference_as("sysctl_oid_list")33        sysctl = sysctl_list.slh_first34        35        # skip the head entry if new list (recursive call)36        if r:37            sysctl = sysctl.oid_link.sle_next38        while sysctl and sysctl.is_valid():39            name = sysctl.oid_name.dereference()40            if len(name) == 0:41                break42            ctltype = sysctl.get_ctltype()...Learn to execute automation testing from scratch with LambdaTest Learning Hub. Right from setting up the prerequisites to run your first automation test, to following best practices and diving deeper into advanced test scenarios. LambdaTest Learning Hubs compile a list of step-by-step guides to help you be proficient with different test automation frameworks i.e. Selenium, Cypress, TestNG etc.
You could also refer to video tutorials over LambdaTest YouTube channel to get step by step demonstration from industry experts.
Get 100 minutes of automation test minutes FREE!!
