The following script has been circling around a lot of my pcapy google searches, it does exactly what I need it to do, which is live packet capture.
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
I want to stream the results into web ui through flask. Let's use part of the example script that comes with Flask (app.py). Which is the following:
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)
where it says INSERT STREAMING VARIABLE HERE is where pcapy results are supposed to stream to. For both of these to run concurrently I used threading:
bt = threading.Thread(name='background', target=background_thread)
rp = threading.Thread(name='', target=recv_pkts)
bt.start()
rp.start()
I want to see Pcapy results streamed into Flask but I have no idea how to do it. Please help!