Get process information for network connections using sockstat
187437
def _netinfo_freebsd_netbsd():
    '''
    
    '''
    ret = {}
    # NetBSD requires '-n' to disable port-to-service resolution
    out = __salt__['cmd.run'](
        'sockstat -46 {0} | tail -n+2'.format(
            '-n' if __grains__['kernel'] == 'NetBSD' else ''
        ), python_shell=True
    )
    for line in out.splitlines():
        user, cmd, pid, _, proto, local_addr, remote_addr = line.split()
        local_addr = '.'.join(local_addr.rsplit(':', 1))
        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
1034202
def netstat():
    '''
    
    '''
    ret = []
    cmd = ['netstat', '-nao']
    lines = __salt__['cmd.run'](cmd, python_shell=False).splitlines()
    for line in lines:
        comps = line.split()
        if line.startswith('  TCP'):
            ret.append({
                'local-address': comps[1],
                'proto': comps[0],
                'remote-address': comps[2],
                'state': comps[3],
                'program': comps[4]})
        if line.startswith('  UDP'):
            ret.append({
                'local-address': comps[1],
                'proto': comps[0],
                'remote-address': comps[2],
                'state': None,
                'program': comps[3]})
    return ret
1113558
def _get_static_info(interface):
    '''
    
    '''
    data = {
        'connectionid': interface.name,
        'label': interface.name,
        'hwaddr': interface.hwaddr[:-1],
        'up': False,
        'ipv4': {
            'supportedrequestmodes': ['static', 'dhcp_linklocal', 'disabled'],
            'requestmode': 'static'
        },
        'wireless': False
    }
    hwaddr_section_number = ''.join(data['hwaddr'].split(':'))
    if os.path.exists(INTERFACES_CONFIG):
        information = _load_config(hwaddr_section_number, ['IPv4', 'Nameservers'], filename=INTERFACES_CONFIG)
        if information['IPv4'] != '':
            ipv4_information = information['IPv4'].split('/')
            data['ipv4']['address'] = ipv4_information[0]
            data['ipv4']['dns'] = information['Nameservers'].split(',')
            data['ipv4']['netmask'] = ipv4_information[1]
            data['ipv4']['gateway'] = ipv4_information[2]
    return data
65883
def network_details():
        
        # Get IPv4 details
        ipv4_addresses = [
            info[4][0]
            for info in socket.getaddrinfo(
                socket.gethostname(), None, socket.AF_INET
            )
        ]

        # Add localhost
        ipv4_addresses.extend(
            info[4][0]
            for info in socket.getaddrinfo("localhost", None, socket.AF_INET)
        )

        # Filter addresses
        ipv4_addresses = sorted(set(ipv4_addresses))

        try:
            # Get IPv6 details
            ipv6_addresses = [
                info[4][0]
                for info in socket.getaddrinfo(
                    socket.gethostname(), None, socket.AF_INET6
                )
            ]

            # Add localhost
            ipv6_addresses.extend(
                info[4][0]
                for info in socket.getaddrinfo(
                    "localhost", None, socket.AF_INET6
                )
            )

            # Filter addresses
            ipv6_addresses = sorted(set(ipv6_addresses))
        except (socket.gaierror, AttributeError):
            # AttributeError: AF_INET6 is missing in some versions of Python
            ipv6_addresses = None

        return {
            "IPv4": ipv4_addresses,
            "IPv6": ipv6_addresses,
            "host.name": socket.gethostname(),
            "host.fqdn": socket.getfqdn(),
        }
486879
def idle_connections(self):
        
        return [c for c in self.connections.values()
                if not c.busy and not c.closed]
361002
def getProcessStatus(self):
        
        info_dict = {}
        cur = self._conn.cursor()
        cur.execute("""SHOW FULL PROCESSLIST;""")
        rows = cur.fetchall()
        if rows:
            for row in rows:
                if row[6] == '':
                    state = 'idle'
                elif row[6] is None:
                    state = 'other'
                else:
                    state = str(row[6]).replace(' ', '_').lower()
                info_dict[state] = info_dict.get(state, 0) + 1
        return info_dict
972599
def echo_info(conn):
    """"""
    click.echo("General information:")
    click.echo(" Hostname: {}".format(conn.hostname))
    click.echo(" HW Family: {}".format(conn.family))
    click.echo(" HW Platform: {}".format(conn.platform))
    click.echo(" SW Type: {}".format(conn.os_type))
    click.echo(" SW Version: {}".format(conn.os_version))
    click.echo(" Prompt: {}".format(conn.prompt))
    click.echo(" Console connection: {}".format(conn.is_console))

    click.echo("\nUDI:")
    click.echo(" PID: {}".format(conn.pid))
    click.echo(" Description: {}".format(conn.description))
    click.echo(" Name: {}".format(conn.name))
    click.echo(" SN: {}".format(conn.sn))
    click.echo(" VID: {}".format(conn.vid))
152916
def getconnections(self, vhost = None):
        ""
        if vhost is None:
            return list(self.managed_connections)
        else:
            return [c for c in self.managed_connections if c.protocol.vhost == vhost]
1062846
def getProcessStats(self):
        
        info_dict = {}
        try:
            fp = open(cpustatFile, 'r')
            data = fp.read()
            fp.close()
        except:
            raise IOError('Failed reading stats from file: %s' % cpustatFile)
        for line in data.splitlines():
            arr = line.split()
            if len(arr) > 1 and arr[0] in ('ctxt', 'intr', 'softirq',
                                           'processes', 'procs_running', 
                                           'procs_blocked'):
                info_dict[arr[0]] = arr[1]
        return info_dict
111963
def dump_stats(myStats):
    
    print("\n----%s PYTHON PING Statistics----" % (myStats.thisIP))

    if myStats.pktsSent > 0:
        myStats.fracLoss = (myStats.pktsSent - myStats.pktsRcvd) \
                / myStats.pktsSent

    print(("%d packets transmitted, %d packets received, "
           "%0.1f%% packet loss") % (
        myStats.pktsSent,
        myStats.pktsRcvd,
        100.0 * myStats.fracLoss
    ))

    if myStats.pktsRcvd > 0:
        print("round-trip (ms)  min/avg/max = %d/%0.1f/%d" % (
            myStats.minTime,
            myStats.totTime / myStats.pktsRcvd,
            myStats.maxTime
        ))

    print("")
    return
148228
def get_file_network_traffic(self, resources):
        
        api_name = 'virustotal-file-network-traffic'
        api_endpoint = 'file/network-traffic'
        return self._extract_all_responses(resources, api_endpoint, api_name)
1226199
def connection_made(self, transport):
        ''''''
        self.transport = transport
        # If the Socks proxy was used then _proxy and _remote_address are already set
        if self._proxy is None:
            # This would throw if called on a closed SSL transport.  Fixed in asyncio in
            # Python 3.6.1 and 3.5.4
            peername = transport.get_extra_info('peername')
            self._remote_address = NetAddress(peername[0], peername[1])
        self._task = spawn_sync(self._process_messages(), loop=self.loop)
640337
def get_agent_sock_path(env=None, sp=subprocess):
    """"""
    args = [util.which('gpgconf'), '--list-dirs']
    output = check_output(args=args, env=env, sp=sp)
    lines = output.strip().split(b'\n')
    dirs = dict(line.split(b':', 1) for line in lines)
    log.debug('%s: %s', args, dirs)
    return dirs[b'agent-socket']
577718
def node_info():
    '''
    
    '''
    with _get_xapi_session() as xapi:
        # get node uuid
        host_rec = _get_record(xapi, 'host', _get_all(xapi, 'host')[0])
        # get first CPU (likely to be a core) uuid
        host_cpu_rec = _get_record(xapi, 'host_cpu', host_rec['host_CPUs'][0])
        # get related metrics
        host_metrics_rec = _get_metrics_record(xapi, 'host', host_rec)

        # adapted / cleaned up from Xen's xm
        def getCpuMhz():
            cpu_speeds = [int(host_cpu_rec["speed"])
                          for host_cpu_it in host_cpu_rec
                          if "speed" in host_cpu_it]
            if cpu_speeds:
                return sum(cpu_speeds) / len(cpu_speeds)
            else:
                return 0

        def getCpuFeatures():
            if host_cpu_rec:
                return host_cpu_rec['features']

        def getFreeCpuCount():
            cnt = 0
            for host_cpu_it in host_cpu_rec:
                if not host_cpu_rec['cpu_pool']:
                    cnt += 1
            return cnt

        info = {
                'cpucores': _get_val(host_rec,
                                    ["cpu_configuration", "nr_cpus"]),
                'cpufeatures': getCpuFeatures(),
                'cpumhz': getCpuMhz(),
                'cpuarch': _get_val(host_rec,
                                    ["software_version", "machine"]),
                'cputhreads': _get_val(host_rec,
                                    ["cpu_configuration", "threads_per_core"]),
                'phymemory': int(host_metrics_rec["memory_total"]) / 1024 / 1024,
                'cores_per_sockets': _get_val(host_rec,
                                    ["cpu_configuration", "cores_per_socket"]),
                'free_cpus': getFreeCpuCount(),
                'free_memory': int(host_metrics_rec["memory_free"]) / 1024 / 1024,
                'xen_major': _get_val(host_rec,
                                    ["software_version", "xen_major"]),
                'xen_minor': _get_val(host_rec,
                                    ["software_version", "xen_minor"]),
                'xen_extra': _get_val(host_rec,
                                    ["software_version", "xen_extra"]),
                'xen_caps': " ".join(_get_val(host_rec, ["capabilities"])),
                'xen_scheduler': _get_val(host_rec,
                                    ["sched_policy"]),
                'xen_pagesize': _get_val(host_rec,
                                    ["other_config", "xen_pagesize"]),
                'platform_params': _get_val(host_rec,
                                    ["other_config", "platform_params"]),
                'xen_commandline': _get_val(host_rec,
                                    ["other_config", "xen_commandline"]),
                'xen_changeset': _get_val(host_rec,
                                    ["software_version", "xen_changeset"]),
                'cc_compiler': _get_val(host_rec,
                                    ["software_version", "cc_compiler"]),
                'cc_compile_by': _get_val(host_rec,
                                    ["software_version", "cc_compile_by"]),
                'cc_compile_domain': _get_val(host_rec,
                                    ["software_version", "cc_compile_domain"]),
                'cc_compile_date': _get_val(host_rec,
                                    ["software_version", "cc_compile_date"]),
                'xend_config_format': _get_val(host_rec,
                                    ["software_version", "xend_config_format"])
                }

        return info
1046356
def network_io_counters(interface=None):
    '''
    
    '''
    if not interface:
        return dict(psutil.net_io_counters()._asdict())
    else:
        stats = psutil.net_io_counters(pernic=True)
        if interface in stats:
            return dict(stats[interface]._asdict())
        else:
            return False
1021868
def _netstat_sunos():
    '''
    
    '''
    log.warning('User and program not (yet) supported on SunOS')

    ret = []
    for addr_family in ('inet', 'inet6'):
        # Lookup TCP connections
        cmd = 'netstat -f {0} -P tcp -an | tail +5'.format(addr_family)
        out = __salt__['cmd.run'](cmd, python_shell=True)
        for line in out.splitlines():
            comps = line.split()
            ret.append({
                'proto': 'tcp6' if addr_family == 'inet6' else 'tcp',
                'recv-q': comps[5],
                'send-q': comps[4],
                'local-address': comps[0],
                'remote-address': comps[1],
                'state': comps[6]})
        # Lookup UDP connections
        cmd = 'netstat -f {0} -P udp -an | tail +5'.format(addr_family)
        out = __salt__['cmd.run'](cmd, python_shell=True)
        for line in out.splitlines():
            comps = line.split()
            ret.append({
                'proto': 'udp6' if addr_family == 'inet6' else 'udp',
                'local-address': comps[0],
                'remote-address': comps[1] if len(comps) > 2 else ''})

    return ret
190966
def get_facts(self):
        """"""
        # default values.
        vendor = "Cisco"
        uptime = -1
        serial_number, fqdn, os_version, hostname, domain_name, model = ("",) * 6

        # obtain output from device
        show_ver = self._send_command("show version")
        show_hosts = self._send_command("show hosts")
        show_int_status = self._send_command("show interface status")
        show_hostname = self._send_command("show hostname")

        # uptime/serial_number/IOS version
        for line in show_ver.splitlines():
            if " uptime is " in line:
                _, uptime_str = line.split(" uptime is ")
                uptime = self.parse_uptime(uptime_str)

            if "Processor Board ID" in line:
                _, serial_number = line.split("Processor Board ID ")
                serial_number = serial_number.strip()

            if "system: " in line or "NXOS: " in line:
                line = line.strip()
                os_version = line.split()[2]
                os_version = os_version.strip()

            if "cisco" in line and "hassis" in line:
                match = re.search(r".cisco (.*) \(", line)
                if match:
                    model = match.group(1).strip()
                match = re.search(r".cisco (.* [cC]hassis)", line)
                if match:
                    model = match.group(1).strip()

        hostname = show_hostname.strip()

        # Determine domain_name and fqdn
        for line in show_hosts.splitlines():
            if "Default domain" in line:
                _, domain_name = re.split(r".*Default domain.*is ", line)
                domain_name = domain_name.strip()
                break
        if hostname.count(".") >= 2:
            fqdn = hostname
            # Remove domain name from hostname
            if domain_name:
                hostname = re.sub(re.escape(domain_name) + "$", "", hostname)
                hostname = hostname.strip(".")
        elif domain_name:
            fqdn = "{}.{}".format(hostname, domain_name)

        # interface_list filter
        interface_list = []
        show_int_status = show_int_status.strip()
        # Remove the header information
        show_int_status = re.sub(
            r"(?:^---------+$|^Port .*$|^ .*$)", "", show_int_status, flags=re.M
        )
        for line in show_int_status.splitlines():
            if not line:
                continue
            interface = line.split()[0]
            # Return canonical interface name
            interface_list.append(helpers.canonical_interface_name(interface))

        return {
            "uptime": int(uptime),
            "vendor": vendor,
            "os_version": py23_compat.text_type(os_version),
            "serial_number": py23_compat.text_type(serial_number),
            "model": py23_compat.text_type(model),
            "hostname": py23_compat.text_type(hostname),
            "fqdn": fqdn,
            "interface_list": interface_list,
        }