import subprocess
import pyshark
import sqlite3

def open_ryu_controller():
    try:
        subprocess.Popen(["ryu-manager", "ryu.app.simple_switch_13"])
    except FileNotFoundError:
        print("Ryu controller not found. Please make sure Ryu is installed and in your system's PATH.")

def capture_packets(interface, connection, cursor):
    capture = pyshark.LiveCapture(interface=interface)

    try:
        # Start capturing packets
        for packet in capture.sniff_continuously():
            # Process and analyze the packet
            process_packet(packet, connection, cursor)

    except KeyboardInterrupt:
        # Handle keyboard interrupt (e.g., when the user presses Ctrl+C)
        pass

def process_packet(packet, connection, cursor):
    # Extract relevant information from the packet
    # Check the protocol and access the appropriate attributes for source and destination addresses
    if 'IP' in packet:
        source = packet['IP'].src
        destination = packet['IP'].dst
    elif 'IPv6' in packet:
        source = packet['IPv6'].src
        destination = packet['IPv6'].dst
    else:
        source = 'Unknown'
        destination = 'Unknown'

    # Other attributes
    protocol = packet.highest_layer
    length = packet.length

    # Perform vulnerability scanning or analysis on the packet
    # You can add your custom logic here to detect vulnerabilities

    # Print packet details
    print(f"Protocol: {protocol}, Source: {source}, Destination: {destination}, Length: {length}")

    # Insert packet data into the database table
    insert_packet_data(connection, cursor, protocol, source, destination, length)

def create_packet_table(cursor):
    # Create the packet table if it doesn't exist
    cursor.execute('''
        CREATE TABLE IF NOT EXISTS packets (
            id INTEGER PRIMARY KEY AUTOINCREMENT,
            protocol TEXT,
            source TEXT,
            destination TEXT,
            length INTEGER
        )
    ''')

def insert_packet_data(connection, cursor, protocol, source, destination, length):
    # Insert packet data into the database table
    cursor.execute('''
        INSERT INTO packets (protocol, source, destination, length)
        VALUES (?, ?, ?, ?)
    ''', (protocol, source, destination, length))
    connection.commit()

if __name__ == '__main__':
    # Specify the interface to capture packets on (e.g., 'eth0' or 'en0')
    interface = 'ens33'

    # Create a connection to the SQLite database file
    connection = sqlite3.connect('captured_packets.db')
    cursor = connection.cursor()

    # Call the function to create the packet table
    create_packet_table(cursor)

    # Call the function to start the Ryu controller
    open_ryu_controller()

    # Call the function to start capturing packets
    capture_packets(interface, connection, cursor)

    # Close the database connection when done
    connection.close()

