Returns neighbor configuration for given neighbor ip address.

    Raises exception if no neighbor with `neigh_ip_address` exists.
480153
def _get_neighbor_conf(neigh_ip_address):
    
    neigh_conf = \
        CORE_MANAGER.neighbors_conf.get_neighbor_conf(neigh_ip_address)
    if not neigh_conf:
        raise RuntimeConfigError(desc='No Neighbor configuration with IP'
                                 ' address %s' % neigh_ip_address)
    assert isinstance(neigh_conf, NeighborConf)
    return neigh_conf
261793
def maybe_ip_addr(addr):
    

    if six.PY2 and isinstance(addr, str):
        addr = unicode(addr)  # noqa
    try:
        return ipaddress.ip_address(addr)
    except ValueError:
        pass
    return str(addr)
1277568
def get_out_ip_addr(cls, tenant_id):
        
        if tenant_id not in cls.serv_obj_dict:
            LOG.error("Fabric not prepared for tenant %s", tenant_id)
            return
        tenant_obj = cls.serv_obj_dict.get(tenant_id)
        return tenant_obj.get_out_ip_addr()
237736
def ip4_address(self):
        
        if self._ip4_address is None and self.network is not None:
            self._ip4_address = self._get_ip_address(
                libvirt.VIR_IP_ADDR_TYPE_IPV4)

        return self._ip4_address
161154
def get_by_ip(cls, ip):
        ''
        ret = cls.hosts_by_ip.get(ip)
        if ret is None:
            ret = cls.hosts_by_ip[ip] = [Host(ip)]
        return ret
1222195
def p2th_address(self) -> Optional[str]:
        ''''''

        if self.id:
            return Kutil(network=self.network,
                         privkey=bytearray.fromhex(self.id)).address
        else:
            return None
365262
def out_filter_get(self, address):
        

        func_name = 'neighbor.out_filter.get'
        param = {
            neighbors.IP_ADDRESS: address,
        }

        return call(func_name, **param)
606340
def get_ip_on_same_subnet(self, other_compute):
        
        if other_compute == self:
            return (self.host_ip, self.host_ip)

        # Perhaps the user has correct network gateway, we trust him
        if (self.host_ip not in ('0.0.0.0', '127.0.0.1') and other_compute.host_ip not in ('0.0.0.0', '127.0.0.1')):
            return (self.host_ip, other_compute.host_ip)

        this_compute_interfaces = yield from self.interfaces()
        other_compute_interfaces = yield from other_compute.interfaces()

        # Sort interface to put the compute host in first position
        # we guess that if user specified this host it could have a reason (VMware Nat / Host only interface)
        this_compute_interfaces = sorted(this_compute_interfaces, key=lambda i: i["ip_address"] != self.host_ip)
        other_compute_interfaces = sorted(other_compute_interfaces, key=lambda i: i["ip_address"] != other_compute.host_ip)

        for this_interface in this_compute_interfaces:
            # Skip if no ip or no netmask (vbox when stopped set a null netmask)
            if len(this_interface["ip_address"]) == 0 or this_interface["netmask"] is None:
                continue
            # Ignore 169.254 network because it's for Windows special purpose
            if this_interface["ip_address"].startswith("169.254."):
                continue

            this_network = ipaddress.ip_network("{}/{}".format(this_interface["ip_address"], this_interface["netmask"]), strict=False)

            for other_interface in other_compute_interfaces:
                if len(other_interface["ip_address"]) == 0 or other_interface["netmask"] is None:
                    continue

                # Avoid stuff like 127.0.0.1
                if other_interface["ip_address"] == this_interface["ip_address"]:
                    continue

                other_network = ipaddress.ip_network("{}/{}".format(other_interface["ip_address"], other_interface["netmask"]), strict=False)
                if this_network.overlaps(other_network):
                    return (this_interface["ip_address"], other_interface["ip_address"])

        raise ValueError("No common subnet for compute {} and {}".format(self.name, other_compute.name))
699855
def _allocate_address(self, instance):
        
        connection = self._connect()
        free_addresses = [ ip for ip in connection.get_all_addresses() if not ip.instance_id]
        if not free_addresses:
            try:
                address = connection.allocate_address()
            except Exception as ex:
                log.error("Unable to allocate a public IP address to instance `%s`",
                          instance.id)
                return None

        try:
            address = free_addresses.pop()
            instance.use_ip(address)
            return address.public_ip
        except Exception as ex:
            log.error("Unable to associate IP address %s to instance `%s`",
                      address, instance.id)
            return None
643542
public IPRangeNode findAddr(InetAddress addr) {

	for (IPRangeNode c: this.list) {

	    IPRangeNode result = c.findAddr(addr);

	    if (result != null) return result;
	}

	return null;
    }
541748
def get_bgp_neighbors(self):
        
        supported_afi = ["ipv4", "ipv6"]

        bgp_neighbor_data = dict()
        bgp_neighbor_data["global"] = {}

        # get summary output from device
        cmd_bgp_all_sum = "show bgp all summary"
        summary_output = self._send_command(cmd_bgp_all_sum).strip()

        if "Invalid input detected" in summary_output:
            raise CommandErrorException("BGP is not running on this device")

        # get neighbor output from device
        neighbor_output = ""
        for afi in supported_afi:
            cmd_bgp_neighbor = "show bgp %s unicast neighbors" % afi
            neighbor_output += self._send_command(cmd_bgp_neighbor).strip()
            # trailing newline required for parsing
            neighbor_output += "\n"

        # Regular expressions used for parsing BGP summary
        parse_summary = {
            "patterns": [
                # For address family: IPv4 Unicast
                {
                    "regexp": re.compile(r"^For address family: (?P<afi>\S+) "),
                    "record": False,
                },
                # Capture router_id and local_as values, e.g.:
                # BGP router identifier 10.0.1.1, local AS number 65000
                {
                    "regexp": re.compile(
                        r"^.* router identifier (?P<router_id>{}), "
                        r"local AS number (?P<local_as>{})".format(
                            IPV4_ADDR_REGEX, ASN_REGEX
                        )
                    ),
                    "record": False,
                },
                # Match neighbor summary row, capturing useful details and
                # discarding the 5 columns that we don't care about, e.g.:
                # Neighbor   V          AS MsgRcvd MsgSent   TblVer  InQ OutQ Up/Down  State/PfxRcd
                # 10.0.0.2   4       65000 1336020 64337701 1011343614    0    0 8w0d         3143
                {
                    "regexp": re.compile(
                        r"^\*?(?P<remote_addr>({})|({}))"
                        r"\s+\d+\s+(?P<remote_as>{})(\s+\S+){{5}}\s+"
                        r"(?P<uptime>(never)|\d+\S+)"
                        r"\s+(?P<accepted_prefixes>\d+)".format(
                            IPV4_ADDR_REGEX, IPV6_ADDR_REGEX, ASN_REGEX
                        )
                    ),
                    "record": True,
                },
                # Same as above, but for peer that are not Established, e.g.:
                # Neighbor      V       AS MsgRcvd MsgSent   TblVer  InQ OutQ Up/Down  State/PfxRcd
                # 192.168.0.2   4    65002       0       0        1    0    0 never    Active
                {
                    "regexp": re.compile(
                        r"^\*?(?P<remote_addr>({})|({}))"
                        r"\s+\d+\s+(?P<remote_as>{})(\s+\S+){{5}}\s+"
                        r"(?P<uptime>(never)|\d+\S+)\s+(?P<state>\D.*)".format(
                            IPV4_ADDR_REGEX, IPV6_ADDR_REGEX, ASN_REGEX
                        )
                    ),
                    "record": True,
                },
                # ipv6 peers often break accross rows because of the longer peer address,
                # match as above, but in separate expressions, e.g.:
                # Neighbor      V       AS MsgRcvd MsgSent   TblVer  InQ OutQ Up/Down  State/PfxRcd
                # 2001:DB8::4
                #               4    65004 9900690  612449 155362939    0    0 26w6d       36391
                {
                    "regexp": re.compile(
                        r"^\*?(?P<remote_addr>({})|({}))".format(
                            IPV4_ADDR_REGEX, IPV6_ADDR_REGEX
                        )
                    ),
                    "record": False,
                },
                {
                    "regexp": re.compile(
                        r"^\s+\d+\s+(?P<remote_as>{})(\s+\S+){{5}}\s+"
                        r"(?P<uptime>(never)|\d+\S+)"
                        r"\s+(?P<accepted_prefixes>\d+)".format(ASN_REGEX)
                    ),
                    "record": True,
                },
                # Same as above, but for peers that are not Established, e.g.:
                # Neighbor      V       AS MsgRcvd MsgSent   TblVer  InQ OutQ Up/Down  State/PfxRcd
                # 2001:DB8::3
                #               4    65003       0       0        1    0    0 never    Idle (Admin)
                {
                    "regexp": re.compile(
                        r"^\s+\d+\s+(?P<remote_as>{})(\s+\S+){{5}}\s+"
                        r"(?P<uptime>(never)|\d+\S+)\s+(?P<state>\D.*)".format(
                            ASN_REGEX
                        )
                    ),
                    "record": True,
                },
            ],
            "no_fill_fields": [
                "accepted_prefixes",
                "state",
                "uptime",
                "remote_as",
                "remote_addr",
            ],
        }

        parse_neighbors = {
            "patterns": [
                # Capture BGP neighbor is 10.0.0.2,  remote AS 65000, internal link
                {
                    "regexp": re.compile(
                        r"^BGP neighbor is (?P<remote_addr>({})|({})),"
                        r"\s+remote AS (?P<remote_as>{}).*".format(
                            IPV4_ADDR_REGEX, IPV6_ADDR_REGEX, ASN_REGEX
                        )
                    ),
                    "record": False,
                },
                # Capture description
                {
                    "regexp": re.compile(r"^\s+Description: (?P<description>.+)"),
                    "record": False,
                },
                # Capture remote_id, e.g.:
                # BGP version 4, remote router ID 10.0.1.2
                {
                    "regexp": re.compile(
                        r"^\s+BGP version \d+, remote router ID "
                        r"(?P<remote_id>{})".format(IPV4_ADDR_REGEX)
                    ),
                    "record": False,
                },
                # Capture state
                {
                    "regexp": re.compile(r"^\s+BGP state = (?P<state>\w+)"),
                    "record": False,
                },
                # Capture AFI and SAFI names, e.g.:
                # For address family: IPv4 Unicast
                {
                    "regexp": re.compile(r"^\s+For address family: (?P<afi>\S+) "),
                    "record": False,
                },
                # Capture current sent and accepted prefixes, e.g.:
                #     Prefixes Current:          637213       3142 (Consumes 377040 bytes)
                {
                    "regexp": re.compile(
                        r"^\s+Prefixes Current:\s+(?P<sent_prefixes>\d+)\s+"
                        r"(?P<accepted_prefixes>\d+).*"
                    ),
                    "record": False,
                },
                # Capture received_prefixes if soft-reconfig is enabled for the peer
                {
                    "regexp": re.compile(
                        r"^\s+Saved (soft-reconfig):.+(?P<received_prefixes>\d+).*"
                    ),
                    "record": True,
                },
                # Otherwise, use the following as an end of row marker
                {
                    "regexp": re.compile(r"^\s+Local Policy Denied Prefixes:.+"),
                    "record": True,
                },
            ],
            # fields that should not be "filled down" across table rows
            "no_fill_fields": [
                "received_prefixes",
                "accepted_prefixes",
                "sent_prefixes",
            ],
        }

        # Parse outputs into a list of dicts
        summary_data = []
        summary_data_entry = {}

        for line in summary_output.splitlines():
            # check for matches against each pattern
            for item in parse_summary["patterns"]:
                match = item["regexp"].match(line)
                if match:
                    # a match was found, so update the temp entry with the match's groupdict
                    summary_data_entry.update(match.groupdict())
                    if item["record"]:
                        # Record indicates the last piece of data has been obtained; move
                        # on to next entry
                        summary_data.append(copy.deepcopy(summary_data_entry))
                        # remove keys that are listed in no_fill_fields before the next pass
                        for field in parse_summary["no_fill_fields"]:
                            try:
                                del summary_data_entry[field]
                            except KeyError:
                                pass
                    break

        neighbor_data = []
        neighbor_data_entry = {}
        for line in neighbor_output.splitlines():
            # check for matches against each pattern
            for item in parse_neighbors["patterns"]:
                match = item["regexp"].match(line)
                if match:
                    # a match was found, so update the temp entry with the match's groupdict
                    neighbor_data_entry.update(match.groupdict())
                    if item["record"]:
                        # Record indicates the last piece of data has been obtained; move
                        # on to next entry
                        neighbor_data.append(copy.deepcopy(neighbor_data_entry))
                        # remove keys that are listed in no_fill_fields before the next pass
                        for field in parse_neighbors["no_fill_fields"]:
                            try:
                                del neighbor_data_entry[field]
                            except KeyError:
                                pass
                    break

        router_id = None

        for entry in summary_data:
            if not router_id:
                router_id = entry["router_id"]
            elif entry["router_id"] != router_id:
                raise ValueError

        # check the router_id looks like an ipv4 address
        router_id = napalm.base.helpers.ip(router_id, version=4)

        # add parsed data to output dict
        bgp_neighbor_data["global"]["router_id"] = router_id
        bgp_neighbor_data["global"]["peers"] = {}
        for entry in summary_data:
            remote_addr = napalm.base.helpers.ip(entry["remote_addr"])
            afi = entry["afi"].lower()
            # check that we're looking at a supported afi
            if afi not in supported_afi:
                continue
            # get neighbor_entry out of neighbor data
            neighbor_entry = None
            for neighbor in neighbor_data:
                if (
                    neighbor["afi"].lower() == afi
                    and napalm.base.helpers.ip(neighbor["remote_addr"]) == remote_addr
                ):
                    neighbor_entry = neighbor
                    break
            # check for proper session data for the afi
            if neighbor_entry is None:
                continue
            elif not isinstance(neighbor_entry, dict):
                raise ValueError(
                    msg="Couldn't find neighbor data for %s in afi %s"
                    % (remote_addr, afi)
                )

            # check for admin down state
            try:
                if "(Admin)" in entry["state"]:
                    is_enabled = False
                else:
                    is_enabled = True
            except KeyError:
                is_enabled = True

            # parse uptime value
            uptime = self.bgp_time_conversion(entry["uptime"])

            # BGP is up if state is Established
            is_up = "Established" in neighbor_entry["state"]

            # check whether session is up for address family and get prefix count
            try:
                accepted_prefixes = int(entry["accepted_prefixes"])
            except (ValueError, KeyError):
                accepted_prefixes = -1

            # Only parse neighbor detailed data if BGP session is-up
            if is_up:
                try:
                    # overide accepted_prefixes with neighbor data if possible (since that's newer)
                    accepted_prefixes = int(neighbor_entry["accepted_prefixes"])
                except (ValueError, KeyError):
                    pass

                # try to get received prefix count, otherwise set to accepted_prefixes
                received_prefixes = neighbor_entry.get(
                    "received_prefixes", accepted_prefixes
                )

                # try to get sent prefix count and convert to int, otherwise set to -1
                sent_prefixes = int(neighbor_entry.get("sent_prefixes", -1))
            else:
                received_prefixes = -1
                sent_prefixes = -1
                uptime = -1

            # get description
            try:
                description = py23_compat.text_type(neighbor_entry["description"])
            except KeyError:
                description = ""

            # check the remote router_id looks like an ipv4 address
            remote_id = napalm.base.helpers.ip(neighbor_entry["remote_id"], version=4)

            if remote_addr not in bgp_neighbor_data["global"]["peers"]:
                bgp_neighbor_data["global"]["peers"][remote_addr] = {
                    "local_as": napalm.base.helpers.as_number(entry["local_as"]),
                    "remote_as": napalm.base.helpers.as_number(entry["remote_as"]),
                    "remote_id": remote_id,
                    "is_up": is_up,
                    "is_enabled": is_enabled,
                    "description": description,
                    "uptime": uptime,
                    "address_family": {
                        afi: {
                            "received_prefixes": received_prefixes,
                            "accepted_prefixes": accepted_prefixes,
                            "sent_prefixes": sent_prefixes,
                        }
                    },
                }
            else:
                # found previous data for matching remote_addr, but for different afi
                existing = bgp_neighbor_data["global"]["peers"][remote_addr]
                assert afi not in existing["address_family"]
                # compare with existing values and croak if they don't match
                assert existing["local_as"] == napalm.base.helpers.as_number(
                    entry["local_as"]
                )
                assert existing["remote_as"] == napalm.base.helpers.as_number(
                    entry["remote_as"]
                )
                assert existing["remote_id"] == remote_id
                assert existing["is_enabled"] == is_enabled
                assert existing["description"] == description
                # merge other values in a sane manner
                existing["is_up"] = existing["is_up"] or is_up
                existing["uptime"] = max(existing["uptime"], uptime)
                existing["address_family"][afi] = {
                    "received_prefixes": received_prefixes,
                    "accepted_prefixes": accepted_prefixes,
                    "sent_prefixes": sent_prefixes,
                }
        return bgp_neighbor_data
525316
public static AddressMatcher getAddressMatcher(String address) {
        final AddressMatcher matcher;
        final int indexColon = address.indexOf(':');
        final int lastIndexColon = address.lastIndexOf(':');
        final int indexDot = address.indexOf('.');
        final int lastIndexDot = address.lastIndexOf('.');

        if (indexColon > -1 && lastIndexColon > indexColon) {
            if (indexDot == -1) {
                matcher = new Ip6AddressMatcher();
                parseIpv6(matcher, address);
            } else {
                // IPv4 mapped IPv6
                if (indexDot >= lastIndexDot) {
                    throw new InvalidAddressException(address);
                }
                final int lastIndexColon2 = address.lastIndexOf(':');
                final String host2 = address.substring(lastIndexColon2 + 1);
                matcher = new Ip4AddressMatcher();
                parseIpv4(matcher, host2);
            }
        } else if (indexDot > -1 && lastIndexDot > indexDot && indexColon == -1) {
            // IPv4
            matcher = new Ip4AddressMatcher();
            parseIpv4(matcher, address);
        } else {
            throw new InvalidAddressException(address);
        }
        return matcher;
    }
1297544
public final Neighbour getNeighbour(SIBUuid8 neighbourUUID, boolean includeRecovered)
  {
    if (TraceComponent.isAnyTracingEnabled() && tc.isEntryEnabled())
      SibTr.entry(tc, "getNeighbour", new Object[] { neighbourUUID, Boolean.valueOf(includeRecovered)});
    
    Neighbour neighbour = _neighbours.getNeighbour(neighbourUUID); 
    
    if((neighbour == null) && includeRecovered)
      neighbour = _neighbours.getRecoveredNeighbour(neighbourUUID);
    
    if (TraceComponent.isAnyTracingEnabled() && tc.isEntryEnabled())
      SibTr.exit(tc, "getNeighbour", neighbour);
    
    return neighbour;
  }
379209
def get_ip_addresses():
    
    log = logging.getLogger(mod_logger + '.get_ip_addresses')

    command = ['/sbin/ifconfig']
    try:
        result = run_command(command)
    except CommandError:
        raise
    ifconfig = result['output'].strip()

    # Scan the ifconfig output for IPv4 addresses
    devices = {}
    parts = ifconfig.split()
    device = None
    for part in parts:

        if device is None:
            if 'eth' in part or 'eno' in part:
                device = part
        else:
            test = part.split(':', 1)
            if len(test) == 2:
                if test[0] == 'addr':
                    ip_address = test[1]
                    log.info('Found IP address %s on device %s', ip_address,
                             device)
                    devices[device] = ip_address
                    device = None
    return devices
537191
public static InetAddress getByAddress(String host, byte[] addr, int scopeId)
        throws UnknownHostException {
        if (host != null && host.length() > 0 && host.charAt(0) == '[') {
            if (host.charAt(host.length()-1) == ']') {
                host = host.substring(1, host.length() -1);
            }
        }
        if (addr != null) {
            if (addr.length == Inet4Address.INADDRSZ) {
                return new Inet4Address(host, addr);
            } else if (addr.length == Inet6Address.INADDRSZ) {
                byte[] newAddr
                    = IPAddressUtil.convertFromIPv4MappedAddress(addr);
                if (newAddr != null) {
                    return new Inet4Address(host, newAddr);
                } else {
                    return new Inet6Address(host, addr, scopeId);
                }
            }
        }
        throw new UnknownHostException("addr is of illegal length");
    }
175908
def _add_neighbors(self, settings):
        
        for neighbor_settings in settings:
            LOG.debug('Adding neighbor settings: %s', neighbor_settings)
            try:
                self.speaker.neighbor_add(**neighbor_settings)
            except RuntimeConfigError as e:
                LOG.exception(e)
1065273
def get_bgp_config(self, group="", neighbor=""):
        """"""
        _GROUP_FIELD_MAP_ = {
            "type": "type",
            "multipath": "multipath",
            "apply-groups": "apply_groups",
            "remove-private-as": "remove_private_as",
            "ebgp-multihop": "multihop_ttl",
            "remote-as": "remote_as",
            "local-v4-addr": "local_address",
            "local-v6-addr": "local_address",
            "local-as": "local_as",
            "description": "description",
            "import-policy": "import_policy",
            "export-policy": "export_policy",
        }

        _PEER_FIELD_MAP_ = {
            "description": "description",
            "remote-as": "remote_as",
            "local-v4-addr": "local_address",
            "local-v6-addr": "local_address",
            "local-as": "local_as",
            "next-hop-self": "nhs",
            "route-reflector-client": "route_reflector_client",
            "import-policy": "import_policy",
            "export-policy": "export_policy",
            "passwd": "authentication_key",
        }

        _PROPERTY_FIELD_MAP_ = _GROUP_FIELD_MAP_.copy()
        _PROPERTY_FIELD_MAP_.update(_PEER_FIELD_MAP_)

        _PROPERTY_TYPE_MAP_ = {
            # used to determine the default value
            # and cast the values
            "remote-as": int,
            "ebgp-multihop": int,
            "local-v4-addr": py23_compat.text_type,
            "local-v6-addr": py23_compat.text_type,
            "local-as": int,
            "remove-private-as": bool,
            "next-hop-self": bool,
            "description": py23_compat.text_type,
            "route-reflector-client": bool,
            "password": py23_compat.text_type,
            "route-map": py23_compat.text_type,
            "apply-groups": list,
            "type": py23_compat.text_type,
            "import-policy": py23_compat.text_type,
            "export-policy": py23_compat.text_type,
            "multipath": bool,
        }

        _DATATYPE_DEFAULT_ = {py23_compat.text_type: "", int: 0, bool: False, list: []}

        def default_group_dict(local_as):
            group_dict = {}
            group_dict.update(
                {
                    key: _DATATYPE_DEFAULT_.get(_PROPERTY_TYPE_MAP_.get(prop))
                    for prop, key in _GROUP_FIELD_MAP_.items()
                }
            )
            group_dict.update(
                {"prefix_limit": {}, "neighbors": {}, "local_as": local_as}
            )  # few more default values
            return group_dict

        def default_neighbor_dict(local_as):
            neighbor_dict = {}
            neighbor_dict.update(
                {
                    key: _DATATYPE_DEFAULT_.get(_PROPERTY_TYPE_MAP_.get(prop))
                    for prop, key in _PEER_FIELD_MAP_.items()
                }
            )  # populating with default values
            neighbor_dict.update(
                {"prefix_limit": {}, "local_as": local_as, "authentication_key": ""}
            )  # few more default values
            return neighbor_dict

        def parse_options(options, default_value=False):

            if not options:
                return {}

            config_property = options[0]
            field_name = _PROPERTY_FIELD_MAP_.get(config_property)
            field_type = _PROPERTY_TYPE_MAP_.get(config_property)
            field_value = _DATATYPE_DEFAULT_.get(field_type)  # to get the default value

            if not field_type:
                # no type specified at all => return empty dictionary
                return {}

            if not default_value:
                if len(options) > 1:
                    field_value = napalm.base.helpers.convert(
                        field_type, options[1], _DATATYPE_DEFAULT_.get(field_type)
                    )
                else:
                    if field_type is bool:
                        field_value = True
            if field_name is not None:
                return {field_name: field_value}
            elif config_property in ["route-map", "password"]:
                # do not respect the pattern neighbor [IP_ADDRESS] [PROPERTY] [VALUE]
                # or need special output (e.g.: maximum-routes)
                if config_property == "password":
                    return {"authentication_key": py23_compat.text_type(options[2])}
                    # returns the MD5 password
                if config_property == "route-map":
                    direction = None
                    if len(options) == 3:
                        direction = options[2]
                        field_value = field_type(options[1])  # the name of the policy
                    elif len(options) == 2:
                        direction = options[1]
                    if direction == "in":
                        field_name = "import_policy"
                    else:
                        field_name = "export_policy"
                    return {field_name: field_value}

            return {}

        bgp_config = {}

        commands = ["show running-config | section router bgp"]
        bgp_conf = self.device.run_commands(commands, encoding="text")[0].get(
            "output", "\n\n"
        )
        bgp_conf_lines = bgp_conf.splitlines()

        bgp_neighbors = {}

        if not group:
            neighbor = ""  # noqa

        local_as = 0
        bgp_neighbors = {}
        for bgp_conf_line in bgp_conf_lines:
            default_value = False
            bgp_conf_line = bgp_conf_line.strip()
            if bgp_conf_line.startswith("router bgp"):
                local_as = int(bgp_conf_line.replace("router bgp", "").strip())
                continue
            if not (
                bgp_conf_line.startswith("neighbor")
                or bgp_conf_line.startswith("no neighbor")
            ):
                continue
            if bgp_conf_line.startswith("no"):
                default_value = True
            bgp_conf_line = bgp_conf_line.replace("no neighbor ", "").replace(
                "neighbor ", ""
            )
            bgp_conf_line_details = bgp_conf_line.split()
            group_or_neighbor = py23_compat.text_type(bgp_conf_line_details[0])
            options = bgp_conf_line_details[1:]
            try:
                # will try to parse the neighbor name
                # which sometimes is the IP Address of the neigbor
                # or the name of the BGP group
                IPAddress(group_or_neighbor)
                # if passes the test => it is an IP Address, thus a Neighbor!
                peer_address = group_or_neighbor
                if peer_address not in bgp_neighbors:
                    bgp_neighbors[peer_address] = default_neighbor_dict(local_as)
                if options[0] == "peer-group":
                    bgp_neighbors[peer_address]["__group"] = options[1]

                # in the config, neighbor details are lister after
                # the group is specified for the neighbor:
                #
                # neighbor 192.168.172.36 peer-group 4-public-anycast-peers
                # neighbor 192.168.172.36 remote-as 12392
                # neighbor 192.168.172.36 maximum-routes 200
                #
                # because the lines are parsed sequentially
                # can use the last group detected
                # that way we avoid one more loop to
                # match the neighbors with the group they belong to
                # directly will apend the neighbor in the neighbor list of the group at the end

                bgp_neighbors[peer_address].update(
                    parse_options(options, default_value)
                )
            except AddrFormatError:
                # exception trying to parse group name
                # group_or_neighbor represents the name of the group
                group_name = group_or_neighbor
                if group and group_name != group:
                    continue
                if group_name not in bgp_config.keys():
                    bgp_config[group_name] = default_group_dict(local_as)
                bgp_config[group_name].update(parse_options(options, default_value))

        for peer, peer_details in bgp_neighbors.items():
            peer_group = peer_details.pop("__group", None)
            if not peer_group:
                peer_group = "_"
            if peer_group not in bgp_config:
                bgp_config[peer_group] = default_group_dict(local_as)
            bgp_config[peer_group]["neighbors"][peer] = peer_details

        return bgp_config