由于stop_filter是作用在每一个packet的,当终止函数返回True的时候,只有在收到包的时候sniff才会返回,所以如果捕获的是明文数据,可以直接通过过滤Raw load方式处理,但是如果都是密文,通过kill方式来结束sniff也是一个可取的办法
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 |
from scapy.all import sniff, Raw, wrpcap import threading import time import signal e = threading.Event() def handler(signum, frame): global e e.set() def sniff_with_signal(): global e pcap = sniff(iface=['wlxe84e063348c8', 'lo'], stop_filter=lambda p: e.is_set()) #pcap = sniff(iface=['wlxe84e063348c8', 'lo'], # stop_filter=lambda p: p.haslayer(Raw) and 'stopflag' in p.getlayer(Raw).load) wrpcap('/tmp/test.pcap', pcap) print('pcap has wrote into file /tmp/test.pcap') def main(): signal.signal(signal.SIGTERM, handler) thread = threading.Thread(target=sniff_with_signal) thread.start() while True: thread.join(2) if thread.is_alive(): print('thread is alive') else: break if __name__ == '__main__': main() |