Beispiel #1
0
 def __init__(self, *args, **kargs):
     utilsBase.__init__(self, *args, **kargs)
     try:
         import sys
         sys.path.insert(0, '/usr/share/ifupdown2/')
         from nlmanager.nlmanager import NetlinkManager
         # this should force the use of the local nlmanager
         self._nlmanager_api = NetlinkManager(extra_debug=False)
     except Exception as e:
         self.logger.error('cannot initialize ifupdown2\'s '
                           'netlink manager: %s' % str(e))
         raise
    args = parser.parse_args()

    # Build a list of route tuples to add/del
    # =======================================
    routes = []
    ecmp_routes = []
    rtbase = int(IPv4Address("11.0.0.0"))
    ip = IPv4Network(rtbase)
    nexthop = IPv4Address(args.nexthop)
    nexthop_ifindex = int(args.nexthopifindex)
    ROUTE_COUNT = int(args.count)

    for x in xrange(ROUTE_COUNT):
        ip = IPv4Network(rtbase)
        rtbase += 4  # we always use /30s for this test
        routes.append((AF_INET, ip.ip, 30, nexthop, nexthop_ifindex))

    log.info("Routes:\n%s" % pformat(routes))

    # Create an instance of NetlinkManager and
    # call routes_add() or routes_del()
    # =======================================
    nlmanager = NetlinkManager()

    if args.add:
        nlmanager.routes_add(routes, ecmp_routes, table=args.table)
    elif args.delete:
        nlmanager.routes_del(routes, ecmp_routes, table=args.table)
    else:
        raise Exception("You must specify --add or --delete")
#!/usr/bin/env python

import argparse
import logging
from nlmanager.nlmanager import NetlinkManager

# Logging and args
logging.basicConfig(level=logging.DEBUG,
                    format='%(asctime)s %(levelname)7s: %(message)s')
log = logging.getLogger()

parser = argparse.ArgumentParser(description="Create a bridge vlan interface")
parser.add_argument('ifindex', type=int, help='interface name')
parser.add_argument('vlan', type=int, help='vlan ID')
args = parser.parse_args()

# Create an instance of NetlinkManager and use it to add a subinterface
nlmanager = NetlinkManager()
nlmanager.debug_link(True)

log.info("Calling link_add_bridge_vlan() with ifindex %d, vlan_id %d" %
         (args.ifindex, args.vlan))
nlmanager.link_add_bridge_vlan(args.ifindex, args.vlan)
Beispiel #4
0
#!/usr/bin/env python

import argparse
import logging
from nlmanager.nlmanager import NetlinkManager
from nlmanager.nlpacket import RTM_SETLINK

# Logging and args
logging.basicConfig(level=logging.INFO,
                    format='%(asctime)s %(levelname)7s: %(message)s')
log = logging.getLogger()

# Create an instance of NetlinkManager and use it to add a subinterface
nlmanager = NetlinkManager()
# nlmanager.debug_link(True)
nlmanager.vlan_show()
Beispiel #5
0
        description="Add/del neighbors using nlmanager")
    parser.add_argument('--add',
                        action='store_true',
                        help='add routes',
                        default=False)
    parser.add_argument('--delete',
                        action='store_true',
                        help='delete routes',
                        default=False)
    # parser.add_argument('--count', help='Number of routes to add/delete', default=10)
    parser.add_argument('ifindex', type=int, help='Interface index')
    args = parser.parse_args()

    # Build a list of route tuples to add/del
    # =======================================
    ip = IPv4Address('11.1.1.1')
    mac = 'E02F.1234.1234'

    # Create an instance of NetlinkManager and
    # call neighbor_add() or neighbor_del()
    # ========================================
    nlmanager = NetlinkManager()
    nlmanager.debug_neighbor(True)

    if args.add:
        nlmanager.neighbor_add(AF_INET, args.ifindex, ip, mac)
    elif args.delete:
        nlmanager.neighbor_del(AF_INET, args.ifindex, ip, mac)
    else:
        raise Exception("You must specify --add or --delete")
Beispiel #6
0
class Netlink(utilsBase):
    VXLAN_UDP_PORT = 4789

    def __init__(self, *args, **kargs):
        utilsBase.__init__(self, *args, **kargs)
        try:
            import sys
            sys.path.insert(0, '/usr/share/ifupdown2/')
            from nlmanager.nlmanager import NetlinkManager
            # this should force the use of the local nlmanager
            self._nlmanager_api = NetlinkManager(extra_debug=False)
        except Exception as e:
            self.logger.error('cannot initialize ifupdown2\'s '
                              'netlink manager: %s' % str(e))
            raise

    def get_iface_index(self, ifacename):
        if ifupdownflags.flags.DRYRUN: return
        try:
            return self._nlmanager_api.get_iface_index(ifacename)
        except Exception as e:
            raise Exception('%s: netlink: %s: cannot get ifindex: %s' %
                            (ifacename, ifacename, str(e)))

    def link_add_vlan(self, vlanrawdevice, ifacename, vlanid):
        self.logger.info(
            '%s: netlink: ip link add link %s name %s type vlan id %s' %
            (ifacename, vlanrawdevice, ifacename, vlanid))
        if ifupdownflags.flags.DRYRUN: return
        ifindex = self.get_iface_index(vlanrawdevice)
        try:
            return self._nlmanager_api.link_add_vlan(ifindex, ifacename,
                                                     vlanid)
        except Exception as e:
            raise Exception('netlink: %s: cannot create vlan %s: %s' %
                            (vlanrawdevice, vlanid, str(e)))

    def link_add_macvlan(self, ifacename, macvlan_ifacename):
        self.logger.info(
            '%s: netlink: ip link add link %s name %s type macvlan mode private'
            % (ifacename, ifacename, macvlan_ifacename))
        if ifupdownflags.flags.DRYRUN: return
        ifindex = self.get_iface_index(ifacename)
        try:
            return self._nlmanager_api.link_add_macvlan(
                ifindex, macvlan_ifacename)
        except Exception as e:
            raise Exception('netlink: %s: cannot create macvlan %s: %s' %
                            (ifacename, macvlan_ifacename, str(e)))

    def link_set_updown(self, ifacename, state):
        self.logger.info('%s: netlink: ip link set dev %s %s' %
                         (ifacename, ifacename, state))
        if ifupdownflags.flags.DRYRUN: return
        try:
            return self._nlmanager_api.link_set_updown(ifacename, state)
        except Exception as e:
            raise Exception('netlink: cannot set link %s %s: %s' %
                            (ifacename, state, str(e)))

    def link_set_protodown(self, ifacename, state):
        self.logger.info('%s: netlink: set link %s protodown %s' %
                         (ifacename, ifacename, state))
        if ifupdownflags.flags.DRYRUN: return
        try:
            return self._nlmanager_api.link_set_protodown(ifacename, state)
        except Exception as e:
            raise Exception('netlink: cannot set link %s protodown %s: %s' %
                            (ifacename, state, str(e)))

    def link_set_master(self, ifacename, master_dev, state=None):
        self.logger.info(
            '%s: netlink: ip link set dev %s master %s %s' %
            (ifacename, ifacename, master_dev, state if state else ''))
        if ifupdownflags.flags.DRYRUN: return
        try:
            master = 0 if not master_dev else self.get_iface_index(master_dev)
            return self._nlmanager_api.link_set_master(ifacename,
                                                       master,
                                                       state=state)
        except Exception as e:
            raise Exception('netlink: %s: cannot set %s master %s: %s' %
                            (ifacename, ifacename, master_dev, str(e)))

    def link_set_nomaster(self, ifacename, state=None):
        self.logger.info('%s: netlink: ip link set dev %s nomaster %s' %
                         (ifacename, ifacename, state if state else ''))
        if ifupdownflags.flags.DRYRUN: return
        try:
            return self._nlmanager_api.link_set_master(ifacename,
                                                       0,
                                                       state=state)
        except Exception as e:
            raise Exception('netlink: %s: cannot set %s nomaster: %s' %
                            (ifacename, ifacename, str(e)))

    def link_add_bridge_vlan(self, ifacename, vlanid):
        self.logger.info('%s: netlink: bridge vlan add vid %s dev %s' %
                         (ifacename, vlanid, ifacename))
        if ifupdownflags.flags.DRYRUN: return
        ifindex = self.get_iface_index(ifacename)
        try:
            return self._nlmanager_api.link_add_bridge_vlan(ifindex, vlanid)
        except Exception as e:
            raise Exception('netlink: %s: cannot create bridge vlan %s: %s' %
                            (ifacename, vlanid, str(e)))

    def link_del_bridge_vlan(self, ifacename, vlanid):
        self.logger.info('%s: netlink: bridge vlan del vid %s dev %s' %
                         (ifacename, vlanid, ifacename))
        if ifupdownflags.flags.DRYRUN: return
        ifindex = self.get_iface_index(ifacename)
        try:
            return self._nlmanager_api.link_del_bridge_vlan(ifindex, vlanid)
        except Exception as e:
            raise Exception('netlink: %s: cannot remove bridge vlan %s: %s' %
                            (ifacename, vlanid, str(e)))

    def link_add_vxlan(self,
                       ifacename,
                       vxlanid,
                       local=None,
                       dstport=VXLAN_UDP_PORT,
                       group=None,
                       learning='on',
                       ageing=None):
        cmd = 'ip link add %s type vxlan id %s dstport %s' % (ifacename,
                                                              vxlanid, dstport)
        cmd += ' local %s' % local if local else ''
        cmd += ' ageing %s' % ageing if ageing else ''
        cmd += ' remote %s' % group if group else ' noremote'
        cmd += ' nolearning' if learning == 'off' else ''
        self.logger.info('%s: netlink: %s' % (ifacename, cmd))
        if ifupdownflags.flags.DRYRUN: return
        try:
            return self._nlmanager_api.link_add_vxlan(ifacename,
                                                      vxlanid,
                                                      dstport=dstport,
                                                      local=local,
                                                      group=group,
                                                      learning=learning,
                                                      ageing=ageing)
        except Exception as e:
            raise Exception('netlink: %s: cannot create vxlan %s: %s' %
                            (ifacename, vxlanid, str(e)))
#!/usr/bin/env python

import logging
from nlmanager.nlmanager import NetlinkManager

logging.basicConfig(level=logging.DEBUG,
                    format='%(asctime)s %(levelname)7s: %(message)s')
log = logging.getLogger()

nlmanager = NetlinkManager(log_level=logging.DEBUG)
nlmanager.debug_netconf(True)
nlmanager.netconf_dump()
#!/usr/bin/env python

import argparse
import logging
from nlmanager.nlmanager import NetlinkManager
from nlmanager.nlpacket import RTM_SETLINK

# Logging and args
logging.basicConfig(level=logging.DEBUG,
                    format='%(asctime)s %(levelname)7s: %(message)s')
log = logging.getLogger()

parser = argparse.ArgumentParser(description="Add VLAN(s) to an interface")
parser.add_argument('ifindex', type=int, help='interface name')
parser.add_argument('vlanstart', type=int, help='vlan ID')
parser.add_argument('vlanend', type=int, help='vlan ID')
args = parser.parse_args()

# Create an instance of NetlinkManager and use it to add a subinterface
nlmanager = NetlinkManager()
nlmanager.debug_link(True)

log.info("Calling vlan_modify() with ifindex %d, vlan start %d, vlan end %d" %
         (args.ifindex, args.vlanstart, args.vlanend))
nlmanager.vlan_modify(RTM_SETLINK, args.ifindex, args.vlanstart, args.vlanend)
2016-01-13 14:53:11,263  INFO: TXed  RTM_NEWLINK, pid 7582, seq 2, 76 bytes
2016-01-13 14:53:11,263  INFO: RXed  NLMSG_ERROR, pid 7582, seq 2, 36 bytes, error code NLE_SUCCESS...this is an ACK
root@superm-redxp-05[examples]#

root@superm-redxp-05[examples]# ip link show swp54.2
93: swp54.2@swp54: <BROADCAST,MULTICAST> mtu 1500 qdisc noop state DOWN mode DEFAULT
    link/ether 00:25:90:b2:01:fb brd ff:ff:ff:ff:ff:ff
root@superm-redxp-05[examples]#
"""

# Logging and args
logging.basicConfig(level=logging.DEBUG,
                    format='%(asctime)s %(levelname)7s: %(message)s')
log = logging.getLogger()

parser = argparse.ArgumentParser(description="Create a vlan interface")
parser.add_argument('interface', help='interface name')
args = parser.parse_args()

ifname = args.interface
(parent_ifname, vlan_id) = ifname.split('.')
vlan_id = int(vlan_id)

# Create an instance of NetlinkManager and use it to add a subinterface
nlmanager = NetlinkManager()
nlmanager.debug_link(True)
parent_index = nlmanager.get_iface_index(parent_ifname)

log.info("Calling link_add_vlan() with parent_index %d, ifname %s, vlan_id %d" % (parent_index, ifname, vlan_id))
nlmanager.link_add_vlan(parent_index, ifname, vlan_id)
root@superm-redxp-05[examples]# ip link show swp1
3: swp1: <BROADCAST,MULTICAST,UP,LOWER_UP> mtu 1500 qdisc pfifo_fast state UP mode DEFAULT qlen 500
    link/ether 00:25:90:b2:01:b7 brd ff:ff:ff:ff:ff:ff
root@superm-redxp-05[examples]#
"""

if __name__ == '__main__':
    logging.basicConfig(level=logging.DEBUG,
                        format='%(asctime)s %(levelname)7s: %(message)s')
    log = logging.getLogger()

    parser = argparse.ArgumentParser(description="Set interface up or down")
    parser.add_argument('--up',
                        action='store_true',
                        help='add routes',
                        default=False)
    parser.add_argument('--down',
                        action='store_true',
                        help='delete routes',
                        default=False)
    parser.add_argument('interface', help='interface name')
    args = parser.parse_args()

    nlmanager = NetlinkManager()
    if args.up:
        nlmanager.link_set_updown(args.interface, 'up')
    elif args.down:
        nlmanager.link_set_updown(args.interface, 'down')
    else:
        raise Exception("You must specify --up or --down")
Beispiel #11
0
#!/usr/bin/env python

import logging
import socket

from nlmanager.nlpacket import *
from nlmanager.nlmanager import NetlinkManager

logging.basicConfig(level=logging.INFO, format='%(asctime)s %(levelname)7s: %(message)s')
log = logging.getLogger()

nlmanager = NetlinkManager()

try:
    nl_if = nlmanager.get_iface_name(1)
    print nl_if[0:3]
except:
    print "nack"

Beispiel #12
0
#!/usr/bin/env python

import logging
import socket
from nlmanager.nlpacket import *
from nlmanager.nlmanager import NetlinkManager

logging.basicConfig(level=logging.INFO,
                    format='%(asctime)s %(levelname)7s: %(message)s')
log = logging.getLogger()

nlmanager = NetlinkManager()

print "%4s  %7s  %25s  %15s" % ('AFI', 'ifindex', 'Neighbor', 'MAC')
print "%s  %s  %s  %s" % ('=' * 4, '=' * 7, '=' * 25, '=' * 15)

for msg in nlmanager.request_dump(RTM_GETNEIGH, socket.AF_UNSPEC, debug=True):

    # dump color coded debug output. This also dumps the
    # msg.attributes dictionary in human readable format
    #
    # You must set "level=logging.DEBUG" to see this output
    # msg.dump()

    print "%s  %7d  %25s  %s" %\
        ("IPv4" if msg.family == socket.AF_INET else "IPv6",
         msg.ifindex,
         msg.get_attribute_value(Neighbor.NDA_DST),
         msg.get_attribute_value(Neighbor.NDA_LLADDR))
9.9.9.9/32  10.0.1.2           2

root@superm-redxp-05[examples]#
"""

if __name__ == '__main__':
    logging.basicConfig(level=logging.DEBUG,
                        format='%(asctime)s %(levelname)7s: %(message)s')
    log = logging.getLogger()

    parser = argparse.ArgumentParser(
        description="Do 'ip route get' equivalent")
    parser.add_argument('ip', help='IPv4 address to lookup')
    parser.add_argument('--debug',
                        action='store_true',
                        help='Enable debugs',
                        default=False)
    args = parser.parse_args()

    if args.debug:
        log.setLevel(logging.DEBUG)
        debug = True
    else:
        debug = False

    nlmanager = NetlinkManager()
    ip = IPv4Address(args.ip)

    routes = nlmanager.route_get(ip, debug=debug)
    nlmanager.routes_print(routes)