2012-04-17 69 views
2

我开发,测试一个网络应用的Python脚本。作为测试的一部分,它需要将网络配置(IP地址,路由...)从一个接口(物理接口)移动到另一个接口(网桥),并在测试完成后,将系统恢复到原来的状态。什么是在Python中完成这个最优雅的方法?移动IP配置到另一个

一些想法,我曾想过:

  1. 在测试期间不取消从物理接口的IP地址,这样路由不会丢失。但是,这将意味着相同的IP地址将共存于在测试过程中。这会成为某些特定Linux内核的问题吗?虽然,它似乎在我的系统上工作得很好...
  2. 将IP地址分配给网桥并取消分配从物理接口。易于在python中实现,因为这需要执行简单的ifconfig调用和解析。但如果默认路由是通过物理接口,那么它将在同一时间消失,当我从物理接口未分配IP地址。
  3. 解析ip route ls输出和路由与IP配置一起移动。这似乎是唯一合理的方法,但需要相当多的编码。

  4. 也许有一些更优雅?像iptables-save eth0>eth0_confiptables-restore eth0_conf?还有其他建议吗?

该测试工具必须是可移植的,并且能够在不同的Linux内核上运行。

回答

1

我建议以下方法:

  1. 确保桥接接口是向下
  2. 配置桥接接口
  3. 执行ifconfig eth0 down && ifconfig br0 up

,并恢复:

  1. 执行te 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/ 
[email protected]\([0-9]\+\.[0-9]\+\.[0-9]\+\.[0-9]\+/[0-9]\+\)@\[email protected] 
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 
} 
+0

我喜欢你带来向上/向下的接口,以恢复路线的方法。我想这可能适用于我。现在唯一的问题是 - 如何从eth0-> br0移动路由(我相信在测试过程中两个接口都应该启动)。 – 2012-04-17 17:09:56

+0

@AnsisAtteka你能详细阐述一下你的设置吗? br0包含哪些接口? eth0和br0在同一个物理网络上吗?你想达到什么目的? – mensi 2012-04-17 17:31:59

+0

至少根据我的经验,在同一子网中有两个物理接口可能会很痛苦。我设法通过为接口使用单独的路由表来解决这些问题。 – mensi 2012-04-17 17:32:54