我想使用tshark
(一种Wireshark的命令行风格)捕获数据包,同时连接到telnet上的远程主机设备。我想调用我为捕获而编写的函数:
def wire_cap(ip1,ip2,op_fold,file_name,duration): # invoke tshark to capture traffic during session
if duration == 0:
cmd='"tshark" -i 1 -P -w '+ op_fold+file_name+'.pcap src ' + str(ip1) + ' or src '+ str(ip2)
else:
cmd='"tshark" -i 1 -a duration:'+str(duration)+' -P -w '+ op_fold+file_name+'.pcap src ' + str(ip1) + ' or src '+ str(ip2)
p = subprocess.Popen(cmd, shell=True,stderr=subprocess.PIPE)
while True:
out = p.stderr.read(1)
if out == '' and p.poll() != None:
break
if out != '':
sys.stdout.write(out)
sys.stdout.flush()
出于调试目的,我想在后台运行此函数,方法是在需要时调用它,并在捕获后停止它。像这样:
Start a thread or a background process called wire_capture
//Do something here
Stop the thread or the background process wire_capture
通过阅读一点,我意识到thread.start_new_thread()
和threading.Thread()
似乎仅在我知道捕获的持续时间(退出条件)时才是合适的。我尝试使用thread.exit()
,但是它的作用类似于sys.exit()
,并完全停止了程序的执行。我还尝试了threading.Event()
,如下所示:
if cap_flg:
print "Starting a packet capture thread...."
th_capture = threading.Thread(target=wire_cap, name='Thread_Packet_Capture', args=(IP1, IP2, output, 'wire_capture', 0, ))
th_capture.setDaemon(True)
th_capture.start()
.
.
.
.
.
if cap_flg:
thread_kill = threading.Event()
print "Exiting the packet capture thread...."
thread_kill.set()
th_capture.join()
我想知道当我想停止进程时如何使其停止(例如可以添加退出条件以便退出线程执行)。我尝试的上述代码似乎无效。
答案 0 :(得分:2)
threading.Event()
方法是正确的,但是您需要在两个线程中都可见该事件,因此需要在启动第二个线程并将其传递之前创建它:
if cap_flg:
print "Starting a packet capture thread...."
thread_kill = threading.Event()
th_capture = threading.Thread(target=wire_cap, name='Thread_Packet_Capture', args=(IP1, IP2, output, 'wire_capture', 0, thread_kill))
th_capture.setDaemon(True)
th_capture.start()
在该while
循环中,让监视线程在每次迭代时检查该事件,如果已设置,则停止该循环(并可能终止它开始的tshark
)。您还需要通过仅从管道读取是否有可用数据来确保进程不会永远等待进程的输出,并忽略终止事件,
def wire_cap(ip1,ip2,op_fold,file_name,duration,event): # invoke tshark to capture traffic during session
if duration == 0:
cmd='"tshark" -i 1 -P -w '+ op_fold+file_name+'.pcap src ' + str(ip1) + ' or src '+ str(ip2)
else:
cmd='"tshark" -i 1 -a duration:'+str(duration)+' -P -w '+ op_fold+file_name+'.pcap src ' + str(ip1) + ' or src '+ str(ip2)
p = subprocess.Popen(cmd, shell=True,stderr=subprocess.PIPE)
while not event.is_set():
# Make sure to not block forever waiting for
# the process to say things, so we can see if
# the event gets set. Only read if data is available.
if len(select.select([p.stderr], [], [], 0.1)) > 0:
out = p.stderr.read(1)
if out == '' and p.poll() != None:
break
if out != '':
sys.stdout.write(out)
sys.stdout.flush()
p.kill()
然后要实际告诉线程停止,您只需设置事件:
if cap_flg:
print "Exiting the packet capture thread...."
thread_kill.set()
th_capture.join()