Python多线程" ping"

时间:2014-12-02 11:11:18

标签: python multithreading

我一直在尝试制作一个python脚本,它会要求你提供一个IP,并且我会做很多同时的PING。

但似乎我一次只能运行一个PING

我在OSX上运行

import _thread
import os
import time

def main():

    threadnbr = 0

    ip = str(input("Input the ip adresse to play with? "))
    threads = int(input("Have many threads? "))

    check(ip)

    if check(ip) == 0:
        print("It is up")
    else:
        print("Is is down")

    thread(ip, threads, threadnbr)

def thread(ip, threads, threadnbr):

    while threads > threadnbr:

        _thread.start_new_thread(dos(ip))

        threadnbr = threadnbr + 1

    else:
        print(threadnbr, " started")

def check(ip):

    response = os.system("ping -c 1 " + ip)

    return response

def dos(ip):

    os.system("ping -i 0.1 -s 8000 " + ip)
    print("1")

main()

2 个答案:

答案 0 :(得分:1)

_thread.start_new_thread(dos(ip))

这里没有正确提供参数 - 您的代码在主线程中运行。有关详细信息,请参阅the documentation

此外,您应该使用threading代替thread。该模块已弃用。

如果dos表示DoS,我真诚地希望您针对自己的基础设施进行教育。

答案 1 :(得分:1)

您可以使用Scapy lib而不是使用内置ping。 这是一个多线程ping:

import threading
from scapy.all import *

def send_pkt(dst,padding=0):
    pkt       = IP(dst=dst)/ICMP()/Padding('\x00'*padding)
    ans,unans = sr(pkt)
    ans.summary(lambda (s,r): r.sprintf("%IP.src% is alive"))


def thread(dst, threads, threadnbr):

    while threads > threadnbr:
        t = threading.Thread(None, send_pkt, None, (dst,), {'padding':8000})
        t.start()
        threadnbr = threadnbr + 1
    else:
        print(threadnbr, " started")


def main():
    dst       = raw_input("Input the ip adresse to play with? ")
    threads   = int(raw_input("Have many threads? "))
    threadnbr = 0

    send_pkt(dst)

    thread(dst, threads, threadnbr)

main()