我正在开发一个Python脚本来测试一个网络应用程序。作为测试的一部分,它需要移动网络配置(IP地址、路由.)从一个接口(物理接口)到另一个接口(桥),测试完成后,将系统恢复到原来的状态。在Python中实现这一点的最优雅的方法是什么?
我想过的一些想法:
ifconfig
调用和解析。但是,如果默认路由是通过物理接口,那么当我从物理interface.ip route ls
输出,并将路由与IP配置一起移动。这似乎是唯一合理的方法,但需要相当多的编码。iptables-save eth0>eth0_conf
,iptables-restore eth0_conf
?任何其他suggestions?这个测试工具必须是可移植的,并且能够在不同的Linux内核上运行。
发布于 2012-04-17 11:38:21
我建议采取以下办法:
interface
ifconfig eth0 down && ifconfig br0 up
并恢复:
执行ifconfig br0 down && ifconfig eth0 up
的
现在,对于路线,这取决于你有什么样的路线。如果使用显式接口定义静态路由,那么唯一的选择似乎是解析ip route ls
并将它们转换到新接口。
您还可以玩弄上下命令的顺序以及多个路由表:
ip route add <whatever> table 2
ip rule add from br0 table 2
但是这会变得很棘手,所以我的建议是坚持简单的解决方案,即使它包含更多的编码。
下面是xend的network-bridge
脚本中的另一个实现这一目标的示例:
# 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
}
https://stackoverflow.com/questions/10186298
复制相似问题