Return ss information for Linux distros
    (netstat is deprecated and may not be available)
484195
def _ss_linux():
    '''
    
    '''
    ret = []
    cmd = 'ss -tulpnea'
    out = __salt__['cmd.run'](cmd)
    for line in out.splitlines():
        comps = line.split()
        ss_user = 0
        ss_inode = 0
        ss_program = ''
        length = len(comps)
        if line.startswith('tcp') or line.startswith('udp'):
            i = 6
            while i < (length - 1):
                fields = comps[i].split(":")
                if fields[0] == "users":
                    users = fields[1].split(",")
                    ss_program = users[0].split("\"")[1]

                if fields[0] == "uid":
                    ss_user = fields[1]

                if fields[0] == "ino":
                    ss_inode = fields[1]

                i += 1

        if line.startswith('tcp'):
            ss_state = comps[1]
            if ss_state == "ESTAB":
                ss_state = "ESTABLISHED"
            ret.append({
                'proto': comps[0],
                'recv-q': comps[2],
                'send-q': comps[3],
                'local-address': comps[4],
                'remote-address': comps[5],
                'state': ss_state,
                'user': ss_user,
                'inode': ss_inode,
                'program': ss_program})
        if line.startswith('udp'):
            ret.append({
                'proto': comps[0],
                'recv-q': comps[2],
                'send-q': comps[3],
                'local-address': comps[4],
                'remote-address': comps[5],
                'user': ss_user,
                'inode': ss_inode,
                'program': ss_program})
    return ret
1042698
def ss(name):
    '''
    

    '''
    sanitize_name = six.text_type(name)
    ss_infos = __salt__['cmd.run']("ss -neap")
    found_infos = []
    ret = []
    for info in ss_infos.splitlines():
        if info.find(sanitize_name) != -1:
            found_infos.append(info)
    ret.extend([sanitize_name, found_infos])
    return ret
564195
def distros(ctx, opts, package_format):
    """"""
    # Use stderr for messages if the output is something else (e.g.  # JSON)
    use_stderr = opts.output != "pretty"

    click.echo("Getting list of distributions ... ", nl=False, err=use_stderr)

    context_msg = "Failed to get list of distributions!"
    with handle_api_exceptions(ctx, opts=opts, context_msg=context_msg):
        with maybe_spinner(opts):
            distros_ = list_distros(package_format=package_format)

    click.secho("OK", fg="green", err=use_stderr)

    if utils.maybe_print_as_json(opts, distros_):
        return

    headers = ["Distro", "Release", "Format", "Distro / Release (Identifier)"]
    if package_format:
        headers.remove("Format")

    rows = []
    for distro in sorted(distros_, key=itemgetter("slug")):
        if not distro["versions"]:
            continue

        for release in sorted(distro["versions"], key=itemgetter("slug")):
            row = [
                click.style(distro["name"], fg="cyan"),
                click.style(release["name"], fg="yellow"),
                click.style(distro["format"], fg="blue"),
                "%(distro)s/%(release)s"
                % {
                    "distro": click.style(distro["slug"], fg="magenta"),
                    "release": click.style(release["slug"], fg="green"),
                },
            ]

            if package_format:
                row.pop(2)  # Remove format column

            rows.append(row)

    if distros_:
        click.echo()
        utils.pretty_print_table(headers, rows)

    click.echo()

    num_results = sum(
        1 for distro in distros_ for release in distro["versions"] if release
    )
    list_suffix = "distribution release%s" % ("s" if num_results != 1 else "")
    utils.pretty_print_list_info(num_results=num_results, suffix=list_suffix)
675221
def _netinfo_openbsd():
    '''
    
    '''
    ret = {}
    _fstat_re = re.compile(
        r'internet(6)? (?:stream tcp 0x\S+ (\S+)|dgram udp (\S+))'
        r'(?: [<>=-]+ (\S+))?$'
    )
    out = __salt__['cmd.run']('fstat')
    for line in out.splitlines():
        try:
            user, cmd, pid, _, details = line.split(None, 4)
            ipv6, tcp, udp, remote_addr = _fstat_re.match(details).groups()
        except (ValueError, AttributeError):
            # Line either doesn't have the right number of columns, or the
            # regex which looks for address information did not match. Either
            # way, ignore this line and continue on to the next one.
            continue
        if tcp:
            local_addr = tcp
            proto = 'tcp{0}'.format('' if ipv6 is None else ipv6)
        else:
            local_addr = udp
            proto = 'udp{0}'.format('' if ipv6 is None else ipv6)
        if ipv6:
            # IPv6 addresses have the address part enclosed in brackets (if the
            # address part is not a wildcard) to distinguish the address from
            # the port number. Remove them.
            local_addr = ''.join(x for x in local_addr if x not in '[]')

        # Normalize to match netstat output
        local_addr = '.'.join(local_addr.rsplit(':', 1))
        if remote_addr is None:
            remote_addr = '*.*'
        else:
            remote_addr = '.'.join(remote_addr.rsplit(':', 1))

        ret.setdefault(
            local_addr, {}).setdefault(
                remote_addr, {}).setdefault(
                    proto, {}).setdefault(
                        pid, {})['user'] = user
        ret[local_addr][remote_addr][proto][pid]['cmd'] = cmd
    return ret
480529
def verify_system_status(self):
        """"""
        if not sys.platform.startswith('linux'):
            raise InstallError('Supported platform is Linux only.')

        if self.python.is_system_python():
            if self.python.is_python_binding_installed():
                message = '''
RPM Python binding already installed on system Python.
Nothing to do.
'''
                Log.info(message)
                raise InstallSkipError(message)
            elif self.sys_installed:
                pass
            else:
                message = '''
RPM Python binding on system Python should be installed manually.
Install the proper RPM package of python{,2,3}-rpm,
or set a environment variable RPM_PY_SYS=true
'''
                raise InstallError(message)

        if self.rpm.is_system_rpm():
            self.verify_package_status()
842010
def system_info(conf, args):
    """"""
    src = conf.config['instances'][args.src]
    src_url = api.build_system_url(build_instance_url(src))
    src_auth = tuple([conf.creds['instances'][args.src]['user'],
                      conf.creds['instances'][args.src]['pass']])
    verify_ssl = src.get('verify_ssl', True)
    sysinfo_json = api.system_info(src_url, src_auth, verify_ssl)
    return sysinfo_json
213361
def _ps(self, sys_output):
        
        '''  '''
        
        import re
        gap_pattern = re.compile('\t|\s{2,}')
        container_list = []
        output_lines = sys_output.split('\n')
        column_headers = gap_pattern.split(output_lines[0])
        for i in range(1,len(output_lines)):
            columns = gap_pattern.split(output_lines[i])
            container_details = {}
            if len(columns) > 1:
                for j in range(len(column_headers)):
                    container_details[column_headers[j]] = ''
                    if j <= len(columns) - 1:
                        container_details[column_headers[j]] = columns[j]
        # stupid hack for possible empty port column
                if container_details['PORTS'] and not container_details['NAMES']:
                    from copy import deepcopy
                    container_details['NAMES'] = deepcopy(container_details['PORTS'])
                    container_details['PORTS'] = ''
                container_list.append(container_details)
    
        return container_list
436809
def _hw_data(osdata):
    '''
    
    '''

    if salt.utils.platform.is_proxy():
        return {}

    grains = {}
    if osdata['kernel'] == 'Linux' and os.path.exists('/sys/class/dmi/id'):
        # On many Linux distributions basic firmware information is available via sysfs
        # requires CONFIG_DMIID to be enabled in the Linux kernel configuration
        sysfs_firmware_info = {
            'biosversion': 'bios_version',
            'productname': 'product_name',
            'manufacturer': 'sys_vendor',
            'biosreleasedate': 'bios_date',
            'uuid': 'product_uuid',
            'serialnumber': 'product_serial'
        }
        for key, fw_file in sysfs_firmware_info.items():
            contents_file = os.path.join('/sys/class/dmi/id', fw_file)
            if os.path.exists(contents_file):
                try:
                    with salt.utils.files.fopen(contents_file, 'r') as ifile:
                        grains[key] = salt.utils.stringutils.to_unicode(ifile.read().strip(), errors='replace')
                        if key == 'uuid':
                            grains['uuid'] = grains['uuid'].lower()
                except (IOError, OSError) as err:
                    # PermissionError is new to Python 3, but corresponds to the EACESS and
                    # EPERM error numbers. Use those instead here for PY2 compatibility.
                    if err.errno == EACCES or err.errno == EPERM:
                        # Skip the grain if non-root user has no access to the file.
                        pass
    elif salt.utils.path.which_bin(['dmidecode', 'smbios']) is not None and not (
            salt.utils.platform.is_smartos() or
            (  # SunOS on SPARC - 'smbios: failed to load SMBIOS: System does not export an SMBIOS table'
                osdata['kernel'] == 'SunOS' and
                osdata['cpuarch'].startswith('sparc')
            )):
        # On SmartOS (possibly SunOS also) smbios only works in the global zone
        # smbios is also not compatible with linux's smbios (smbios -s = print summarized)
        grains = {
            'biosversion': __salt__['smbios.get']('bios-version'),
            'productname': __salt__['smbios.get']('system-product-name'),
            'manufacturer': __salt__['smbios.get']('system-manufacturer'),
            'biosreleasedate': __salt__['smbios.get']('bios-release-date'),
            'uuid': __salt__['smbios.get']('system-uuid')
        }
        grains = dict([(key, val) for key, val in grains.items() if val is not None])
        uuid = __salt__['smbios.get']('system-uuid')
        if uuid is not None:
            grains['uuid'] = uuid.lower()
        for serial in ('system-serial-number', 'chassis-serial-number', 'baseboard-serial-number'):
            serial = __salt__['smbios.get'](serial)
            if serial is not None:
                grains['serialnumber'] = serial
                break
    elif salt.utils.path.which_bin(['fw_printenv']) is not None:
        # ARM Linux devices expose UBOOT env variables via fw_printenv
        hwdata = {
            'manufacturer': 'manufacturer',
            'serialnumber': 'serial#',
            'productname': 'DeviceDesc',
        }
        for grain_name, cmd_key in six.iteritems(hwdata):
            result = __salt__['cmd.run_all']('fw_printenv {0}'.format(cmd_key))
            if result['retcode'] == 0:
                uboot_keyval = result['stdout'].split('=')
                grains[grain_name] = _clean_value(grain_name, uboot_keyval[1])
    elif osdata['kernel'] == 'FreeBSD':
        # On FreeBSD /bin/kenv (already in base system)
        # can be used instead of dmidecode
        kenv = salt.utils.path.which('kenv')
        if kenv:
            # In theory, it will be easier to add new fields to this later
            fbsd_hwdata = {
                'biosversion': 'smbios.bios.version',
                'manufacturer': 'smbios.system.maker',
                'serialnumber': 'smbios.system.serial',
                'productname': 'smbios.system.product',
                'biosreleasedate': 'smbios.bios.reldate',
                'uuid': 'smbios.system.uuid',
            }
            for key, val in six.iteritems(fbsd_hwdata):
                value = __salt__['cmd.run']('{0} {1}'.format(kenv, val))
                grains[key] = _clean_value(key, value)
    elif osdata['kernel'] == 'OpenBSD':
        sysctl = salt.utils.path.which('sysctl')
        hwdata = {'biosversion': 'hw.version',
                  'manufacturer': 'hw.vendor',
                  'productname': 'hw.product',
                  'serialnumber': 'hw.serialno',
                  'uuid': 'hw.uuid'}
        for key, oid in six.iteritems(hwdata):
            value = __salt__['cmd.run']('{0} -n {1}'.format(sysctl, oid))
            if not value.endswith(' value is not available'):
                grains[key] = _clean_value(key, value)
    elif osdata['kernel'] == 'NetBSD':
        sysctl = salt.utils.path.which('sysctl')
        nbsd_hwdata = {
            'biosversion': 'machdep.dmi.board-version',
            'manufacturer': 'machdep.dmi.system-vendor',
            'serialnumber': 'machdep.dmi.system-serial',
            'productname': 'machdep.dmi.system-product',
            'biosreleasedate': 'machdep.dmi.bios-date',
            'uuid': 'machdep.dmi.system-uuid',
        }
        for key, oid in six.iteritems(nbsd_hwdata):
            result = __salt__['cmd.run_all']('{0} -n {1}'.format(sysctl, oid))
            if result['retcode'] == 0:
                grains[key] = _clean_value(key, result['stdout'])
    elif osdata['kernel'] == 'Darwin':
        grains['manufacturer'] = 'Apple Inc.'
        sysctl = salt.utils.path.which('sysctl')
        hwdata = {'productname': 'hw.model'}
        for key, oid in hwdata.items():
            value = __salt__['cmd.run']('{0} -b {1}'.format(sysctl, oid))
            if not value.endswith(' is invalid'):
                grains[key] = _clean_value(key, value)
    elif osdata['kernel'] == 'SunOS' and osdata['cpuarch'].startswith('sparc'):
        # Depending on the hardware model, commands can report different bits
        # of information.  With that said, consolidate the output from various
        # commands and attempt various lookups.
        data = ""
        for (cmd, args) in (('/usr/sbin/prtdiag', '-v'), ('/usr/sbin/prtconf', '-vp'), ('/usr/sbin/virtinfo', '-a')):
            if salt.utils.path.which(cmd):  # Also verifies that cmd is executable
                data += __salt__['cmd.run']('{0} {1}'.format(cmd, args))
                data += '\n'

        sn_regexes = [
            re.compile(r) for r in [
                r'(?im)^\s*Chassis\s+Serial\s+Number\n-+\n(\S+)',  # prtdiag
                r'(?im)^\s*chassis-sn:\s*(\S+)',  # prtconf
                r'(?im)^\s*Chassis\s+Serial#:\s*(\S+)',  # virtinfo
            ]
        ]

        obp_regexes = [
            re.compile(r) for r in [
                r'(?im)^\s*System\s+PROM\s+revisions.*\nVersion\n-+\nOBP\s+(\S+)\s+(\S+)',  # prtdiag
                r'(?im)^\s*version:\s*\'OBP\s+(\S+)\s+(\S+)',  # prtconf
            ]
        ]

        fw_regexes = [
            re.compile(r) for r in [
                r'(?im)^\s*Sun\s+System\s+Firmware\s+(\S+)\s+(\S+)',  # prtdiag
            ]
        ]

        uuid_regexes = [
            re.compile(r) for r in [
                r'(?im)^\s*Domain\s+UUID:\s*(\S+)',  # virtinfo
            ]
        ]

        manufacture_regexes = [
            re.compile(r) for r in [
                r'(?im)^\s*System\s+Configuration:\s*(.*)(?=sun)',  # prtdiag
            ]
        ]

        product_regexes = [
            re.compile(r) for r in [
                r'(?im)^\s*System\s+Configuration:\s*.*?sun\d\S+[^\S\r\n]*(.*)',  # prtdiag
                r'(?im)^[^\S\r\n]*banner-name:[^\S\r\n]*(.*)',  # prtconf
                r'(?im)^[^\S\r\n]*product-name:[^\S\r\n]*(.*)',  # prtconf
            ]
        ]

        sn_regexes = [
            re.compile(r) for r in [
                r'(?im)Chassis\s+Serial\s+Number\n-+\n(\S+)',  # prtdiag
                r'(?i)Chassis\s+Serial#:\s*(\S+)',  # virtinfo
                r'(?i)chassis-sn:\s*(\S+)',  # prtconf
            ]
        ]

        obp_regexes = [
            re.compile(r) for r in [
                r'(?im)System\s+PROM\s+revisions.*\nVersion\n-+\nOBP\s+(\S+)\s+(\S+)',  # prtdiag
                r'(?im)version:\s*\'OBP\s+(\S+)\s+(\S+)',  # prtconf
            ]
        ]

        fw_regexes = [
            re.compile(r) for r in [
                r'(?i)Sun\s+System\s+Firmware\s+(\S+)\s+(\S+)',  # prtdiag
            ]
        ]

        uuid_regexes = [
            re.compile(r) for r in [
                r'(?i)Domain\s+UUID:\s+(\S+)',  # virtinfo
            ]
        ]

        for regex in sn_regexes:
            res = regex.search(data)
            if res and len(res.groups()) >= 1:
                grains['serialnumber'] = res.group(1).strip().replace("'", "")
                break

        for regex in obp_regexes:
            res = regex.search(data)
            if res and len(res.groups()) >= 1:
                obp_rev, obp_date = res.groups()[0:2]  # Limit the number in case we found the data in multiple places
                grains['biosversion'] = obp_rev.strip().replace("'", "")
                grains['biosreleasedate'] = obp_date.strip().replace("'", "")

        for regex in fw_regexes:
            res = regex.search(data)
            if res and len(res.groups()) >= 1:
                fw_rev, fw_date = res.groups()[0:2]
                grains['systemfirmware'] = fw_rev.strip().replace("'", "")
                grains['systemfirmwaredate'] = fw_date.strip().replace("'", "")
                break

        for regex in uuid_regexes:
            res = regex.search(data)
            if res and len(res.groups()) >= 1:
                grains['uuid'] = res.group(1).strip().replace("'", "")
                break

        for regex in manufacture_regexes:
            res = regex.search(data)
            if res and len(res.groups()) >= 1:
                grains['manufacture'] = res.group(1).strip().replace("'", "")
                break

        for regex in product_regexes:
            res = regex.search(data)
            if res and len(res.groups()) >= 1:
                t_productname = res.group(1).strip().replace("'", "")
                if t_productname:
                    grains['product'] = t_productname
                    grains['productname'] = t_productname
                    break
    elif osdata['kernel'] == 'AIX':
        cmd = salt.utils.path.which('prtconf')
        if cmd:
            data = __salt__['cmd.run']('{0}'.format(cmd)) + os.linesep
            for dest, regstring in (('serialnumber', r'(?im)^\s*Machine\s+Serial\s+Number:\s+(\S+)'),
                                    ('systemfirmware', r'(?im)^\s*Firmware\s+Version:\s+(.*)')):
                for regex in [re.compile(r) for r in [regstring]]:
                    res = regex.search(data)
                    if res and len(res.groups()) >= 1:
                        grains[dest] = res.group(1).strip().replace("'", '')

            product_regexes = [re.compile(r'(?im)^\s*System\s+Model:\s+(\S+)')]
            for regex in product_regexes:
                res = regex.search(data)
                if res and len(res.groups()) >= 1:
                    grains['manufacturer'], grains['productname'] = res.group(1).strip().replace("'", "").split(",")
                    break
        else:
            log.error('The \'prtconf\' binary was not found in $PATH.')

    elif osdata['kernel'] == 'AIX':
        cmd = salt.utils.path.which('prtconf')
        if data:
            data = __salt__['cmd.run']('{0}'.format(cmd)) + os.linesep
            for dest, regstring in (('serialnumber', r'(?im)^\s*Machine\s+Serial\s+Number:\s+(\S+)'),
                                    ('systemfirmware', r'(?im)^\s*Firmware\s+Version:\s+(.*)')):
                for regex in [re.compile(r) for r in [regstring]]:
                    res = regex.search(data)
                    if res and len(res.groups()) >= 1:
                        grains[dest] = res.group(1).strip().replace("'", '')

            product_regexes = [re.compile(r'(?im)^\s*System\s+Model:\s+(\S+)')]
            for regex in product_regexes:
                res = regex.search(data)
                if res and len(res.groups()) >= 1:
                    grains['manufacturer'], grains['productname'] = res.group(1).strip().replace("'", "").split(",")
                    break
        else:
            log.error('The \'prtconf\' binary was not found in $PATH.')

    return grains
172254
def _load_fsstat_data(self, timeout=3):
        """"""

        def stats_thread():
            try:
                cmd = ['fsstat', self.get_raw_path(), '-o', str(self.offset // self.disk.block_size)]

                # Setting the fstype explicitly makes fsstat much faster and more reliable
                # In some versions, the auto-detect yaffs2 check takes ages for large images
                fstype = {
                    "ntfs": "ntfs", "fat": "fat", "ext": "ext", "iso": "iso9660", "hfs+": "hfs",
                    "ufs": "ufs", "swap": "swap", "exfat": "exfat",
                }.get(self.fstype, None)
                if fstype:
                    cmd.extend(["-f", fstype])

                logger.debug('$ {0}'.format(' '.join(cmd)))
                stats_thread.process = subprocess.Popen(cmd, stdout=subprocess.PIPE, stderr=subprocess.PIPE)

                for line in iter(stats_thread.process.stdout.readline, b''):
                    line = line.decode('utf-8')
                    logger.debug('< {0}'.format(line))
                    if line.startswith("File System Type:"):
                        self.info['statfstype'] = line[line.index(':') + 2:].strip()
                    elif line.startswith("Last Mount Point:") or line.startswith("Last mounted on:"):
                        self.info['lastmountpoint'] = line[line.index(':') + 2:].strip().replace("//", "/")
                    elif line.startswith("Volume Name:") and not self.info.get('label'):
                        self.info['label'] = line[line.index(':') + 2:].strip()
                    elif line.startswith("Version:"):
                        self.info['version'] = line[line.index(':') + 2:].strip()
                    elif line.startswith("Source OS:"):
                        self.info['version'] = line[line.index(':') + 2:].strip()
                    elif 'CYLINDER GROUP INFORMATION' in line or 'BLOCK GROUP INFORMATION' in line:
                        # noinspection PyBroadException
                        try:
                            stats_thread.process.terminate()
                            logger.debug("Terminated fsstat at cylinder/block group information.")
                        except Exception:
                            pass
                        break

                if self.info.get('lastmountpoint') and self.info.get('label'):
                    self.info['label'] = "{0} ({1})".format(self.info['lastmountpoint'], self.info['label'])
                elif self.info.get('lastmountpoint') and not self.info.get('label'):
                    self.info['label'] = self.info['lastmountpoint']
                elif not self.info.get('lastmountpoint') and self.info.get('label') and \
                        self.info['label'].startswith("/"):  # e.g. /boot1
                    if self.info['label'].endswith("1"):
                        self.info['lastmountpoint'] = self.info['label'][:-1]
                    else:
                        self.info['lastmountpoint'] = self.info['label']

            except Exception:  # ignore any exceptions here.
                logger.exception("Error while obtaining stats.")

        stats_thread.process = None

        thread = threading.Thread(target=stats_thread)
        thread.start()
        thread.join(timeout)
        if thread.is_alive():
            # noinspection PyBroadException
            try:
                stats_thread.process.terminate()
            except Exception:
                pass
            thread.join()
            logger.debug("Killed fsstat after {0}s".format(timeout))
1206541
def ping():
    '''
    

    '''
    r = __salt__['dracr.system_info'](host=DETAILS['host'],
                                      admin_username=DETAILS['admin_username'],
                                      admin_password=DETAILS['admin_password'])
    if r.get('retcode', 0) == 1:
        return False
    else:
        return True
    try:
        return r['dict'].get('ret', False)
    except Exception:
        return False
579654
def info():
    """"""
    try:
        platform_info = {
            'system': platform.system(),
            'release': platform.release(),
        }
    except IOError:
        platform_info = {
            'system': 'Unknown',
            'release': 'Unknown',
        }

    implementation_info = _implementation()
    urllib3_info = {'version': urllib3.__version__}
    chardet_info = {'version': chardet.__version__}

    pyopenssl_info = {
        'version': None,
        'openssl_version': '',
    }
    if OpenSSL:
        pyopenssl_info = {
            'version': OpenSSL.__version__,
            'openssl_version': '%x' % OpenSSL.SSL.OPENSSL_VERSION_NUMBER,
        }
    cryptography_info = {
        'version': getattr(cryptography, '__version__', ''),
    }
    idna_info = {
        'version': getattr(idna, '__version__', ''),
    }

    system_ssl = ssl.OPENSSL_VERSION_NUMBER
    system_ssl_info = {
        'version': '%x' % system_ssl if system_ssl is not None else ''
    }

    return {
        'platform': platform_info,
        'implementation': implementation_info,
        'system_ssl': system_ssl_info,
        'using_pyopenssl': pyopenssl is not None,
        'pyOpenSSL': pyopenssl_info,
        'urllib3': urllib3_info,
        'chardet': chardet_info,
        'cryptography': cryptography_info,
        'idna': idna_info,
        'requests': {
            'version': requests_version,
        },
    }
1331684
def get_sys():
    '''
    
    '''
    cmd = ''
    if salt.utils.path.which('localectl'):
        cmd = 'localectl | grep Keymap | sed -e"s/: /=/" -e"s/^[ \t]*//"'
    elif 'RedHat' in __grains__['os_family']:
        cmd = 'grep LAYOUT /etc/sysconfig/keyboard | grep -vE "^#"'
    elif 'Debian' in __grains__['os_family']:
        cmd = 'grep XKBLAYOUT /etc/default/keyboard | grep -vE "^#"'
    elif 'Gentoo' in __grains__['os_family']:
        cmd = 'grep "^keymap" /etc/conf.d/keymaps | grep -vE "^#"'
    out = __salt__['cmd.run'](cmd, python_shell=True).split('=')
    ret = out[1].replace('"', '')
    return ret
635812
def facilityMsToNet(SsVersionIndicator_presence=0):
    """"""
    a = TpPd(pd=0x3)
    b = MessageType(mesType=0x3a)  # 00111010
    c = Facility()
    packet = a / b / c
    if SsVersionIndicator_presence is 1:
        d = SsVersionIndicatorHdr(ieiSVI=0x7F, eightBitSVI=0x0)
        packet = packet / d
    return packet
687175
def stc_system_info(stc_addr):
    
    stc = stchttp.StcHttp(stc_addr)
    sessions = stc.sessions()
    if sessions:
        # If a session already exists, use it to get STC information.
        stc.join_session(sessions[0])
        sys_info = stc.system_info()
    else:
        # Create a new session to get STC information.
        stc.new_session('anonymous')
        try:
            sys_info = stc.system_info()
        finally:
            # Make sure the temporary session in terminated.
            stc.end_session()

    return sys_info
583261
def _check_ver(pyver, op, wanted):
    '''
    
    '''
    pyver = distutils.version.LooseVersion(pyver)
    wanted = distutils.version.LooseVersion(wanted)
    return getattr(operator, '__{}__'.format(op))(pyver, wanted)
307167
def netbsd_interfaces():
    '''
    
    '''
    # NetBSD versions prior to 8.0 can still use linux_interfaces()
    if LooseVersion(os.uname()[2]) < LooseVersion('8.0'):
        return linux_interfaces()

    ifconfig_path = salt.utils.path.which('ifconfig')
    cmd = subprocess.Popen(
        '{0} -a'.format(ifconfig_path),
        shell=True,
        stdout=subprocess.PIPE,
        stderr=subprocess.STDOUT).communicate()[0]
    return _netbsd_interfaces_ifconfig(salt.utils.stringutils.to_str(cmd))
1130736
def _get_sysv_services(root, systemd_services=None):
    '''
    
    '''
    initscript_path = _root(INITSCRIPT_PATH, root)
    try:
        sysv_services = os.listdir(initscript_path)
    except OSError as exc:
        if exc.errno == errno.ENOENT:
            pass
        elif exc.errno == errno.EACCES:
            log.error(
                'Unable to check sysvinit scripts, permission denied to %s',
                initscript_path
            )
        else:
            log.error(
                'Error %d encountered trying to check sysvinit scripts: %s',
                exc.errno,
                exc.strerror
            )
        return []

    if systemd_services is None:
        systemd_services = _get_systemd_services(root)

    ret = []
    for sysv_service in sysv_services:
        if os.access(os.path.join(initscript_path, sysv_service), os.X_OK):
            if sysv_service in systemd_services:
                log.debug(
                    'sysvinit script \'%s\' found, but systemd unit '
                    '\'%s.service\' already exists',
                    sysv_service, sysv_service
                )
                continue
            ret.append(sysv_service)
    return ret