将IP配置从一个接口切换到另一个接口

时间:2012-04-17 06:35:03

标签: python linux networking

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

我想过的一些想法:

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

  4. 也许有更优雅的东西?与iptables-save eth0>eth0_confiptables-restore eth0_conf一样?还有其他建议吗?

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

1 个答案:

答案 0 :(得分:1)

我建议采用以下方法:

  1. 确保网桥接口已关闭
  2. 配置网桥接口
  3. 执行ifconfig eth0 down && ifconfig br0 up
  4. 要恢复:

    1. 执行ifconfig br0 down && ifconfig eth0 up
    2. 现在路线取决于您拥有的路线类型。如果使用显式接口定义静态路由,则唯一的选择似乎是解析ip route ls并将它们转换为新接口。

      你也可以玩起来& amp; down命令以及多个路由表:

      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
      }