-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathdatabase.py
More file actions
51 lines (43 loc) · 1.41 KB
/
Copy pathdatabase.py
File metadata and controls
51 lines (43 loc) · 1.41 KB
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
40
41
42
43
44
45
46
47
48
49
50
51
import sqlite3
import datetime
import os
from scapy.all import IP, TCP, UDP
if not os.path.exists('logs'):
os.makedirs('logs')
conn = sqlite3.connect("logs/firewall_logs.db", check_same_thread=False)
c = conn.cursor()
def setup_database():
c.execute('''CREATE TABLE IF NOT EXISTS connections (
id INTEGER PRIMARY KEY AUTOINCREMENT,
timestamp TEXT,
src_ip TEXT,
dst_ip TEXT,
src_port INTEGER,
dst_port INTEGER,
protocol TEXT,
process_name TEXT,
dst_country TEXT
)''')
conn.commit()
def log_packet(packet, process_name, dst_country):
timestamp = datetime.datetime.now().isoformat()
src_ip = packet[IP].src
dst_ip = packet[IP].dst
src_port, dst_port, protocol = (None, None, "IP")
if TCP in packet:
protocol = "TCP"
src_port = packet[TCP].sport
dst_port = packet[TCP].dport
elif UDP in packet:
protocol = "UDP"
src_port = packet[UDP].sport
dst_port = packet[UDP].dport
try:
c.execute(
"INSERT INTO connections (timestamp, src_ip, dst_ip, src_port, dst_port, protocol, process_name, dst_country) VALUES (?, ?, ?, ?, ?, ?, ?, ?)",
(timestamp, src_ip, dst_ip, src_port, dst_port, protocol, process_name, dst_country)
)
conn.commit()
except sqlite3.Error as e:
print(f"Database error: {e}")
setup_database()