Пример #1
0
 def get_addr(self, family=AF_UNSPEC):
     '''
     Get all addresses.
     '''
     msg = ifaddrmsg()
     msg['family'] = family
     return self.nlm_request(msg, RTM_GETADDR)
Пример #2
0
 def get_addr(self, family=AF_UNSPEC):
     '''
     Get all addresses.
     '''
     msg = ifaddrmsg()
     msg['family'] = family
     return self.nlm_request(msg, RTM_GETADDR)
Пример #3
0
    def addr(self,
             command,
             index,
             address,
             mask=24,
             family=None,
             scope=0,
             **kwarg):
        '''
        Address operations

        * command -- add, delete
        * index -- device index
        * address -- IPv4 or IPv6 address
        * mask -- address mask
        * family -- socket.AF_INET for IPv4 or socket.AF_INET6 for IPv6
        * scope -- the address scope, see /etc/iproute2/rt_scopes

        Example::

            index = 62
            ip.addr("add", index, address="10.0.0.1", mask=24)
            ip.addr("add", index, address="10.0.0.2", mask=24)
        '''

        commands = {
            'add': RTM_NEWADDR,
            'del': RTM_DELADDR,
            'remove': RTM_DELADDR,
            'delete': RTM_DELADDR
        }
        command = commands.get(command, command)

        flags = NLM_F_REQUEST | NLM_F_ACK | NLM_F_CREATE | NLM_F_EXCL

        # try to guess family, if it is not forced
        if family is None:
            if address.find(":") > -1:
                family = AF_INET6
            else:
                family = AF_INET

        msg = ifaddrmsg()
        msg['index'] = index
        msg['family'] = family
        msg['prefixlen'] = mask
        msg['scope'] = scope
        if family == AF_INET:
            msg['attrs'] = [['IFA_LOCAL', address], ['IFA_ADDRESS', address]]
        elif family == AF_INET6:
            msg['attrs'] = [['IFA_ADDRESS', address]]
        for key in kwarg:
            nla = ifaddrmsg.name2nla(key)
            if kwarg[key] is not None:
                msg['attrs'].append([nla, kwarg[key]])
        return self.nlm_request(
            msg,
            msg_type=command,
            msg_flags=flags,
            terminate=lambda x: x['header']['type'] == NLMSG_ERROR)
Пример #4
0
    def addr(self, action, interface, address, mask=24, family=AF_INET):
        """
        Address operations

        * action -- add, delete
        * interface -- device index
        * address -- IPv4 or IPv6 address
        * mask -- address mask
        * family -- socket.AF_INET for IPv4 or socket.AF_INET6 for IPv6

        Example:

        dev = 62
        ip.addr("add", dev, address="10.0.0.1", mask=24)
        ip.addr("add", dev, address="10.0.0.2", mask=24)
        """

        actions = {"add": RTM_NEWADDR, "delete": RTM_DELADDR}
        action = actions.get(action, action)

        flags = NLM_F_REQUEST | NLM_F_ACK | NLM_F_CREATE | NLM_F_EXCL
        msg = ifaddrmsg()
        msg["index"] = interface
        msg["family"] = family
        msg["prefixlen"] = mask
        msg["scope"] = 0xFE
        if family == AF_INET:
            msg["attrs"] = (("IFA_LOCAL", address), ("IFA_ADDRESS", address))
        elif family == AF_INET6:
            msg["attrs"] = (("IFA_ADDRESS", address),)
        return self.nlm_request(msg, msg_type=action, msg_flags=flags)
Пример #5
0
 def get_addr(self, family=AF_UNSPEC):
     """
     Get all addresses.
     """
     msg = ifaddrmsg()
     msg["family"] = family
     return self.nlm_request(msg, RTM_GETADDR)
Пример #6
0
 def get_addr(self, *argv, **kwarg):
     ret = []
     data = self._ifc.run()
     parsed = self._ifc.parse(data)
     for name, specs in parsed['addrs'].items():
         for spec in specs:
             msg = ifaddrmsg().load(spec)
             del msg['value']
             ret.append(msg)
     return ret
Пример #7
0
 def get_addr(self, *argv, **kwarg):
     ret = []
     data = self._ifc.run()
     parsed = self._ifc.parse(data)
     for name, specs in parsed['addrs'].items():
         for spec in specs:
             msg = ifaddrmsg().load(spec)
             msg['header']['type'] = RTM_NEWADDR
             del msg['value']
             ret.append(msg)
     return ret
Пример #8
0
    def addr(self, command, index, address, mask=24,
             family=None, scope=0, **kwarg):
        '''
        Address operations

        * command -- add, delete
        * index -- device index
        * address -- IPv4 or IPv6 address
        * mask -- address mask
        * family -- socket.AF_INET for IPv4 or socket.AF_INET6 for IPv6
        * scope -- the address scope, see /etc/iproute2/rt_scopes

        Example::

            index = 62
            ip.addr("add", index, address="10.0.0.1", mask=24)
            ip.addr("add", index, address="10.0.0.2", mask=24)
        '''

        commands = {'add': RTM_NEWADDR,
                    'del': RTM_DELADDR,
                    'remove': RTM_DELADDR,
                    'delete': RTM_DELADDR}
        command = commands.get(command, command)

        flags = NLM_F_REQUEST | NLM_F_ACK | NLM_F_CREATE | NLM_F_EXCL

        # try to guess family, if it is not forced
        if family is None:
            if address.find(":") > -1:
                family = AF_INET6
            else:
                family = AF_INET

        msg = ifaddrmsg()
        msg['index'] = index
        msg['family'] = family
        msg['prefixlen'] = mask
        msg['scope'] = scope
        if family == AF_INET:
            msg['attrs'] = [['IFA_LOCAL', address],
                            ['IFA_ADDRESS', address]]
        elif family == AF_INET6:
            msg['attrs'] = [['IFA_ADDRESS', address]]
        for key in kwarg:
            nla = ifaddrmsg.name2nla(key)
            if kwarg[key] is not None:
                msg['attrs'].append([nla, kwarg[key]])
        return self.nlm_request(msg,
                                msg_type=command,
                                msg_flags=flags,
                                terminate=lambda x: x['header']['type'] ==
                                NLMSG_ERROR)
Пример #9
0
    def _GetAdaptersInfo(self):
        ret = {'interfaces': [],
               'addresses': []}

        # prepare buffer
        buf = ctypes.create_string_buffer(15000)
        buf_len = ctypes.c_ulong(15000)
        (ctypes
         .windll
         .iphlpapi
         .GetAdaptersInfo(ctypes.byref(buf),
                          ctypes.byref(buf_len)))
        adapter = IP_ADAPTER_INFO.from_address(ctypes.addressof(buf))
        while True:
            mac = ':'.join(['%02x' % x for x in adapter.Address][:6])
            ifname = (ctypes
                      .string_at(ctypes.addressof(adapter.AdapterName))
                      .decode('utf-8'))
            spec = {'index': adapter.Index,
                    'attrs': (['IFLA_ADDRESS', mac],
                              ['IFLA_IFNAME', ifname])}

            msg = ifinfmsg().load(spec)
            del msg['value']
            ret['interfaces'].append(msg)

            ipaddr = adapter.IpAddressList
            while True:
                addr = (ctypes
                        .string_at(ctypes.addressof(ipaddr.IpAddress))
                        .decode('utf-8'))
                mask = (ctypes
                        .string_at(ctypes.addressof(ipaddr.IpMask))
                        .decode('utf-8'))
                spec = {'index': adapter.Index,
                        'family': AF_INET,
                        'prefixlen': dqn2int(mask),
                        'attrs': (['IFA_ADDRESS', addr],
                                  ['IFA_LOCAL', addr],
                                  ['IFA_LABEL', ifname])}
                msg = ifaddrmsg().load(spec)
                del msg['value']
                ret['addresses'].append(msg)
                if ipaddr.Next:
                    ipaddr = ipaddr.Next.contents
                else:
                    break

            if adapter.Next:
                adapter = adapter.Next.contents
            else:
                break
        return ret
Пример #10
0
 def get_addr(self, family=AF_UNSPEC, index=None):
     """
     Get addresses::
         ip.get_addr()  # get all addresses
         ip.get_addr(index=2)  # get addresses for the 2nd interface
     """
     msg = ifaddrmsg()
     msg["family"] = family
     ret = self.nlm_request(msg, RTM_GETADDR)
     if index is not None:
         return [x for x in ret if x.get("index") == index]
     else:
         return ret
Пример #11
0
 def get_addr(self, family=AF_UNSPEC, index=None):
     '''
     Get addresses::
         ip.get_addr()  # get all addresses
         ip.get_addr(index=2)  # get addresses for the 2nd interface
     '''
     msg = ifaddrmsg()
     msg['family'] = family
     ret = self.nlm_request(msg, RTM_GETADDR)
     if index is not None:
         return [x for x in ret if x.get('index') == index]
     else:
         return ret
Пример #12
0
def convert_ifa_msg(msg):
    ret = ifaddrmsg()
    ret['header']['type'] = RTNL_NEWADDR if \
        msg['header']['type'] == RTM_NEWADDR else \
        RTNL_DELADDR
    ret['index'] = msg['IFP']['index']
    ret['family'] = msg['IFA']['header']['family']
    ret['prefixlen'] = dqn2int(msg['NETMASK']['address'], ret['family'])
    ret['attrs'] = [['IFA_ADDRESS', msg['IFA']['address']],
                    ['IFA_BROADCAST', msg['BRD']['address']],
                    ['IFA_LABEL', msg['IFP']['ifname']]]
    del ret['value']
    return ret
Пример #13
0
def convert_ifa_msg(msg):
    ret = ifaddrmsg()
    ret['header']['type'] = RTNL_NEWADDR if \
        msg['header']['type'] == RTM_NEWADDR else \
        RTNL_DELADDR
    ret['index'] = msg['IFP']['index']
    ret['family'] = msg['IFA']['header']['family']
    ret['prefixlen'] = dqn2int(msg['NETMASK']['address'], ret['family'])
    ret['attrs'] = [['IFA_ADDRESS', msg['IFA']['address']],
                    ['IFA_BROADCAST', msg['BRD']['address']],
                    ['IFA_LABEL', msg['IFP']['ifname']]]
    del ret['value']
    return ret
Пример #14
0
    def _GetAdaptersInfo(self):
        ret = {'interfaces': [],
               'addresses': []}

        # prepare buffer
        buf = ctypes.create_string_buffer(15000)
        buf_len = ctypes.c_ulong(15000)
        (ctypes
         .windll
         .iphlpapi
         .GetAdaptersInfo(ctypes.byref(buf),
                          ctypes.byref(buf_len)))
        adapter = IP_ADAPTER_INFO.from_address(ctypes.addressof(buf))
        while True:
            mac = ':'.join(['%02x' % x for x in adapter.Address][:6])
            ifname = ctypes.string_at(ctypes.addressof(adapter.AdapterName))
            spec = {'index': adapter.Index,
                    'attrs': (['IFLA_ADDRESS', mac],
                              ['IFLA_IFNAME', ifname])}

            msg = ifinfmsg().load(spec)
            del msg['value']
            ret['interfaces'].append(msg)

            ipaddr = adapter.IpAddressList
            while True:
                addr = ctypes.string_at(ctypes.addressof(ipaddr.IpAddress))
                mask = ctypes.string_at(ctypes.addressof(ipaddr.IpMask))
                spec = {'index': adapter.Index,
                        'family': AF_INET,
                        'prefixlen': dqn2int(mask),
                        'attrs': (['IFA_ADDRESS', addr],
                                  ['IFA_LOCAL', addr],
                                  ['IFA_LABEL', ifname])}
                msg = ifaddrmsg().load(spec)
                del msg['value']
                ret['addresses'].append(msg)
                if ipaddr.Next:
                    ipaddr = ipaddr.Next.contents
                else:
                    break

            if adapter.Next:
                adapter = adapter.Next.contents
            else:
                break
        return ret
Пример #15
0
    def addr(self, command, index=None, address=None, mask=None,
             family=None, scope=None, match=None, **kwarg):
        '''
        Address operations

        * command -- add, delete
        * index -- device index
        * address -- IPv4 or IPv6 address
        * mask -- address mask
        * family -- socket.AF_INET for IPv4 or socket.AF_INET6 for IPv6
        * scope -- the address scope, see /etc/iproute2/rt_scopes
        * \*\*kwarg -- any ifaddrmsg field or NLA

        Later the method signature will be changed to::

            def addr(self, command, match=None, **kwarg):
                # the method body

        So only keyword arguments (except of the command) will be accepted.
        The reason for this change is an unification of API.

        Example::

            idx = 62
            ip.addr('add', index=idx, address='10.0.0.1', mask=24)
            ip.addr('add', index=idx, address='10.0.0.2', mask=24)

        With more NLAs::

            # explicitly set broadcast address
            ip.addr('add', index=idx,
                    address='10.0.0.3',
                    broadcast='10.0.0.255',
                    prefixlen=24)

            # make the secondary address visible to ifconfig: add label
            ip.addr('add', index=idx,
                    address='10.0.0.4',
                    broadcast='10.0.0.255',
                    prefixlen=24,
                    label='eth0:1')
        '''

        flags_create = NLM_F_REQUEST | NLM_F_ACK | NLM_F_CREATE | NLM_F_EXCL
        commands = {'add': (RTM_NEWADDR, flags_create),
                    'del': (RTM_DELADDR, flags_create),
                    'remove': (RTM_DELADDR, flags_create),
                    'delete': (RTM_DELADDR, flags_create)}
        (command, flags) = commands.get(command, command)

        # fetch args
        index = index or kwarg.pop('index', 0)
        family = family or kwarg.pop('family', None)
        prefixlen = mask or kwarg.pop('mask', 0) or kwarg.pop('prefixlen', 0)
        scope = scope or kwarg.pop('scope', 0)

        # move address to kwarg
        # FIXME: add deprecation notice
        if address:
            kwarg['address'] = address

        # try to guess family, if it is not forced
        if kwarg.get('address') and family is None:
            if address.find(":") > -1:
                family = AF_INET6
                mask = mask or 128
            else:
                family = AF_INET
                mask = mask or 24

        # setup the message
        msg = ifaddrmsg()
        msg['index'] = index
        msg['family'] = family or 0
        msg['prefixlen'] = prefixlen
        msg['scope'] = scope

        # inject IFA_LOCAL, if family is AF_INET
        if family == AF_INET and kwarg.get('address'):
            kwarg['local'] = kwarg['address']

        # work on NLA
        for key in kwarg:
            nla = ifaddrmsg.name2nla(key)
            if kwarg[key] is not None:
                msg['attrs'].append([nla, kwarg[key]])

        ret = self.nlm_request(msg,
                               msg_type=command,
                               msg_flags=flags,
                               terminate=lambda x: x['header']['type'] ==
                               NLMSG_ERROR)
        if match:
            return self._match(match, ret)
        else:
            return ret
Пример #16
0
    def addr(self,
             command,
             index=None,
             address=None,
             mask=None,
             family=None,
             scope=None,
             match=None,
             **kwarg):
        '''
        Address operations

        * command -- add, delete
        * index -- device index
        * address -- IPv4 or IPv6 address
        * mask -- address mask
        * family -- socket.AF_INET for IPv4 or socket.AF_INET6 for IPv6
        * scope -- the address scope, see /etc/iproute2/rt_scopes
        * \*\*kwarg -- any ifaddrmsg field or NLA

        Later the method signature will be changed to::

            def addr(self, command, match=None, **kwarg):
                # the method body

        So only keyword arguments (except of the command) will be accepted.
        The reason for this change is an unification of API.

        Example::

            idx = 62
            ip.addr('add', index=idx, address='10.0.0.1', mask=24)
            ip.addr('add', index=idx, address='10.0.0.2', mask=24)

        With more NLAs::

            # explicitly set broadcast address
            ip.addr('add', index=idx,
                    address='10.0.0.3',
                    broadcast='10.0.0.255',
                    prefixlen=24)

            # make the secondary address visible to ifconfig: add label
            ip.addr('add', index=idx,
                    address='10.0.0.4',
                    broadcast='10.0.0.255',
                    prefixlen=24,
                    label='eth0:1')
        '''

        flags_create = NLM_F_REQUEST | NLM_F_ACK | NLM_F_CREATE | NLM_F_EXCL
        commands = {
            'add': (RTM_NEWADDR, flags_create),
            'del': (RTM_DELADDR, flags_create),
            'remove': (RTM_DELADDR, flags_create),
            'delete': (RTM_DELADDR, flags_create)
        }
        (command, flags) = commands.get(command, command)

        # fetch args
        index = index or kwarg.pop('index', 0)
        family = family or kwarg.pop('family', None)
        prefixlen = mask or kwarg.pop('mask', 0) or kwarg.pop('prefixlen', 0)
        scope = scope or kwarg.pop('scope', 0)

        # move address to kwarg
        # FIXME: add deprecation notice
        if address:
            kwarg['address'] = address

        # try to guess family, if it is not forced
        if kwarg.get('address') and family is None:
            if address.find(":") > -1:
                family = AF_INET6
                mask = mask or 128
            else:
                family = AF_INET
                mask = mask or 24

        # setup the message
        msg = ifaddrmsg()
        msg['index'] = index
        msg['family'] = family or 0
        msg['prefixlen'] = prefixlen
        msg['scope'] = scope

        # inject IFA_LOCAL, if family is AF_INET
        if family == AF_INET and kwarg.get('address'):
            kwarg['local'] = kwarg['address']

        # patch broadcast, if needed
        if kwarg.get('broadcast') is True:
            kwarg['broadcast'] = getbroadcast(address, mask, family)

        # work on NLA
        for key in kwarg:
            nla = ifaddrmsg.name2nla(key)
            if kwarg[key] is not None:
                msg['attrs'].append([nla, kwarg[key]])

        ret = self.nlm_request(
            msg,
            msg_type=command,
            msg_flags=flags,
            terminate=lambda x: x['header']['type'] == NLMSG_ERROR)
        if match:
            return self._match(match, ret)
        else:
            return ret