How to use the pyroute2.IPRoute function in pyroute2

To help you get started, we’ve selected a few pyroute2 examples, based on popular ways it is used in public projects.

Secure your code as it's written. Use Snyk Code to scan source code in minutes - no build needed - and fix issues immediately.

github iovisor / bcc / tests / python / test_brb.py View on Github external
# 8: ----------------------------------------------------------------------
# 8: Ran 1 test in 11.296s
# 8: 
# 8: OK

from ctypes import c_uint
from netaddr import IPAddress, EUI
from bcc import BPF
from pyroute2 import IPRoute, NetNS, IPDB, NSPopen
import sys
from time import sleep
from unittest import main, TestCase
from simulation import Simulation

arg1 = sys.argv.pop(1)
ipr = IPRoute()
ipdb = IPDB(nl=ipr)
sim = Simulation(ipdb)

class TestBPFSocket(TestCase):
    def set_default_const(self):
        self.ns1            = "ns1"
        self.ns2            = "ns2"
        self.ns_router      = "ns_router"
        self.vm1_ip         = "100.1.1.1"
        self.vm2_ip         = "200.1.1.1"
        self.vm1_rtr_ip     = "100.1.1.254"
        self.vm2_rtr_ip     = "200.1.1.254"
        self.vm1_rtr_mask   = "100.1.1.0/24"
        self.vm2_rtr_mask   = "200.1.1.0/24"

    def get_table(self, b):
github n0stack / n0stack / n0core / target / network / dhcp / dnsmasq.py View on Github external
>>> masq.delete_host_entry('9e:e8:1d:d0:2c:c9')

        Stop dnsmasq process.
        >>> masq.stop_process()

        Start dnsmasq process.
        >>> masq.start_process(pool)

        Respawn dnsmasq process to change its DHCP allocation pool.
        >>> pool = ['192.168.1.2', '192.168.1.128']
        >>> masq.respawn_process(pool)

        Delete DHCP server.
        >>> masq.delete_dhcp_server()
    """
    ip = IPRoute()  # type: IPRoute

    def __init__(self, network_id, bridge_name, log_dir=None):  # logging is disabled
        # type: (str, str, Optional[str]) -> None
        """
        Set names in order to create or delete resources.

        Args:
            subnet_id: Subnet ID.
            bridge_name: Name of bridge linked to Dnsmasq server.
            log_dir: Directory path to save log file.
        """
        id = network_id.split("-")[0]
        self.netns_name = 'nndhcp{}'.format(network_id)
        self.tap_name = 'ntndhcp{}'.format(id)
        self.peer_name = 'nedhcp{}'.format(id)
        self.bridge_name = bridge_name
github procszoo / procszoo / procszoo / network / __init__.py View on Github external
def get_all_oifnames_of_default_route(wifi=None):
    '''return list of all out interface index'''
    ipr = IPRoute()
    _idx_list = [r.get_attr('RTA_OIF') for r in ipr.get_default_routes()]
    if wifi:
        idx_list = _idx_list
    else:
        idx_list = [idx for idx in _idx_list if not is_ifindex_wireless(idx)]
    if not idx_list:
        return []
    links = ipr.get_links(*idx_list)
    name_list = [l.get_attr('IFLA_IFNAME') for l in links]
    ipr.close()
    return name_list
github fernnf / vsdnemul / vsdnemul / lib / iproutelib.py View on Github external
def _add_port_ns(ifname, netns, new_name=None):
    check_not_null(ifname, "the interface name cannot be null")
    check_not_null(netns, "the namespace node cannot be null")

    with IPRoute() as ipr:
        idx = ipr.link_lookup(ifname=ifname)[0]
        if new_name is not None:
            ipr.link('set', index=idx, net_ns_fd=netns, ifname=new_name, state="up")
        else:
            ipr.link('set', index=idx, net_ns_fd=netns, state="up")
github iovisor / bcc / examples / networking / tc_perf_event.py View on Github external
icmp_type = int(skb_event.raw[54])

    # Only print for echo request
    if icmp_type == 128:
        src_ip = bytes(bytearray(skb_event.raw[22:38]))
        dst_ip = bytes(bytearray(skb_event.raw[38:54]))
        print("%-3s %-32s %-12s 0x%08x" %
              (cpu, socket.inet_ntop(socket.AF_INET6, src_ip),
               socket.inet_ntop(socket.AF_INET6, dst_ip),
               skb_event.magic))

try:
    b = BPF(text=bpf_txt)
    fn = b.load_func("handle_egress", BPF.SCHED_CLS)

    ipr = pyroute2.IPRoute()
    ipr.link("add", ifname="me", kind="veth", peer="you")
    me = ipr.link_lookup(ifname="me")[0]
    you = ipr.link_lookup(ifname="you")[0]
    for idx in (me, you):
        ipr.link('set', index=idx, state='up')

    ipr.tc("add", "clsact", me)
    ipr.tc("add-filter", "bpf", me, ":1", fd=fn.fd, name=fn.name,
           parent="ffff:fff3", classid=1, direct_action=True)

    b["skb_events"].open_perf_buffer(print_skb_event)
    print('Try: "ping6 ff02::1%me"\n')
    print("%-3s %-32s %-12s %-10s" % ("CPU", "SRC IP", "DST IP", "Magic"))
    try:
        while True:
            b.perf_buffer_poll()
github fernnf / vsdnemul / vsdnemul / lib / iproutelib.py View on Github external
def create():
        with IPRoute() as ipr:
            ipr.link("add", ifname=ifname, kind="veth", peer=peer)

            ifnet = ipr.link_lookup(ifname=ifname)[0]
            ifpeer = ipr.link_lookup(ifname=peer)[0]

            ipr.link("set", index=ifnet,  mtu=mtu)
            ipr.link("set", index=ifnet, state="up")
            ipr.link("set", index=ifpeer, mtu=mtu)
            ipr.link("set", index=ifpeer, state="up")
github telstra / open-kilda / services / lab-service / traffexam / kilda / traffexam / model.py View on Github external
def __init__(self, name):
        self.name = name

        ip = pyroute2.IPRoute()
        idx = ip.link_lookup(ifname=self.name)
        if not idx:
            raise ValueError('network interface not found.'.format(name), name)
        self.index = idx[0]
github fernnf / vsdnemul / vsdnemul / lib / iproutelib.py View on Github external
def addport():
        with IPRoute() as ipr:
            inet = ipr.link_lookup(ifname=master)[0]

            for i in slaves:
                slave = ipr.link_lookup(ifname=i)[0]
                ipr.link("set", index=slave, master=inet)
github iovisor / bcc / examples / networking / distributed_bridge / main.py View on Github external
gretap = 0

if "mesh" in argv:
    multicast = 0

if "dhcp" in argv:
    dhcp = 1
    multicast = 0

if "gretap" in argv:
    gretap = 1
    multicast = 0

print("multicast %d dhcp %d gretap %d" % (multicast, dhcp, gretap))

ipr = IPRoute()
ipdb = IPDB(nl=ipr)

num_hosts = 3
null = open("/dev/null", "w")

class TunnelSimulation(Simulation):
    def __init__(self, ipdb):
        super(TunnelSimulation, self).__init__(ipdb)

    def start(self):
        # each entry is tuple of ns_ipdb, out_ifc, in_ifc
        host_info = []
        for i in range(0, num_hosts):
            print("Launching host %i of %i" % (i + 1, num_hosts))
            ipaddr = "172.16.1.%d/24" % (100 + i)
            host_info.append(self._create_ns("host%d" % i, ipaddr=ipaddr,
github freenas / freenas / src / middlewared / middlewared / plugins / interface / netif_linux / routing.py View on Github external
import enum
import ipaddress
import logging
import socket

import bidict
from pyroute2 import IPRoute

from .address.ipv6 import ipv6_netmask_to_prefixlen
from .address.types import AddressFamily

logger = logging.getLogger(__name__)

__all__ = ["Route", "RouteFlags", "RoutingTable"]

ip = IPRoute()


class Route:
    def __init__(self, network, netmask, gateway=None, interface=None, flags=None):
        self.network = ipaddress.ip_address(network)
        self.netmask = ipaddress.ip_address(netmask)
        self.gateway = ipaddress.ip_address(gateway) if gateway else None
        self.interface = interface or None
        self.flags = flags or set()

    def __getstate__(self):
        return {
            'network': str(self.network),
            'netmask': str(self.netmask),
            'gateway': str(self.gateway) if self.gateway else None,
            'interface': self.interface,