使用 python 创建拓扑

Creating a topology using python

我想使用 python API 构建一个 mininet 拓扑。我的拓扑应该有 2 个控制器、3 个交换机,每个交换机将连接多个主机(连接的主机数分别为 2、4、1)。这是代码:

#!/usr/bin/python                                                                                                                                                                   

import time
from mininet.net import Mininet
from mininet.node import Controller, OVSKernelSwitch, RemoteController
from mininet.cli import CLI
from mininet.log import setLogLevel, info


def net():

    net = Mininet(controller=RemoteController, switch=OVSKernelSwitch)
    c1 = net.addController('c1', controller=RemoteController, ip="127.0.0.1", port=6653)
    c2 = net.addController('c2', controller=RemoteController, ip="127.0.0.1", port=7753)

    s_n = 3 #number of switches
    c_n = 2 #number of controllers
    hosts = []
    amount = [2, 4, 1] # number of hosts that each switch has

    info( "*** Creating switches\n" )
    switches = [ net.addSwitch( 's%s' % s ) for s in range( 1, s_n ) ]

    index1 = 0 
    L_in = 0
    index2 = 0

    info( "*** Creating hosts\n" )
    for s in switches:
        L_in = (L_in + 1)
        if L_in <= len(amount):

            index1 = (index2 + 1)
            index2 = (index1 + amount[L_in]) - 1
            hosts = [ net.addHost( 'h%s' % n ) for n in ( index1, index2 ) ]
            for h in hosts:
                net.addLink( s, h )
        else:
            break

    # Wire up switches
    last = None
    for switch in switches:
        if last:
            net.addLink( last, switch )
        last = switch

    net.build()
    c1.start()
    c2.start()

    for sw in switches[:c_n]:
        sw.start( [c1] )

    for sw in switches[c_n:]:   
        sw.start( [c2] )

    net.start()
    CLI( net )
    net.stop()


if __name__ == '__main__':
    setLogLevel( 'info' )
    net()

但是当我 运行 代码时,它无法正常工作。例如,我希望有 3 个开关,但创建了 2 个开关。我预计有 7 个主机,但创建了 4 个主机。主机和交换机之间的连接也不正确。这是输出:

*** Creating switches
*** Creating hosts
*** Configuring hosts
h1 h4 h5 h5 
*** Starting controller
c1 c2 
*** Starting 2 switches
s1 s2 ...
*** Starting CLI:
mininet> net
h1 h1-eth0:s1-eth1
h4 h4-eth0:s1-eth2
h5 h5-eth0:s2-eth2
h5 h5-eth0:s2-eth2
s1 lo:  s1-eth1:h1-eth0 s1-eth2:h4-eth0 s1-eth3:s2-eth3
s2 lo:  s2-eth1:h5-eth0 s2-eth2:h5-eth0 s2-eth3:s1-eth3
c1
c2

这里有很多问题。

range(1, n) 生成从 1n-1 的数字,而不是 n.

您定义的函数 net 将隐藏模块 net 的先前(导入的?)定义。称它为 make_net 或其他名称。

L_in 这样的显式循环索引几乎总是一个坏主意,就像 index2.

这样的非描述性名称一样

像这样的东西应该会给你这样的想法:

n_switches = 3
hosts_per_switch = [2, 4, 1]

switches = [addSwitch("s%d" % n + 1) for n in range(n_switches)]

for (switch, number_of_hosts) in zip(switches, hosts_per_switch):  # Pair them.
    hosts = [addHost("h%d" % n + 1) for n in range(number_of_hosts)]
    for host in hosts:
        addLink(switch, host)