Network interfaces — pyroute2 0.9.4 documentation

# Network interfaces

## List interfaces

List interface keys:

    with NDB(log='on') as ndb:
        for key in ndb.interfaces:
            print(key)

NDB views support some dict methods: items(), values(), keys():

    with NDB(log='on') as ndb:
        for key, nic in ndb.interfaces.items():
            nic.set('state', 'up')
            nic.commit()

## Get interface objects

The keys may be used as selectors to get interface objects:

    with NDB() as ndb:
        for key in ndb.interfaces:
            print(ndb.interfaces[key])

Also possible selector formats are dict() and simple string. The latter means the interface name:

    eth0 = ndb.interfaces['eth0']

Dict selectors are necessary to get interfaces by other properties:

    wrk1_eth0 = ndb.interfaces[{'target': 'worker1.sample.com',
                                'ifname': 'eth0'}]

    wrk2_eth0 = ndb.interfaces[{'target': 'worker2.sample.com',
                                'address': '52:54:00:72:58:b2'}]

## Change nic properties

Changing MTU and MAC address:

    with ndb.interfaces['eth0'] as eth0:
        eth0['mtu'] = 1248
        eth0['address'] = '00:11:22:33:44:55'
    # --> <-- eth0.commit() is called by the context manager

One can change a property either using the assignment statement, or using the .set() routine:

    # same code
    with ndb.interfaces['eth0'] as eth0:
        eth0.set('mtu', 1248)
        eth0.set('address', '00:11:22:33:44:55')

## Create virtual interfaces

Create a bridge and add a port, eth0:

    with ndb.interfaces.create(ifname='br0', kind='bridge') as br0:
        br0.add_port('eth0')

## Bridge and bond ports

Add bridge and bond ports one can use specific API:

    with ndb.interfaces['br0'] as br0:
        br0.add_port('eth0')
        br0.add_port('eth1')
        br0.set('br_max_age', 1024)
        br0.set('br_forward_delay', 1500)

    with ndb.interfaces['bond0'] as bond0:
        bond0.add_port('eth0')
        bond0.add_port('eth1')

To remove a port:

    with ndb.interfaces['br0'] as br0:
        br0.del_port('eth0')

Or by setting the master property on a port, in the same way as with IPRoute:

    index = ndb.interfaces['br0']['index']

    # add a port to a bridge
    with ndb.interfaces['eth0'] as eth0:
        eth0.set('master', index)

    # remove a port from a bridge
    with ndb.interfaces['eth0'] as eth0:
        eth0.set('master', 0)