以下脚本围绕我的许多谷歌搜索进行了调查,它完全符合我的需要,即实时数据包捕获。
import pcapy
from impacket.ImpactDecoder import *
# list all the network devices
pcapy.findalldevs()
max_bytes = 1024
promiscuous = False
read_timeout = 100 # in milliseconds
pc = pcapy.open_live("name of network device to capture from", max_bytes, promiscuous, read_timeout)
pc.setfilter('tcp')
# callback for received packets
def recv_pkts(hdr, data):
packet = EthDecoder().decode(data)
print packet
packet_limit = -1 # infinite
pc.loop(packet_limit, recv_pkts) # capture packets
我想通过烧瓶将结果流式传输到web ui中。让我们使用Flask(app.py)附带的部分示例脚本。以下是:
import threading
from flask import Flask, render_template, session, request
from flask_socketio import SocketIO, emit, join_room, leave_room, \
close_room, rooms, disconnect
import pcapy
from impacket.ImpactDecoder import *
from threading import Lock
app = Flask(__name__)
app.config['SECRET_KEY'] = 'secret!'
socketio = SocketIO(app, async_mode=async_mode)
thread = None
thread_lock = Lock()
def background_thread():
"""Example of how to send server generated events to clients."""
count = 0
while True:
socketio.sleep(10)
count += 1
socketio.emit('my_response',
{'data': 'Server generated event', 'count': **INSERT STREAMING VARIABLE HERE**},
namespace='/test')
@app.route('/')
def index():
return render_template('index.html', async_mode=socketio.async_mode)
@socketio.on('my_ping', namespace='/test')
def ping_pong():
emit('my_pong')
@socketio.on('connect', namespace='/test')
def test_connect():
global thread
with thread_lock:
if thread is None:
thread = socketio.start_background_task(target=background_thread)
emit('my_response', {'data': 'Connected', 'count': 0})
@socketio.on('disconnect', namespace='/test')
def test_disconnect():
print('Client disconnected', request.sid)
if __name__ == '__main__':
socketio.run(app, debug=True, port=4000)
其中 INSERT STREAMING VARIABLE HERE 是pcapy结果应该流向的地方。 为了同时运行这两个,我使用了线程:
bt = threading.Thread(name='background', target=background_thread)
rp = threading.Thread(name='', target=recv_pkts)
bt.start()
rp.start()
我想看到Pcapy的结果流入Flask,但我不知道该怎么做。请帮忙!