'How to run a Mininet CLI command from inside python module

I wrote a python module to generate a random topology using Mininet and connected OpenDayLight as the remote controller.

I would like to pass a command to the mininet CLI, but from inside the python module. After generating the hosts and switches as well as connecting them to the remote controller, the module randomly chooses 2 hosts to act as Server and Client. I am having trouble doing something similar to this, but from in-line inside the python module:

mininet> h<random_number> sudo python HTTPTraffic.py <SrcIP> <DstIP>

HTTPTraffic.py is another module that takes arguments SrcIP and DstIP

This is the part of the main module that elects 2 random hosts and gets their IPs. I would like the HTTPTraffic.py to run in the host corresponding to SrcIP

Nodes = list(range(1,h))
Src = random.choice(Nodes)         # randomly chooses 1 host
Nodes.remove(Src)
Dst = random.choice(Nodes)         # randomly chooses another host

SrcName = 'h%s' %(Src)
DstName = 'h%s' %(Dst)
SrcNode=net.get(SrcName)
DstNode=net.get(DstName)

SrcIP = SrcNode.IP()               # IP retrieval of chosen hosts
DstIP = DstNode.IP()
print ('The Souce/Client is: '+ SrcName)
print (SrcIP)
print ('The Destination/Server is: '+ DstName)
print (DstIP) 

SrcName +".cmd('sudo python HTTPTraffic.py "+SrcIP+" " +DstIP+"')"    # this is where I am having trouble

From the mininet API documentation (See section 'Customizing a Network'), something like that is possible but I am having so much trouble doing it. Also, I would like for this command to run in the background while the main program runs. Any feedback is appreciated.



Solution 1:[1]

I recommend you take a look at the documentation for the Python module subprocess, which acts as an platform-agnostic API for running other programs from your program.

For example, you can call ls by adding the following line to your code:

subprocess.run(["ls", "-l"])

The first argument of run takes an array of strings where each string is a part of the command you are executing.

Solution 2:[2]

You should to build somthing like this:

n=3
for i in range(4):
    user_input = 'h' + str(n)
    globals()[user_input] = net.addHost('h'+ str(n), cls=Host, ip='10.0.1.2'+ str(n) +'/24', defaultRoute='via 10.0.1.1')
    net.addLink(globals()[user_input],s6)
    n += 1

Sources

This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.

Source: Stack Overflow

Solution Source
Solution 1 wheeler
Solution 2 Lucas Fozzatti