Reputation: 1698
I am developing a Python script that tests one networking application. As part of the test, it needs to move networking configuration (IP address, routes ...) from one interface (physical interface) to another interface (bridge), and after the test is done, restore the system back to its original state. What is the most elegant approach to accomplish this in Python?
Some ideas I have thought about:
ifconfig
calls and parsing. But if the default route was through the physical interface, then it would disappear at the same time, when I unassigned the IP address from physical interface.Parse the ip route ls
output and move the routes together with the IP config. This seems the only reasonable approach, but would require quite a lot of coding.
Maybe there is something more elegant? Like iptables-save eth0>eth0_conf
, iptables-restore eth0_conf
? Any other suggestions?
This test tool must be portable, and be able to run on different Linux Kernels.
Upvotes: 2
Views: 1750
Reputation: 9826
I would suggest the following approach:
ifconfig eth0 down && ifconfig br0 up
And to restore:
ifconfig br0 down && ifconfig eth0 up
Now for the routes it depends on what kind of routes you have. If you defined static routes with explicit interfaces, your only choice seems to be parsing ip route ls
and translating them to the new interface.
You can also toy around with the order of the up & down commands as well as multiple routing tables:
ip route add <whatever> table 2
ip rule add from br0 table 2
But this can get tricky, so my suggestion would be to stick to the simple solution, even if it includes some more coding.
Here is another example from xend's network-bridge
script to achieve this:
# Usage: transfer_addrs src dst
# Copy all IP addresses (including aliases) from device $src to device $dst.
transfer_addrs () {
local src=$1
local dst=$2
# Don't bother if $dst already has IP addresses.
if ip addr show dev ${dst} | egrep -q '^ *inet ' ; then
return
fi
# Address lines start with 'inet' and have the device in them.
# Replace 'inet' with 'ip addr add' and change the device name $src
# to 'dev $src'.
ip addr show dev ${src} | egrep '^ *inet ' | sed -e "
s/inet/ip addr add/
s@\([0-9]\+\.[0-9]\+\.[0-9]\+\.[0-9]\+/[0-9]\+\)@\1@
s/${src}/dev ${dst}/
" | sh -e
# Remove automatic routes on destination device
ip route list | sed -ne "
/dev ${dst}\( \|$\)/ {
s/^/ip route del /
p
}" | sh -e
}
# Usage: transfer_routes src dst
# Get all IP routes to device $src, delete them, and
# add the same routes to device $dst.
# The original routes have to be deleted, otherwise adding them
# for $dst fails (duplicate routes).
transfer_routes () {
local src=$1
local dst=$2
# List all routes and grep the ones with $src in.
# Stick 'ip route del' on the front to delete.
# Change $src to $dst and use 'ip route add' to add.
ip route list | sed -ne "
/dev ${src}\( \|$\)/ {
h
s/^/ip route del /
P
g
s/${src}/${dst}/
s/^/ip route add /
P
d
}" | sh -e
}
Upvotes: 1