如何停止计时器线程

时间:2014-03-21 21:31:46

标签: python scapy traffic packets

这是我使用线程的代码

from scapy.all import *
from random import randint
import threading

# Generate packet
pkts = IP(src="10.0.0.1",dst="10.0.0.2")/TCP()/Raw(RandString(size=120))
#print pkts
pkts[TCP].flags = "UFP"

pktList = []
for pktNum in range(0,5):
    pktList.extend(pkts)
    pktList[pktNum][TCP].dport = randint(1,65535) # Pkt has Ran PortNo.
    print pktList[pktNum].summary()
    #print len(pktList[pktNum])
    wrpcap('tcp-packets.pcap',pktList[pktNum])

# Send the list of packets send(pktList)
def send_p():
    start_time=time.time()
    send(pktList)
    totalTime = time.time()-start_time
    print totalTime,"seconds"
    totalBytes=(50*120)/totalTime
    print '%4.1f' % totalBytes, "B/s"
    t=threading.Timer(2,send_p,())
    t.start()

t=threading.Timer(2,send_p,())
t.start()

我想在一段时间后停止线程,因为在我发出键盘中断之前,此代码不会停止。 我该怎么做?

1 个答案:

答案 0 :(得分:1)

线程是坚不可摧的,BuwaHahaha。改为使用多处理,这样就可以杀死所有人。

没有multiprocessing.Timer,所以请在运行流程之前使用import time time.sleep(2)

t=threading.Timer(2,send_p,())变为t=multiprocessing.Process(target=send_p)

使用您的代码的完整示例:

import multiprocessing
import time

# Code that you want to execute then later execute

time.sleep(2)
t=multiprocessing.Process(target=send_p)
t.start()
time.sleep(100) # "Some interval of time"
if t.is_alive():
    t.terminate() # Kill it with fire! or SIGTERM on linux

代码块返回有关每次运行的信息。

from scapy.all import *
from random import randint
import threading
import time
import multiprocessing
from itertools import count

# Generate packet
pkts = IP(src="10.0.0.1",dst="10.0.0.2")/TCP()/Raw(RandString(size=120))
#print pkts
pkts[TCP].flags = "UFP"

pktList = []
for pktNum in range(0,5):
    pktList.extend(pkts)
    pktList[pktNum][TCP].dport = randint(1,65535) # Pkt has Ran PortNo.
    print pktList[pktNum].summary()
    #print len(pktList[pktNum])
    wrpcap('tcp-packets.pcap',pktList[pktNum])

# Send the list of packets send(pktList)
def send_p(queue):
    for run_number in count(): # this will run indefinitely, same as while True, must be killed to stop.
        start_time=time.time()
        send(pktList)
        totalTime = time.time()-start_time
        totalBytes=(50*120)/totalTime
        queue.put((run_number, totalTime, totalBytes))

def create_p2p_traffic():
    pass # do stuff


q = multiprocessing.Queue()
t = multiprocessing.Process(target=send_p, args=(q, ))
t.start()

time.sleep(10)

### Runs without P2P traffic

rates = []

while True: # This loop will pull all items out of the queue and display them.
    run = q.get()
    if not run: # When we reach the end of the queue, exit
        break
print "Average rate of {0:.1f} B/s without p2p traffic".format(sum(rates)/float(len(rates)))


### Runs with P2P traffic

p = multiprocessing.Process(target=create_p2p_traffic)
p.start()

time.sleep(10) # "Some interval of time"

if t.is_alive():
    t.terminate()

if p.is_alive():
    p.terminate()

p2prates = []
while True: # This loop will pull all items out of the queue and display them.
    run = q.get()
    if not run: # When we reach the end of the queue, exit
        break
    run_number, total_time, total_bytes = run
    print "Run {run_number} took a total of {total_time}\
at an average rate of {total_bytes:.1f} B/s".format(run_number=run_number,
                                                    total_time=total_time,
                                                    total_bytes=total_bytes)
    p2prates.append(total_bytes)

print "Average rate of {0:.1f} B/s after p2p started".format(sum(p2prates)/float(len(p2prates)))