Return netstat routing information for NetBSD
544375
def _netstat_route_netbsd():
    '''
    
    '''
    ret = []
    cmd = 'netstat -f inet -rn | tail -n+5'
    out = __salt__['cmd.run'](cmd, python_shell=True)
    for line in out.splitlines():
        comps = line.split()
        ret.append({
            'addr_family': 'inet',
            'destination': comps[0],
            'gateway': comps[1],
            'netmask': '',
            'flags': comps[3],
            'interface': comps[6]})
    cmd = 'netstat -f inet6 -rn | tail -n+5'
    out = __salt__['cmd.run'](cmd, python_shell=True)
    for line in out.splitlines():
        comps = line.split()
        ret.append({
            'addr_family': 'inet6',
            'destination': comps[0],
            'gateway': comps[1],
            'netmask': '',
            'flags': comps[3],
            'interface': comps[6]})
    return ret
1174973
def get_port_stats(port):
    
    cnts = defaultdict(int)
    for c in psutil.net_connections():
        c_port = c.laddr[1]
        if c_port != port:
            continue
        status = c.status.lower()
        cnts[status] += 1
    return cnts
122602
def _netstat_linux():
    '''
    
    '''
    ret = []
    cmd = 'netstat -tulpnea'
    out = __salt__['cmd.run'](cmd)
    for line in out.splitlines():
        comps = line.split()
        if line.startswith('tcp'):
            ret.append({
                'proto': comps[0],
                'recv-q': comps[1],
                'send-q': comps[2],
                'local-address': comps[3],
                'remote-address': comps[4],
                'state': comps[5],
                'user': comps[6],
                'inode': comps[7],
                'program': comps[8]})
        if line.startswith('udp'):
            ret.append({
                'proto': comps[0],
                'recv-q': comps[1],
                'send-q': comps[2],
                'local-address': comps[3],
                'remote-address': comps[4],
                'user': comps[5],
                'inode': comps[6],
                'program': comps[7]})
    return ret
69889
def get_ntp_servers(self):
        """"""
        ntp_table = junos_views.junos_ntp_servers_config_table(self.device)
        ntp_table.get()

        ntp_servers = ntp_table.items()

        if not ntp_servers:
            return {}

        return {napalm_base.helpers.ip(server[0]): {} for server in ntp_servers}
226313
def retrieve_loadbalancer_stats(self, loadbalancer, **_params):
        """"""
        return self.get(self.lbaas_loadbalancer_path_stats % (loadbalancer),
                        params=_params)
539587
def get_data(conn_objs, providers):
    """"""
    cld_svc_map = {"aws": nodes_aws,
                   "azure": nodes_az,
                   "gcp": nodes_gcp,
                   "alicloud": nodes_ali}
    sys.stdout.write("\rCollecting Info:  ")
    sys.stdout.flush()
    busy_obj = busy_disp_on()
    collec_fn = [[cld_svc_map[x.rstrip('1234567890')], conn_objs[x]]
                 for x in providers]
    ngroup = Group()
    node_list = []
    node_list = ngroup.map(get_nodes, collec_fn)
    ngroup.join()
    busy_disp_off(dobj=busy_obj)
    sys.stdout.write("\r                                                 \r")
    sys.stdout.write("\033[?25h")  # cursor back on
    sys.stdout.flush()
    return node_list
39220
def get_sockinfo (host, port=None):
    """"""
    family, socktype = socket.AF_INET, socket.SOCK_STREAM
    return socket.getaddrinfo(host, port, family, socktype)
536262
def get_route_to(self, destination='', protocol=''):
        """"""

        # Note, it should be possible to query the FIB:
        # "<show><routing><fib></fib></routing></show>"
        # To add informations to this getter
        routes = {}

        if destination:
            destination = "<destination>{0}</destination>".format(destination)
        if protocol:
            protocol = "<type>{0}</type>".format(protocol)

        cmd = "<show><routing><route>{0}{1}</route></routing></show>".format(protocol, destination)
        try:
            self.device.op(cmd=cmd)
            routes_table_xml = xmltodict.parse(self.device.xml_root())
            routes_table_json = json.dumps(routes_table_xml['response']['result']['entry'])
            routes_table = json.loads(routes_table_json)
        except (AttributeError, KeyError):
            routes_table = []

        if isinstance(routes_table, dict):
            routes_table = [routes_table]

        for route in routes_table:
            d = {
                'current_active': False,
                'last_active': False,
                'age': -1,
                'next_hop': u'',
                'protocol': u'',
                'outgoing_interface': u'',
                'preference': -1,
                'inactive_reason': u'',
                'routing_table': u'default',
                'selected_next_hop': False,
                'protocol_attributes': {}
            }
            destination = route['destination']
            flags = route['flags']

            if 'A' in flags:
                d['current_active'] = True
            else:
                d['current_active'] = False
            if 'C' in flags:
                d['protocol'] = "connect"
            if 'S' in flags:
                d['protocol'] = "static"
            if 'R' in flags:
                d['protocol'] = "rip"
            if 'R' in flags:
                d['protocol'] = "rip"
            if 'O' in flags:
                d['protocol'] = "ospf"
            if 'B' in flags:
                d['protocol'] = "bgp"
            if 'H' in flags:
                d['protocol'] = "host"
            if route['age'] is not None:
                d['age'] = int(route['age'])
            if route['nexthop'] is not None:
                d['next_hop'] = route['nexthop']
            if route['interface'] is not None:
                d['outgoing_interface'] = route['interface']
            if route['metric'] is not None:
                d['preference'] = int(route['metric'])
            if route['virtual-router'] is not None:
                d['routing_table'] = route['virtual-router']

            if destination not in routes.keys():
                routes[destination] = []
            routes[destination].append(d)

        return routes
595889
def _netstat_route_sunos():
    '''
    
    '''
    ret = []
    cmd = 'netstat -f inet -rn | tail +5'
    out = __salt__['cmd.run'](cmd, python_shell=True)
    for line in out.splitlines():
        comps = line.split()
        ret.append({
            'addr_family': 'inet',
            'destination': comps[0],
            'gateway': comps[1],
            'netmask': '',
            'flags': comps[2],
            'interface': comps[5] if len(comps) >= 6 else ''})
    cmd = 'netstat -f inet6 -rn | tail +5'
    out = __salt__['cmd.run'](cmd, python_shell=True)
    for line in out.splitlines():
        comps = line.split()
        ret.append({
            'addr_family': 'inet6',
            'destination': comps[0],
            'gateway': comps[1],
            'netmask': '',
            'flags': comps[2],
            'interface': comps[5] if len(comps) >= 6 else ''})
    return ret
208470
def _parse_routes():
    '''
    
    '''
    with salt.utils.files.fopen('/proc/net/route', 'r') as fp_:
        out = salt.utils.stringutils.to_unicode(fp_.read())

    ret = {}
    for line in out.splitlines():
        tmp = {}
        if not line.strip():
            continue
        if line.startswith('Iface'):
            continue
        comps = line.split()
        tmp['iface'] = comps[0]
        tmp['destination'] = _hex_to_octets(comps[1])
        tmp['gateway'] = _hex_to_octets(comps[2])
        tmp['flags'] = _route_flags(int(comps[3]))
        tmp['refcnt'] = comps[4]
        tmp['use'] = comps[5]
        tmp['metric'] = comps[6]
        tmp['mask'] = _hex_to_octets(comps[7])
        tmp['mtu'] = comps[8]
        tmp['window'] = comps[9]
        tmp['irtt'] = comps[10]
        if comps[0] not in ret:
            ret[comps[0]] = []
        ret[comps[0]].append(tmp)
    return ret
793417
def collect(self):
        
        performance_indicators = {
            'ns': 'network_send',
            'nr': 'network_receive',
            'dw': 'disk_write',
            'dr': 'disk_read',
            'al': 'activity_log',
            'bm': 'bit_map',
            'lo': 'local_count',
            'pe': 'pending',
            'ua': 'unacknowledged',
            'ap': 'application_pending',
            'ep': 'epochs',
            'wo': 'write_order',
            'oos': 'out_of_sync',
            'cs': 'connection_state',
            'ro': 'roles',
            'ds': 'disk_states'
        }

        results = dict()
        try:
            statusfile = open('/proc/drbd', 'r')
            current_resource = ''
            for line in statusfile:
                if re.search('version', line) is None:
                    if re.search(r' \d: cs', line):
                        matches = re.match(r' (\d): (cs:\w+) (ro:\w+/\w+) '
                                           '(ds:\w+/\w+) (\w{1}) .*', line)
                        current_resource = matches.group(1)
                        results[current_resource] = dict()
                    elif re.search(r'\sns:', line):
                        metrics = line.strip().split(" ")
                        for metric in metrics:
                            item, value = metric.split(":")
                            results[current_resource][
                                performance_indicators[item]] = value

                else:
                    continue
            statusfile.close()
        except IOError as errormsg:
            self.log.error("Can't read DRBD status file: {}".format(errormsg))
            return

        for resource in results.keys():
            for metric_name, metric_value in results[resource].items():
                if metric_value.isdigit():
                    self.publish(resource + "." + metric_name, metric_value)
                else:
                    continue
1067191
def get_snmp_information(self):
        """"""

        # Default values
        snmp_dict = {
            'chassis_id': '',
            'location': '',
            'contact': '',
            'community': {}
        }

        commands = [
            'show snmp chassis',
            'show snmp location',
            'show snmp contact'
        ]
        snmp_config = self.device.run_commands(commands, encoding='json')
        for line in snmp_config:
            for k, v in line.items():
                if k == 'chassisId':
                    snmp_dict['chassis_id'] = v
                else:
                    # Some EOS versions add extra quotes
                    snmp_dict[k] = v.strip('"')

        commands = ['show running-config | section snmp-server community']
        raw_snmp_config = self.device.run_commands(commands, encoding='text')[0].get('output', '')
        for line in raw_snmp_config.splitlines():
            match = self._RE_SNMP_COMM.search(line)
            if match:
                matches = match.groupdict('')
                snmp_dict['community'][match.group('community')] = {
                    'acl': py23_compat.text_type(matches['v4_acl']),
                    'mode': py23_compat.text_type(matches['access'])
                }

        return snmp_dict
1280417
def _netstat_bsd():
    '''
    
    '''
    ret = []
    if __grains__['kernel'] == 'NetBSD':
        for addr_family in ('inet', 'inet6'):
            cmd = 'netstat -f {0} -an | tail -n+3'.format(addr_family)
            out = __salt__['cmd.run'](cmd, python_shell=True)
            for line in out.splitlines():
                comps = line.split()
                entry = {
                    'proto': comps[0],
                    'recv-q': comps[1],
                    'send-q': comps[2],
                    'local-address': comps[3],
                    'remote-address': comps[4]
                }
                if entry['proto'].startswith('tcp'):
                    entry['state'] = comps[5]
                ret.append(entry)
    else:
        # Lookup TCP connections
        cmd = 'netstat -p tcp -an | tail -n+3'
        out = __salt__['cmd.run'](cmd, python_shell=True)
        for line in out.splitlines():
            comps = line.split()
            ret.append({
                'proto': comps[0],
                'recv-q': comps[1],
                'send-q': comps[2],
                'local-address': comps[3],
                'remote-address': comps[4],
                'state': comps[5]})
        # Lookup UDP connections
        cmd = 'netstat -p udp -an | tail -n+3'
        out = __salt__['cmd.run'](cmd, python_shell=True)
        for line in out.splitlines():
            comps = line.split()
            ret.append({
                'proto': comps[0],
                'recv-q': comps[1],
                'send-q': comps[2],
                'local-address': comps[3],
                'remote-address': comps[4]})

    # Add in user and program info
    ppid = _ppid()
    if __grains__['kernel'] == 'OpenBSD':
        netinfo = _netinfo_openbsd()
    elif __grains__['kernel'] in ('FreeBSD', 'NetBSD'):
        netinfo = _netinfo_freebsd_netbsd()
    for idx in range(len(ret)):
        local = ret[idx]['local-address']
        remote = ret[idx]['remote-address']
        proto = ret[idx]['proto']
        try:
            # Make a pointer to the info for this connection for easier
            # reference below
            ptr = netinfo[local][remote][proto]
        except KeyError:
            continue
        # Get the pid-to-ppid mappings for this connection
        conn_ppid = dict((x, y) for x, y in six.iteritems(ppid) if x in ptr)
        try:
            # Master pid for this connection will be the pid whose ppid isn't
            # in the subset dict we created above
            master_pid = next(iter(
                x for x, y in six.iteritems(conn_ppid) if y not in ptr
            ))
        except StopIteration:
            continue
        ret[idx]['user'] = ptr[master_pid]['user']
        ret[idx]['program'] = '/'.join((master_pid, ptr[master_pid]['cmd']))
    return ret
189970
def _netbsd_interfaces_ifconfig(out):
    '''
    
    '''
    ret = dict()

    piface = re.compile(r'^([^\s:]+)')
    pmac = re.compile('.*?address: ([0-9a-f:]+)')

    pip = re.compile(r'.*?inet [^\d]*(.*?)/([\d]*)\s')
    pip6 = re.compile(r'.*?inet6 ([0-9a-f:]+)%([a-zA-Z0-9]*)/([\d]*)\s')

    pupdown = re.compile('UP')
    pbcast = re.compile(r'.*?broadcast ([\d\.]+)')

    groups = re.compile('\r?\n(?=\\S)').split(out)
    for group in groups:
        data = dict()
        iface = ''
        updown = False
        for line in group.splitlines():
            miface = piface.match(line)
            mmac = pmac.match(line)
            mip = pip.match(line)
            mip6 = pip6.match(line)
            mupdown = pupdown.search(line)
            if miface:
                iface = miface.group(1)
            if mmac:
                data['hwaddr'] = mmac.group(1)
            if mip:
                if 'inet' not in data:
                    data['inet'] = list()
                addr_obj = dict()
                addr_obj['address'] = mip.group(1)
                mmask = mip.group(2)
                if mip.group(2):
                    addr_obj['netmask'] = cidr_to_ipv4_netmask(mip.group(2))
                mbcast = pbcast.match(line)
                if mbcast:
                    addr_obj['broadcast'] = mbcast.group(1)
                data['inet'].append(addr_obj)
            if mupdown:
                updown = True
            if mip6:
                if 'inet6' not in data:
                    data['inet6'] = list()
                addr_obj = dict()
                addr_obj['address'] = mip6.group(1)
                mmask6 = mip6.group(3)
                addr_obj['scope'] = mip6.group(2)
                addr_obj['prefixlen'] = mip6.group(3)
                data['inet6'].append(addr_obj)
        data['up'] = updown
        ret[iface] = data
        del data
    return ret
336527
def in6_getifaddr():
    

    # List all network interfaces
    if OPENBSD:
        try:
            f = os.popen("%s" % conf.prog.ifconfig)
        except OSError:
            log_interactive.warning("Failed to execute ifconfig.")
            return []

        # Get the list of network interfaces
        splitted_line = []
        for l in f:
            if "flags" in l:
                iface = l.split()[0].rstrip(':')
                splitted_line.append(iface)

    else:  # FreeBSD, NetBSD or Darwin
        try:
            f = os.popen("%s -l" % conf.prog.ifconfig)
        except OSError:
            log_interactive.warning("Failed to execute ifconfig.")
            return []

        # Get the list of network interfaces
        splitted_line = f.readline().rstrip().split()

    ret = []
    for i in splitted_line:
        ret += _in6_getifaddr(i)
    return ret
216906
def get_bgp_neighbors_detail(self, neighbor_address=''):
        """"""
        def _parse_per_peer_bgp_detail(peer_output):
            """This function parses the raw data per peer and returns a
            json structure per peer.
            """

            int_fields = ['local_as', 'remote_as',
                          'local_port', 'remote_port', 'local_port',
                          'input_messages', 'output_messages', 'input_updates',
                          'output_updates', 'messages_queued_out', 'holdtime',
                          'configured_holdtime', 'keepalive',
                          'configured_keepalive', 'advertised_prefix_count',
                          'received_prefix_count']

            peer_details = []

            # Using preset template to extract peer info
            peer_info = (
                napalm_base.helpers.textfsm_extractor(
                    self, 'bgp_detail', peer_output))

            for item in peer_info:

                # Determining a few other fields in the final peer_info
                item['up'] = (
                    True if item['up'] == "up" else False)
                item['local_address_configured'] = (
                    True if item['local_address'] else False)
                item['multihop'] = (
                    False if item['multihop'] == 0 or
                    item['multihop'] == '' else True)

                # TODO: The below fields need to be retrieved
                # Currently defaulting their values to False or 0
                item['multipath'] = False
                item['remove_private_as'] = False
                item['suppress_4byte_as'] = False
                item['local_as_prepend'] = False
                item['flap_count'] = 0
                item['active_prefix_count'] = 0
                item['suppressed_prefix_count'] = 0

                # Converting certain fields into int
                for key in int_fields:
                    item[key] = napalm_base.helpers.convert(int, item[key], 0)

                # Conforming with the datatypes defined by the base class
                item['export_policy'] = (
                    napalm_base.helpers.convert(
                        py23_compat.text_type, item['export_policy']))
                item['last_event'] = (
                    napalm_base.helpers.convert(
                        py23_compat.text_type, item['last_event']))
                item['remote_address'] = napalm_base.helpers.ip(item['remote_address'])
                item['previous_connection_state'] = (
                    napalm_base.helpers.convert(
                        py23_compat.text_type, item['previous_connection_state']))
                item['import_policy'] = (
                    napalm_base.helpers.convert(
                        py23_compat.text_type, item['import_policy']))
                item['connection_state'] = (
                    napalm_base.helpers.convert(
                        py23_compat.text_type, item['connection_state']))
                item['routing_table'] = (
                    napalm_base.helpers.convert(
                        py23_compat.text_type, item['routing_table']))
                item['router_id'] = napalm_base.helpers.ip(item['router_id'])
                item['local_address'] = napalm_base.helpers.convert(
                    napalm_base.helpers.ip, item['local_address'])

                peer_details.append(item)

            return peer_details

        def _append(bgp_dict, peer_info):

            remote_as = peer_info['remote_as']
            vrf_name = peer_info['routing_table']

            if vrf_name not in bgp_dict.keys():
                bgp_dict[vrf_name] = {}
            if remote_as not in bgp_dict[vrf_name].keys():
                bgp_dict[vrf_name][remote_as] = []

            bgp_dict[vrf_name][remote_as].append(peer_info)

        commands = []
        summary_commands = []
        if not neighbor_address:
            commands.append('show ip bgp neighbors vrf all')
            commands.append('show ipv6 bgp neighbors vrf all')
            summary_commands.append('show ip bgp summary vrf all')
            summary_commands.append('show ipv6 bgp summary vrf all')
        else:
            try:
                peer_ver = IPAddress(neighbor_address).version
            except Exception as e:
                raise e

            if peer_ver == 4:
                commands.append('show ip bgp neighbors %s vrf all' %
                                neighbor_address)
                summary_commands.append('show ip bgp summary vrf all')
            elif peer_ver == 6:
                commands.append('show ipv6 bgp neighbors %s vrf all' %
                                neighbor_address)
                summary_commands.append('show ipv6 bgp summary vrf all')

        raw_output = (
            self.device.run_commands(commands, encoding='text'))
        bgp_summary = (
            self.device.run_commands(summary_commands, encoding='json'))

        bgp_detail_info = {}

        v4_peer_info = []
        v6_peer_info = []

        if neighbor_address:
            peer_info = _parse_per_peer_bgp_detail(raw_output[0]['output'])

            if peer_ver == 4:
                v4_peer_info.append(peer_info[0])
            else:
                v6_peer_info.append(peer_info[0])

        else:
            # Using preset template to extract peer info
            v4_peer_info = _parse_per_peer_bgp_detail(raw_output[0]['output'])
            v6_peer_info = _parse_per_peer_bgp_detail(raw_output[1]['output'])

        for peer_info in v4_peer_info:

            vrf_name = peer_info['routing_table']
            peer_remote_addr = peer_info['remote_address']
            peer_info['accepted_prefix_count'] = (
                bgp_summary[0]['vrfs'][vrf_name]['peers'][peer_remote_addr]['prefixAccepted']
                if peer_remote_addr in bgp_summary[0]['vrfs'][vrf_name]['peers'].keys()
                else 0
            )

            _append(bgp_detail_info, peer_info)

        for peer_info in v6_peer_info:

            vrf_name = peer_info['routing_table']
            peer_remote_addr = peer_info['remote_address']
            peer_info['accepted_prefix_count'] = (
                bgp_summary[1]['vrfs'][vrf_name]['peers'][peer_remote_addr]['prefixAccepted']
                if peer_remote_addr in bgp_summary[1]['vrfs'][vrf_name]['peers'].keys()
                else 0
            )

            _append(bgp_detail_info, peer_info)

        return bgp_detail_info
922004
def retrieveVals(self):
        """"""
        ntpinfo = NTPinfo()
        stats = ntpinfo.getHostOffset(self._remoteHost)
        if stats:
            graph_name = 'ntp_host_stratum_%s' % self._remoteHost
            if self.hasGraph(graph_name):
                self.setGraphVal(graph_name, 'stratum', stats.get('stratum'))
            graph_name = 'ntp_host_stat_%s' % self._remoteHost
            if self.hasGraph(graph_name):
                self.setGraphVal(graph_name, 'offset', stats.get('offset'))
                self.setGraphVal(graph_name, 'delay', stats.get('delay'))