Update public source
This commit is contained in:
+365
@@ -0,0 +1,365 @@
|
||||
from pathlib import Path
|
||||
import subprocess
|
||||
import yaml
|
||||
|
||||
|
||||
class Config:
|
||||
|
||||
def __init__(self):
|
||||
|
||||
# Путь к конфигурационному файлу
|
||||
config_file = (
|
||||
Path(__file__).parent.parent
|
||||
/
|
||||
"config"
|
||||
/
|
||||
"config.yaml"
|
||||
)
|
||||
|
||||
|
||||
# Загрузка YAML
|
||||
with open(
|
||||
config_file,
|
||||
"r"
|
||||
) as file:
|
||||
|
||||
self.cfg = yaml.safe_load(file)
|
||||
|
||||
self._interface = None
|
||||
|
||||
|
||||
|
||||
# -----------------------------
|
||||
# GPS
|
||||
# -----------------------------
|
||||
|
||||
@property
|
||||
def gps_source(self):
|
||||
gps = self.cfg["gps"]
|
||||
|
||||
return gps.get(
|
||||
"source",
|
||||
"gpsrelay"
|
||||
)
|
||||
|
||||
@property
|
||||
def gpsrelay_host(self):
|
||||
gps = self.cfg["gps"]
|
||||
|
||||
if "gpsrelay" in gps:
|
||||
return gps["gpsrelay"]["host"]
|
||||
|
||||
return gps["host"]
|
||||
|
||||
@property
|
||||
def gpsrelay_port(self):
|
||||
gps = self.cfg["gps"]
|
||||
|
||||
if "gpsrelay" in gps:
|
||||
return gps["gpsrelay"]["port"]
|
||||
|
||||
return gps["port"]
|
||||
|
||||
@property
|
||||
def gnss_device(self):
|
||||
gnss = self.cfg["gps"]["gnss"]
|
||||
handler = gnss["handler"]
|
||||
|
||||
return gnss[handler]["device"]
|
||||
|
||||
@property
|
||||
def gnss_at_device(self):
|
||||
return self.cfg["gps"]["gnss"]["modem"]["at_device"]
|
||||
|
||||
@property
|
||||
def gnss_handler(self):
|
||||
return self.cfg["gps"]["gnss"]["handler"]
|
||||
|
||||
|
||||
|
||||
# -----------------------------
|
||||
# Database
|
||||
# -----------------------------
|
||||
|
||||
@property
|
||||
def database(self):
|
||||
|
||||
return self.cfg["database"]["file"]
|
||||
|
||||
@property
|
||||
def vendor_database(self):
|
||||
|
||||
return (
|
||||
Path(__file__).parent.parent
|
||||
/
|
||||
self.cfg["vendor"]["database"]
|
||||
)
|
||||
|
||||
@property
|
||||
def vendor_sources(self):
|
||||
|
||||
return self.cfg["vendor"]["sources"]
|
||||
|
||||
|
||||
# -----------------------------
|
||||
# WiFi
|
||||
# -----------------------------
|
||||
|
||||
@property
|
||||
def interface(self):
|
||||
|
||||
if self._interface is None:
|
||||
|
||||
raise RuntimeError(
|
||||
"WiFi interface is not selected."
|
||||
)
|
||||
|
||||
return self._interface
|
||||
|
||||
def select_interface(self):
|
||||
|
||||
result = subprocess.run(
|
||||
|
||||
[
|
||||
"sudo",
|
||||
"-n",
|
||||
"iw",
|
||||
"dev"
|
||||
],
|
||||
|
||||
capture_output=True,
|
||||
|
||||
text=True
|
||||
|
||||
)
|
||||
|
||||
interfaces = []
|
||||
|
||||
current = None
|
||||
|
||||
for line in result.stdout.splitlines():
|
||||
|
||||
line = line.strip()
|
||||
|
||||
if line.startswith("Interface"):
|
||||
|
||||
current = line.split()[1]
|
||||
|
||||
elif (
|
||||
line.startswith("type")
|
||||
and
|
||||
current
|
||||
):
|
||||
|
||||
if "monitor" in line or "managed" in line:
|
||||
|
||||
interfaces.append(
|
||||
current
|
||||
)
|
||||
|
||||
current = None
|
||||
|
||||
|
||||
if not interfaces:
|
||||
|
||||
raise RuntimeError(
|
||||
"No WiFi interface found."
|
||||
)
|
||||
|
||||
|
||||
iwlist = subprocess.run(
|
||||
|
||||
[
|
||||
"sudo",
|
||||
"-n",
|
||||
"iw",
|
||||
"list"
|
||||
],
|
||||
|
||||
capture_output=True,
|
||||
|
||||
text=True
|
||||
|
||||
).stdout
|
||||
|
||||
|
||||
if "monitor" not in iwlist.lower():
|
||||
|
||||
raise RuntimeError(
|
||||
"No adapter supports monitor mode."
|
||||
)
|
||||
|
||||
|
||||
import os
|
||||
|
||||
requested_interface = os.environ.get(
|
||||
"WIFI_INTERFACE"
|
||||
)
|
||||
|
||||
if requested_interface:
|
||||
|
||||
if requested_interface in interfaces:
|
||||
|
||||
self._interface = (
|
||||
requested_interface
|
||||
)
|
||||
|
||||
return self._interface
|
||||
|
||||
raise RuntimeError(
|
||||
f"WiFi interface '{requested_interface}' "
|
||||
"is not available."
|
||||
)
|
||||
|
||||
|
||||
if len(interfaces) == 1:
|
||||
|
||||
self._interface = interfaces[0]
|
||||
|
||||
return self._interface
|
||||
|
||||
|
||||
print()
|
||||
|
||||
print(
|
||||
"Available WiFi interfaces:"
|
||||
)
|
||||
|
||||
print()
|
||||
|
||||
for index, iface in enumerate(
|
||||
interfaces,
|
||||
start=1
|
||||
):
|
||||
|
||||
print(
|
||||
f"{index}) {iface}"
|
||||
)
|
||||
|
||||
print()
|
||||
|
||||
while True:
|
||||
|
||||
try:
|
||||
|
||||
value = int(
|
||||
input(
|
||||
"Select interface: "
|
||||
)
|
||||
)
|
||||
|
||||
if (
|
||||
1
|
||||
<= value
|
||||
<= len(interfaces)
|
||||
):
|
||||
|
||||
self._interface = (
|
||||
interfaces[value - 1]
|
||||
)
|
||||
|
||||
return self._interface
|
||||
|
||||
except Exception:
|
||||
|
||||
pass
|
||||
|
||||
print(
|
||||
"Invalid selection."
|
||||
)
|
||||
|
||||
@property
|
||||
def wifi_enable_2_4ghz(self):
|
||||
|
||||
return self.cfg["wifi"]["enable_2_4ghz"]
|
||||
|
||||
|
||||
@property
|
||||
def wifi_channels_2_4ghz(self):
|
||||
|
||||
return self.cfg["wifi"]["channels_2_4ghz"]
|
||||
|
||||
|
||||
@property
|
||||
def wifi_enable_5ghz(self):
|
||||
|
||||
return self.cfg["wifi"]["enable_5ghz"]
|
||||
|
||||
|
||||
@property
|
||||
def wifi_channels_5ghz(self):
|
||||
|
||||
return self.cfg["wifi"]["channels_5ghz"]
|
||||
|
||||
|
||||
@property
|
||||
def wifi_enable_6ghz(self):
|
||||
|
||||
return self.cfg["wifi"]["enable_6ghz"]
|
||||
|
||||
|
||||
@property
|
||||
def wifi_channels_6ghz(self):
|
||||
|
||||
return self.cfg["wifi"]["channels_6ghz"]
|
||||
|
||||
|
||||
@property
|
||||
def wifi_filtermode(self):
|
||||
|
||||
return self.cfg["wifi"]["filtermode"]
|
||||
|
||||
|
||||
@property
|
||||
def wifi_extra_args(self):
|
||||
|
||||
return self.cfg["wifi"]["extra_args"]
|
||||
|
||||
|
||||
|
||||
# -----------------------------
|
||||
# Tools
|
||||
# -----------------------------
|
||||
|
||||
@property
|
||||
def hcxdumptool(self):
|
||||
|
||||
return (
|
||||
Path(__file__).parent.parent
|
||||
/
|
||||
"bin"
|
||||
/
|
||||
"hcxdumptool"
|
||||
)
|
||||
|
||||
|
||||
@property
|
||||
def hcxpcapngtool(self):
|
||||
|
||||
return (
|
||||
Path(__file__).parent.parent
|
||||
/
|
||||
"bin"
|
||||
/
|
||||
"hcxpcapngtool"
|
||||
)
|
||||
|
||||
# -----------------------------
|
||||
# Capture
|
||||
# -----------------------------
|
||||
|
||||
@property
|
||||
def capture_directory(self):
|
||||
|
||||
return self.cfg["captures"]["directory"]
|
||||
|
||||
|
||||
|
||||
# -----------------------------
|
||||
# Status
|
||||
# -----------------------------
|
||||
|
||||
@property
|
||||
def status_interval(self):
|
||||
|
||||
return self.cfg["status"]["interval"]
|
||||
+1973
File diff suppressed because it is too large
Load Diff
@@ -0,0 +1,314 @@
|
||||
import os
|
||||
import subprocess
|
||||
import logging
|
||||
import sqlite3
|
||||
import csv
|
||||
|
||||
from vendor_import import VendorImporter
|
||||
|
||||
class EnvironmentChecker:
|
||||
"""
|
||||
Проверка окружения проекта.
|
||||
|
||||
Проверяются:
|
||||
|
||||
- наличие необходимых каталогов;
|
||||
- наличие бинарных файлов;
|
||||
- права на выполнение;
|
||||
- версия hcxdumptool;
|
||||
- наличие базы производителей.
|
||||
|
||||
Основная база проекта не проверяется,
|
||||
так как она может быть создана автоматически
|
||||
при первом запуске.
|
||||
"""
|
||||
|
||||
|
||||
def __init__(
|
||||
self,
|
||||
config
|
||||
):
|
||||
|
||||
self.config = config
|
||||
|
||||
self.log = logging.getLogger(
|
||||
"environment"
|
||||
)
|
||||
|
||||
|
||||
|
||||
# ---------------------------------------------------------
|
||||
# Главная проверка
|
||||
# ---------------------------------------------------------
|
||||
|
||||
def check(self):
|
||||
|
||||
self.log.info(
|
||||
"Checking application environment..."
|
||||
)
|
||||
|
||||
|
||||
self.check_binary(
|
||||
self.config.hcxdumptool,
|
||||
"hcxdumptool"
|
||||
)
|
||||
|
||||
|
||||
self.check_binary(
|
||||
self.config.hcxpcapngtool,
|
||||
"hcxpcapngtool"
|
||||
)
|
||||
|
||||
|
||||
self.check_hcxdumptool_version()
|
||||
|
||||
|
||||
self.check_vendor_database()
|
||||
|
||||
|
||||
self.log.info(
|
||||
"Environment OK"
|
||||
)
|
||||
|
||||
|
||||
|
||||
# ---------------------------------------------------------
|
||||
# Проверка бинарника
|
||||
# ---------------------------------------------------------
|
||||
|
||||
def check_binary(
|
||||
self,
|
||||
path,
|
||||
name
|
||||
):
|
||||
|
||||
if not path.exists():
|
||||
|
||||
raise RuntimeError(
|
||||
|
||||
f"{name} not found:\n\n{path}"
|
||||
|
||||
)
|
||||
|
||||
|
||||
if not path.is_file():
|
||||
|
||||
raise RuntimeError(
|
||||
|
||||
f"{name} is not a file:\n\n{path}"
|
||||
|
||||
)
|
||||
|
||||
|
||||
if not os.access(
|
||||
path,
|
||||
os.X_OK
|
||||
):
|
||||
|
||||
raise RuntimeError(
|
||||
|
||||
f"{name} is not executable:\n\n"
|
||||
f"{path}\n\n"
|
||||
f"Run:\n"
|
||||
f"chmod +x {path}"
|
||||
|
||||
)
|
||||
|
||||
|
||||
self.log.info(
|
||||
f"{name}: OK"
|
||||
)
|
||||
|
||||
|
||||
|
||||
# ---------------------------------------------------------
|
||||
# Проверка версии hcxdumptool
|
||||
# ---------------------------------------------------------
|
||||
|
||||
def check_hcxdumptool_version(self):
|
||||
|
||||
result = subprocess.run(
|
||||
|
||||
[
|
||||
str(
|
||||
self.config.hcxdumptool
|
||||
),
|
||||
"--help"
|
||||
],
|
||||
|
||||
capture_output=True,
|
||||
|
||||
text=True
|
||||
|
||||
)
|
||||
|
||||
|
||||
output = (
|
||||
result.stdout
|
||||
+
|
||||
result.stderr
|
||||
)
|
||||
|
||||
|
||||
if "7." not in output:
|
||||
|
||||
raise RuntimeError(
|
||||
|
||||
"Unsupported hcxdumptool version.\n"
|
||||
"Version 7.x is required."
|
||||
|
||||
)
|
||||
|
||||
|
||||
self.log.info(
|
||||
"hcxdumptool version: OK"
|
||||
)
|
||||
|
||||
|
||||
|
||||
# ---------------------------------------------------------
|
||||
# Проверка базы производителей
|
||||
# ---------------------------------------------------------
|
||||
|
||||
def check_vendor_database(self):
|
||||
|
||||
database = self.config.vendor_database
|
||||
|
||||
rebuild = False
|
||||
|
||||
if not database.exists():
|
||||
|
||||
self.log.warning(
|
||||
"Vendor database not found"
|
||||
)
|
||||
|
||||
rebuild = True
|
||||
|
||||
elif database.stat().st_size == 0:
|
||||
|
||||
self.log.warning(
|
||||
"Vendor database is empty"
|
||||
)
|
||||
|
||||
rebuild = True
|
||||
|
||||
else:
|
||||
|
||||
try:
|
||||
|
||||
connection = sqlite3.connect(
|
||||
database
|
||||
)
|
||||
|
||||
cursor = connection.cursor()
|
||||
|
||||
cursor.execute(
|
||||
"SELECT name FROM sqlite_master "
|
||||
"WHERE type='table' "
|
||||
"AND name='oui'"
|
||||
)
|
||||
|
||||
if cursor.fetchone() is None:
|
||||
|
||||
raise RuntimeError(
|
||||
"vendors table not found"
|
||||
)
|
||||
|
||||
cursor.execute(
|
||||
|
||||
"SELECT COUNT(*) FROM oui"
|
||||
|
||||
)
|
||||
|
||||
records = cursor.fetchone()[0]
|
||||
|
||||
if records < 50000:
|
||||
|
||||
raise RuntimeError(
|
||||
|
||||
f"Only {records} records"
|
||||
|
||||
)
|
||||
|
||||
cursor.execute(
|
||||
|
||||
"SELECT value "
|
||||
"FROM metadata "
|
||||
"WHERE key='import_status'"
|
||||
|
||||
)
|
||||
|
||||
row = cursor.fetchone()
|
||||
|
||||
if (
|
||||
|
||||
row is None
|
||||
|
||||
or
|
||||
|
||||
row[0] != "ok"
|
||||
|
||||
):
|
||||
|
||||
raise RuntimeError(
|
||||
|
||||
"Invalid import_status"
|
||||
|
||||
)
|
||||
|
||||
connection.close()
|
||||
|
||||
self.log.info(
|
||||
|
||||
f"Vendor database: OK ({records} records)"
|
||||
|
||||
)
|
||||
|
||||
return
|
||||
|
||||
except KeyboardInterrupt:
|
||||
|
||||
self.log.warning(
|
||||
"Download cancelled by user"
|
||||
)
|
||||
|
||||
raise
|
||||
|
||||
except Exception as error:
|
||||
|
||||
self.log.warning(
|
||||
|
||||
f"Vendor database is invalid: {error}"
|
||||
|
||||
)
|
||||
|
||||
rebuild = True
|
||||
|
||||
if rebuild:
|
||||
|
||||
database.unlink(
|
||||
missing_ok=True
|
||||
)
|
||||
|
||||
self.log.info(
|
||||
"Creating vendor database..."
|
||||
)
|
||||
|
||||
importer = VendorImporter(
|
||||
self.config
|
||||
)
|
||||
|
||||
importer.bootstrap()
|
||||
|
||||
if not database.exists():
|
||||
|
||||
raise RuntimeError(
|
||||
|
||||
"Unable to create vendor database."
|
||||
|
||||
)
|
||||
|
||||
self.log.info(
|
||||
"Vendor database created"
|
||||
)
|
||||
|
||||
+480
@@ -0,0 +1,480 @@
|
||||
import socket
|
||||
import threading
|
||||
import select
|
||||
import os
|
||||
import termios
|
||||
import logging
|
||||
import subprocess
|
||||
import pynmea2
|
||||
|
||||
from datetime import datetime, timezone
|
||||
|
||||
from models import GPSData
|
||||
|
||||
|
||||
class GPSRelaySource:
|
||||
|
||||
def __init__(self, host, port):
|
||||
|
||||
self.host = host
|
||||
self.port = port
|
||||
|
||||
self.socket = None
|
||||
|
||||
|
||||
def open(self):
|
||||
|
||||
self.socket = socket.create_connection(
|
||||
(
|
||||
self.host,
|
||||
self.port
|
||||
)
|
||||
)
|
||||
|
||||
return self.socket.makefile()
|
||||
|
||||
|
||||
def close(self):
|
||||
|
||||
if self.socket:
|
||||
|
||||
self.socket.close()
|
||||
|
||||
|
||||
class GpsdSource:
|
||||
|
||||
def __init__(self, host="127.0.0.1", port=2947):
|
||||
|
||||
self.host = host
|
||||
self.port = port
|
||||
|
||||
self.socket = None
|
||||
|
||||
|
||||
def open(self):
|
||||
|
||||
self.socket = socket.create_connection(
|
||||
(
|
||||
self.host,
|
||||
self.port
|
||||
)
|
||||
)
|
||||
|
||||
file = self.socket.makefile()
|
||||
|
||||
file.readline()
|
||||
|
||||
self.socket.sendall(
|
||||
b'?WATCH={"enable":true,"json":false,"nmea":true};\n'
|
||||
)
|
||||
|
||||
return file
|
||||
|
||||
|
||||
def close(self):
|
||||
|
||||
if self.socket:
|
||||
|
||||
self.socket.close()
|
||||
|
||||
|
||||
class SerialSource:
|
||||
|
||||
def __init__(self, device):
|
||||
|
||||
self.device = device
|
||||
|
||||
self.fd = None
|
||||
|
||||
self.lock = threading.Lock()
|
||||
|
||||
|
||||
def open(self):
|
||||
|
||||
self.fd = os.open(
|
||||
self.device,
|
||||
os.O_RDWR | os.O_NOCTTY
|
||||
)
|
||||
|
||||
attributes = termios.tcgetattr(
|
||||
self.fd
|
||||
)
|
||||
|
||||
attributes[0] = 0
|
||||
attributes[1] = 0
|
||||
attributes[2] = (
|
||||
termios.CLOCAL |
|
||||
termios.CREAD |
|
||||
termios.CS8
|
||||
)
|
||||
attributes[3] = 0
|
||||
|
||||
attributes[4] = termios.B9600
|
||||
attributes[5] = termios.B9600
|
||||
|
||||
attributes[6][
|
||||
termios.VMIN
|
||||
] = 0
|
||||
|
||||
attributes[6][
|
||||
termios.VTIME
|
||||
] = 5
|
||||
|
||||
termios.tcsetattr(
|
||||
self.fd,
|
||||
termios.TCSANOW,
|
||||
attributes
|
||||
)
|
||||
|
||||
return self
|
||||
|
||||
|
||||
def readline(self):
|
||||
|
||||
with self.lock:
|
||||
|
||||
buffer = b""
|
||||
|
||||
while True:
|
||||
|
||||
ready, _, _ = select.select(
|
||||
[self.fd],
|
||||
[],
|
||||
[],
|
||||
0.5
|
||||
)
|
||||
|
||||
if not ready:
|
||||
return ""
|
||||
|
||||
data = os.read(
|
||||
self.fd,
|
||||
1
|
||||
)
|
||||
|
||||
if not data:
|
||||
return ""
|
||||
|
||||
buffer += data
|
||||
|
||||
if data == b"\n":
|
||||
return buffer.decode(
|
||||
errors="replace"
|
||||
)
|
||||
|
||||
|
||||
def close(self):
|
||||
|
||||
with self.lock:
|
||||
|
||||
if self.fd is not None:
|
||||
|
||||
os.close(
|
||||
self.fd
|
||||
)
|
||||
|
||||
self.fd = None
|
||||
|
||||
class ModemGNSSSource:
|
||||
|
||||
def __init__(
|
||||
self,
|
||||
device,
|
||||
at_device
|
||||
):
|
||||
|
||||
self.device = device
|
||||
self.at_device = at_device
|
||||
|
||||
self.serial = SerialSource(
|
||||
device
|
||||
)
|
||||
|
||||
|
||||
def send_at(self, command):
|
||||
|
||||
result = subprocess.run(
|
||||
[
|
||||
"sudo",
|
||||
"-n",
|
||||
"atinout",
|
||||
"-",
|
||||
self.at_device,
|
||||
"-"
|
||||
],
|
||||
input=command + "\r\n",
|
||||
text=True,
|
||||
capture_output=True,
|
||||
timeout=10
|
||||
)
|
||||
|
||||
if result.returncode != 0:
|
||||
|
||||
raise RuntimeError(
|
||||
"AT command failed: "
|
||||
+ result.stderr.strip()
|
||||
)
|
||||
|
||||
return result.stdout
|
||||
|
||||
|
||||
def ensure_gnss_enabled(self):
|
||||
|
||||
response = self.send_at(
|
||||
"AT+QGPS?"
|
||||
)
|
||||
|
||||
if "+QGPS: 1" not in response:
|
||||
|
||||
self.send_at(
|
||||
"AT+QGPS=1"
|
||||
)
|
||||
|
||||
response = self.send_at(
|
||||
"AT+QGPS?"
|
||||
)
|
||||
|
||||
if "+QGPS: 1" not in response:
|
||||
|
||||
raise RuntimeError(
|
||||
"GNSS did not start."
|
||||
)
|
||||
|
||||
|
||||
def open(self):
|
||||
|
||||
self.ensure_gnss_enabled()
|
||||
|
||||
return self.serial.open()
|
||||
|
||||
|
||||
def readline(self):
|
||||
|
||||
return self.serial.readline()
|
||||
|
||||
|
||||
def close(self):
|
||||
|
||||
self.serial.close()
|
||||
|
||||
|
||||
def create_gps_source(cfg):
|
||||
|
||||
if cfg.gps_source == "gpsrelay":
|
||||
|
||||
return GPSRelaySource(
|
||||
cfg.gpsrelay_host,
|
||||
cfg.gpsrelay_port
|
||||
)
|
||||
|
||||
if cfg.gps_source == "gnss":
|
||||
|
||||
if cfg.gnss_handler == "gpsd":
|
||||
|
||||
return GpsdSource()
|
||||
|
||||
if cfg.gnss_handler == "modem":
|
||||
|
||||
return ModemGNSSSource(
|
||||
cfg.gnss_device,
|
||||
cfg.gnss_at_device
|
||||
)
|
||||
|
||||
if cfg.gnss_handler == "direct":
|
||||
|
||||
return SerialSource(
|
||||
cfg.gnss_device
|
||||
)
|
||||
|
||||
raise ValueError(
|
||||
f"Unknown GNSS handler: {cfg.gnss_handler}"
|
||||
)
|
||||
|
||||
raise ValueError(
|
||||
f"Unknown GPS source: {cfg.gps_source}"
|
||||
)
|
||||
|
||||
|
||||
def parse_nmea(
|
||||
line,
|
||||
received
|
||||
):
|
||||
|
||||
if not line.startswith("$"):
|
||||
|
||||
return None
|
||||
|
||||
try:
|
||||
msg = pynmea2.parse(
|
||||
line
|
||||
)
|
||||
|
||||
except Exception:
|
||||
|
||||
return None
|
||||
|
||||
message_type = getattr(
|
||||
msg,
|
||||
"sentence_type",
|
||||
""
|
||||
)
|
||||
|
||||
if message_type == "RMC":
|
||||
|
||||
if msg.status != "A":
|
||||
return None
|
||||
|
||||
speed = float(
|
||||
msg.spd_over_grnd or 0
|
||||
)
|
||||
|
||||
elif message_type == "GNS":
|
||||
|
||||
mode = getattr(
|
||||
msg,
|
||||
"mode_indicator",
|
||||
""
|
||||
)
|
||||
|
||||
if not mode or mode[0] == "N":
|
||||
return None
|
||||
|
||||
speed = 0
|
||||
|
||||
else:
|
||||
return None
|
||||
|
||||
try:
|
||||
|
||||
return GPSData(
|
||||
latitude=msg.latitude,
|
||||
longitude=msg.longitude,
|
||||
speed=speed,
|
||||
timestamp=received,
|
||||
valid=True
|
||||
)
|
||||
|
||||
except (TypeError, ValueError):
|
||||
return None
|
||||
|
||||
|
||||
class GPSManager:
|
||||
|
||||
def __init__(self, source, session):
|
||||
|
||||
self.source = source
|
||||
|
||||
self.session = session
|
||||
|
||||
self.current = None
|
||||
|
||||
self.running = False
|
||||
|
||||
self.thread = None
|
||||
|
||||
self.log = logging.getLogger("gps")
|
||||
|
||||
|
||||
def start(self):
|
||||
|
||||
self.running = True
|
||||
|
||||
self.thread = threading.Thread(
|
||||
target=self.worker,
|
||||
daemon=True
|
||||
)
|
||||
|
||||
self.thread.start()
|
||||
|
||||
|
||||
def parse_nmea(
|
||||
self,
|
||||
line,
|
||||
received
|
||||
):
|
||||
|
||||
gps = parse_nmea(
|
||||
line,
|
||||
received
|
||||
)
|
||||
|
||||
if gps is None:
|
||||
return
|
||||
|
||||
self.current = gps
|
||||
self.session.update_gps(
|
||||
gps
|
||||
)
|
||||
|
||||
|
||||
def worker(self):
|
||||
|
||||
file = None
|
||||
|
||||
try:
|
||||
|
||||
file = self.source.open()
|
||||
|
||||
self.log.info(
|
||||
"GPS connection established"
|
||||
)
|
||||
|
||||
with open(
|
||||
self.session.gps_file,
|
||||
"a"
|
||||
) as gps_log:
|
||||
|
||||
while self.running:
|
||||
|
||||
if hasattr(
|
||||
self.source,
|
||||
"readline"
|
||||
):
|
||||
|
||||
line = self.source.readline()
|
||||
|
||||
else:
|
||||
|
||||
line = file.readline()
|
||||
|
||||
if not line:
|
||||
continue
|
||||
|
||||
received = datetime.now(
|
||||
timezone.utc
|
||||
)
|
||||
|
||||
gps_log.write(
|
||||
f"{received.isoformat().replace('+00:00', 'Z')};{line}"
|
||||
)
|
||||
|
||||
gps_log.flush()
|
||||
|
||||
self.session.add_nmea()
|
||||
|
||||
self.parse_nmea(
|
||||
line,
|
||||
received
|
||||
)
|
||||
|
||||
except Exception as error:
|
||||
|
||||
self.log.error(
|
||||
f"GPS error: {error}"
|
||||
)
|
||||
|
||||
finally:
|
||||
|
||||
self.source.close()
|
||||
|
||||
|
||||
def get(self):
|
||||
|
||||
return self.current
|
||||
|
||||
|
||||
def stop(self):
|
||||
|
||||
self.running = False
|
||||
|
||||
self.source.close()
|
||||
+291
@@ -0,0 +1,291 @@
|
||||
import threading
|
||||
import time
|
||||
|
||||
from datetime import datetime, timezone
|
||||
|
||||
from gps import create_gps_source, parse_nmea
|
||||
|
||||
|
||||
class GPSTestService:
|
||||
|
||||
def __init__(
|
||||
self,
|
||||
cfg,
|
||||
callback=None
|
||||
):
|
||||
|
||||
self.cfg = cfg
|
||||
self.callback = callback
|
||||
|
||||
self.thread = None
|
||||
self.stop_event = threading.Event()
|
||||
|
||||
self.running = False
|
||||
self.state = "READY"
|
||||
|
||||
self.nmea_received = False
|
||||
self.fix_received = False
|
||||
|
||||
self.nmea_count = 0
|
||||
self.fix_count = 0
|
||||
|
||||
self.latitude = None
|
||||
self.longitude = None
|
||||
|
||||
self.error = None
|
||||
|
||||
|
||||
def emit(self, message):
|
||||
|
||||
if self.callback:
|
||||
self.callback(message)
|
||||
|
||||
|
||||
def start(self):
|
||||
|
||||
if (
|
||||
self.thread is not None
|
||||
and
|
||||
self.thread.is_alive()
|
||||
):
|
||||
return False
|
||||
|
||||
self.stop_event.clear()
|
||||
|
||||
self.running = True
|
||||
self.state = "STARTING"
|
||||
self.nmea_received = False
|
||||
self.fix_received = False
|
||||
self.nmea_count = 0
|
||||
self.fix_count = 0
|
||||
self.latitude = None
|
||||
self.longitude = None
|
||||
self.error = None
|
||||
|
||||
self.thread = threading.Thread(
|
||||
target=self.worker,
|
||||
daemon=True
|
||||
)
|
||||
|
||||
self.thread.start()
|
||||
|
||||
return True
|
||||
|
||||
|
||||
def stop(self):
|
||||
|
||||
self.stop_event.set()
|
||||
|
||||
|
||||
def worker(self):
|
||||
|
||||
source = None
|
||||
file = None
|
||||
|
||||
try:
|
||||
|
||||
self.emit(
|
||||
"[GPS TEST] Starting GPS test "
|
||||
"from saved configuration."
|
||||
)
|
||||
|
||||
source = create_gps_source(
|
||||
self.cfg
|
||||
)
|
||||
|
||||
self.emit(
|
||||
"[GPS TEST] Connecting to GPS source..."
|
||||
)
|
||||
|
||||
file = source.open()
|
||||
|
||||
self.state = "CONNECTED"
|
||||
|
||||
self.emit(
|
||||
"[GPS TEST] GPS source connected. "
|
||||
"Waiting for NMEA..."
|
||||
)
|
||||
|
||||
last_no_fix_message = 0
|
||||
|
||||
while not self.stop_event.is_set():
|
||||
|
||||
if hasattr(
|
||||
source,
|
||||
"readline"
|
||||
):
|
||||
|
||||
line = source.readline()
|
||||
|
||||
else:
|
||||
|
||||
line = file.readline()
|
||||
|
||||
if not line:
|
||||
continue
|
||||
|
||||
self.nmea_count += 1
|
||||
self.nmea_received = True
|
||||
|
||||
if self.state == "CONNECTED":
|
||||
|
||||
self.state = "NMEA"
|
||||
|
||||
self.emit(
|
||||
"[GPS TEST] NMEA received. "
|
||||
"Waiting for valid FIX..."
|
||||
)
|
||||
|
||||
received = datetime.now(
|
||||
timezone.utc
|
||||
)
|
||||
|
||||
gps = parse_nmea(
|
||||
line,
|
||||
received
|
||||
)
|
||||
|
||||
if gps is not None:
|
||||
|
||||
first_fix = not self.fix_received
|
||||
|
||||
self.fix_count += 1
|
||||
self.fix_received = True
|
||||
self.state = "FIX"
|
||||
self.latitude = gps.latitude
|
||||
self.longitude = gps.longitude
|
||||
|
||||
self.emit(
|
||||
"[GPS TEST] FIX received: "
|
||||
f"lat={gps.latitude:.6f} "
|
||||
f"lon={gps.longitude:.6f}"
|
||||
)
|
||||
|
||||
if first_fix:
|
||||
|
||||
self.emit(
|
||||
"[GPS TEST] GPS is ready "
|
||||
"for scanning."
|
||||
)
|
||||
|
||||
elif self.fix_count % 10 == 0:
|
||||
|
||||
self.emit(
|
||||
"[GPS TEST] GPS is ready "
|
||||
"for scanning. "
|
||||
f"FIX: lat={gps.latitude:.6f} "
|
||||
f"lon={gps.longitude:.6f}"
|
||||
)
|
||||
|
||||
elif (
|
||||
self.nmea_received
|
||||
and
|
||||
not self.fix_received
|
||||
and
|
||||
self.nmea_count % 10 == 0
|
||||
and
|
||||
time.monotonic() - last_no_fix_message >= 5
|
||||
):
|
||||
|
||||
last_no_fix_message = (
|
||||
time.monotonic()
|
||||
)
|
||||
|
||||
self.emit(
|
||||
"[GPS TEST] GPS is not ready: "
|
||||
"NMEA received, but no valid FIX yet. "
|
||||
f"NMEA: {self.nmea_count}"
|
||||
)
|
||||
|
||||
except Exception as error:
|
||||
|
||||
self.state = "ERROR"
|
||||
self.error = str(error)
|
||||
|
||||
self.emit(
|
||||
f"[GPS TEST] GPS source error: {error}"
|
||||
)
|
||||
|
||||
finally:
|
||||
|
||||
if source is not None:
|
||||
|
||||
try:
|
||||
source.close()
|
||||
|
||||
except Exception as error:
|
||||
|
||||
self.emit(
|
||||
f"[GPS TEST] Close error: {error}"
|
||||
)
|
||||
|
||||
self.running = False
|
||||
|
||||
if self.state != "ERROR":
|
||||
|
||||
self.state = "STOPPED"
|
||||
|
||||
self.emit(
|
||||
"[GPS TEST] Test stopped."
|
||||
)
|
||||
|
||||
|
||||
def run_gps_test(cfg):
|
||||
|
||||
def output(message):
|
||||
|
||||
print(
|
||||
message,
|
||||
flush=True
|
||||
)
|
||||
|
||||
service = GPSTestService(
|
||||
cfg,
|
||||
callback=output
|
||||
)
|
||||
|
||||
service.start()
|
||||
|
||||
try:
|
||||
|
||||
while service.running:
|
||||
|
||||
time.sleep(0.2)
|
||||
|
||||
except KeyboardInterrupt:
|
||||
|
||||
print(
|
||||
"[GPS TEST] Test interrupted by user.",
|
||||
flush=True
|
||||
)
|
||||
|
||||
if service.fix_received:
|
||||
|
||||
print(
|
||||
"[GPS TEST] Result: "
|
||||
"GPS is ready for scanning.",
|
||||
flush=True
|
||||
)
|
||||
|
||||
print(
|
||||
"[GPS TEST] Last position: "
|
||||
f"lat={service.latitude:.6f} "
|
||||
f"lon={service.longitude:.6f}",
|
||||
flush=True
|
||||
)
|
||||
|
||||
else:
|
||||
|
||||
print(
|
||||
"[GPS TEST] Result: "
|
||||
"GPS is not ready for scanning.",
|
||||
flush=True
|
||||
)
|
||||
|
||||
service.stop()
|
||||
|
||||
while service.running:
|
||||
|
||||
time.sleep(0.1)
|
||||
|
||||
return 0 if service.fix_received else 1
|
||||
@@ -0,0 +1,52 @@
|
||||
import logging
|
||||
from pathlib import Path
|
||||
|
||||
|
||||
|
||||
def setup_logger():
|
||||
|
||||
|
||||
Path(
|
||||
"logs"
|
||||
).mkdir(
|
||||
exist_ok=True
|
||||
)
|
||||
|
||||
|
||||
|
||||
logging.basicConfig(
|
||||
|
||||
|
||||
level=logging.INFO,
|
||||
|
||||
|
||||
format=(
|
||||
|
||||
"%(asctime)s "
|
||||
"[%(levelname)s] "
|
||||
"%(name)s: "
|
||||
"%(message)s"
|
||||
|
||||
),
|
||||
|
||||
|
||||
handlers=[
|
||||
|
||||
|
||||
logging.FileHandler(
|
||||
"logs/project.log"
|
||||
),
|
||||
|
||||
|
||||
logging.StreamHandler()
|
||||
|
||||
]
|
||||
|
||||
|
||||
)
|
||||
|
||||
|
||||
|
||||
return logging.getLogger(
|
||||
"project-wifi"
|
||||
)
|
||||
+496
@@ -0,0 +1,496 @@
|
||||
import signal
|
||||
import sys
|
||||
import time
|
||||
import logging
|
||||
|
||||
|
||||
from config import Config
|
||||
from database import Database
|
||||
from gps import GPSManager, create_gps_source
|
||||
from gps_test import run_gps_test
|
||||
from logger import setup_logger
|
||||
from network import NetworkManagerControl
|
||||
from wifi import WiFiManager
|
||||
from session import Session
|
||||
from environment import EnvironmentChecker
|
||||
from sudo import SudoChecker
|
||||
|
||||
|
||||
# ============================================================
|
||||
# Инициализация
|
||||
# ============================================================
|
||||
|
||||
|
||||
cfg = Config()
|
||||
|
||||
|
||||
if "--gps-test" in sys.argv:
|
||||
|
||||
sudo_checker = SudoChecker()
|
||||
|
||||
sudo_checker.check()
|
||||
|
||||
sys.exit(
|
||||
run_gps_test(
|
||||
cfg
|
||||
)
|
||||
)
|
||||
|
||||
logger = setup_logger()
|
||||
|
||||
|
||||
logger.info(
|
||||
"Project started"
|
||||
)
|
||||
|
||||
|
||||
# ============================================================
|
||||
# Проверка окружения
|
||||
# ============================================================
|
||||
|
||||
try:
|
||||
|
||||
environment = EnvironmentChecker(
|
||||
cfg
|
||||
)
|
||||
|
||||
environment.check()
|
||||
|
||||
sudo_checker = SudoChecker()
|
||||
|
||||
sudo_checker.check()
|
||||
|
||||
cfg.select_interface()
|
||||
|
||||
logger.info(
|
||||
f"WiFi interface: {cfg.interface}"
|
||||
)
|
||||
|
||||
except KeyboardInterrupt:
|
||||
|
||||
logger.info(
|
||||
"Startup cancelled"
|
||||
)
|
||||
|
||||
sys.exit(0)
|
||||
|
||||
# ============================================================
|
||||
# Network
|
||||
# ============================================================
|
||||
|
||||
|
||||
network = NetworkManagerControl(
|
||||
cfg.interface
|
||||
)
|
||||
|
||||
wifi = None
|
||||
|
||||
gps = None
|
||||
|
||||
session = None
|
||||
|
||||
db = None
|
||||
|
||||
parser = None
|
||||
|
||||
session_id = None
|
||||
|
||||
network_prepared = False
|
||||
|
||||
shutdown_requested = False
|
||||
|
||||
scanner_state = "READY"
|
||||
|
||||
def set_scanner_state(state):
|
||||
|
||||
global scanner_state
|
||||
|
||||
if scanner_state == state:
|
||||
return
|
||||
|
||||
scanner_state = state
|
||||
|
||||
print(
|
||||
f"ScannerState: {state}",
|
||||
flush=True
|
||||
)
|
||||
|
||||
|
||||
def shutdown(signum=None, frame=None):
|
||||
|
||||
global shutdown_requested
|
||||
global network_prepared
|
||||
|
||||
if shutdown_requested:
|
||||
return
|
||||
|
||||
shutdown_requested = True
|
||||
|
||||
set_scanner_state(
|
||||
"STOPPED"
|
||||
)
|
||||
|
||||
logger.info(
|
||||
"Shutdown requested"
|
||||
)
|
||||
|
||||
|
||||
try:
|
||||
|
||||
if wifi:
|
||||
|
||||
wifi.stop()
|
||||
|
||||
|
||||
except Exception as error:
|
||||
|
||||
logger.error(
|
||||
f"WiFi stop error: {error}"
|
||||
)
|
||||
|
||||
try:
|
||||
|
||||
if parser and session:
|
||||
|
||||
parser.parse(
|
||||
session,
|
||||
session_id
|
||||
)
|
||||
|
||||
|
||||
except Exception as error:
|
||||
|
||||
logger.error(
|
||||
f"Parser error: {error}"
|
||||
)
|
||||
|
||||
try:
|
||||
|
||||
if gps:
|
||||
|
||||
gps.stop()
|
||||
|
||||
|
||||
except Exception as error:
|
||||
|
||||
logger.error(
|
||||
f"GPS stop error: {error}"
|
||||
)
|
||||
|
||||
|
||||
|
||||
try:
|
||||
|
||||
if (db and session_id is not None):
|
||||
|
||||
db.flush_observations()
|
||||
|
||||
db.finalize_session(
|
||||
session_id
|
||||
)
|
||||
|
||||
db.commit()
|
||||
|
||||
except Exception as error:
|
||||
|
||||
logger.error(
|
||||
f"Database finalize error: {error}"
|
||||
)
|
||||
|
||||
|
||||
|
||||
try:
|
||||
|
||||
if network_prepared:
|
||||
|
||||
network.restore()
|
||||
|
||||
|
||||
except Exception as error:
|
||||
|
||||
logger.error(
|
||||
f"Network restore error: {error}"
|
||||
)
|
||||
|
||||
|
||||
|
||||
try:
|
||||
|
||||
if db:
|
||||
|
||||
db.close()
|
||||
|
||||
|
||||
except Exception:
|
||||
|
||||
pass
|
||||
|
||||
|
||||
|
||||
logger.info(
|
||||
"Project stopped"
|
||||
)
|
||||
|
||||
|
||||
|
||||
sys.exit(0)
|
||||
|
||||
|
||||
signal.signal(
|
||||
signal.SIGINT,
|
||||
shutdown
|
||||
)
|
||||
|
||||
signal.signal(
|
||||
signal.SIGTERM,
|
||||
shutdown
|
||||
)
|
||||
|
||||
from parser import CaptureParser
|
||||
|
||||
# ============================================================
|
||||
# Подготовка оборудования
|
||||
# ============================================================
|
||||
|
||||
|
||||
try:
|
||||
|
||||
network_prepared = True
|
||||
|
||||
network.prepare()
|
||||
|
||||
# ============================================================
|
||||
# Сессия
|
||||
# ============================================================
|
||||
|
||||
session = Session(
|
||||
cfg.capture_directory
|
||||
)
|
||||
|
||||
logger.info(
|
||||
f"Session directory: {session.path}"
|
||||
)
|
||||
|
||||
logger.info(
|
||||
f"Capture file: {session.capture_file}"
|
||||
)
|
||||
|
||||
logger.info(
|
||||
f"GPS track: {session.gps_file}"
|
||||
)
|
||||
|
||||
|
||||
# ============================================================
|
||||
# Database
|
||||
# ============================================================
|
||||
|
||||
db = Database(
|
||||
cfg.database
|
||||
)
|
||||
|
||||
logger.info(
|
||||
"SQLite initialized"
|
||||
)
|
||||
|
||||
parser = CaptureParser(
|
||||
cfg,
|
||||
db
|
||||
)
|
||||
|
||||
session_id = db.create_session(
|
||||
str(session.capture_file)
|
||||
)
|
||||
|
||||
session.id = session_id
|
||||
|
||||
wifi = WiFiManager(
|
||||
cfg,
|
||||
session,
|
||||
cfg.interface
|
||||
)
|
||||
|
||||
gps_source = create_gps_source(
|
||||
cfg
|
||||
)
|
||||
|
||||
gps = GPSManager(
|
||||
gps_source,
|
||||
session
|
||||
)
|
||||
|
||||
wifi.start()
|
||||
|
||||
gps.start()
|
||||
|
||||
set_scanner_state(
|
||||
"ACTIVE"
|
||||
)
|
||||
|
||||
|
||||
except KeyboardInterrupt:
|
||||
|
||||
logger.info(
|
||||
"Startup cancelled"
|
||||
)
|
||||
|
||||
shutdown()
|
||||
|
||||
except Exception as error:
|
||||
|
||||
logger.error(
|
||||
f"Startup error: {error}"
|
||||
)
|
||||
|
||||
shutdown()
|
||||
|
||||
|
||||
# ============================================================
|
||||
# Главный цикл
|
||||
# ============================================================
|
||||
|
||||
|
||||
last_status = 0
|
||||
|
||||
last_capture_size = 0
|
||||
|
||||
capture_stall_count = 0
|
||||
|
||||
last_sudo_keepalive = time.time()
|
||||
|
||||
sudo_keepalive_interval = 60
|
||||
|
||||
|
||||
while True:
|
||||
|
||||
|
||||
now = time.time()
|
||||
|
||||
if (
|
||||
now - last_sudo_keepalive
|
||||
>= sudo_keepalive_interval
|
||||
):
|
||||
|
||||
if sudo_checker.refresh():
|
||||
|
||||
logger.debug(
|
||||
"Sudo keepalive: OK"
|
||||
)
|
||||
|
||||
else:
|
||||
|
||||
logger.warning(
|
||||
"WARNING: sudo keepalive failed"
|
||||
)
|
||||
|
||||
last_sudo_keepalive = now
|
||||
|
||||
|
||||
if wifi and wifi.process:
|
||||
|
||||
return_code = wifi.process.poll()
|
||||
|
||||
if return_code is not None:
|
||||
|
||||
if return_code == 0:
|
||||
|
||||
logger.info(
|
||||
"hcxdumptool finished"
|
||||
)
|
||||
|
||||
else:
|
||||
|
||||
logger.error(
|
||||
f"hcxdumptool exited with code {return_code}"
|
||||
)
|
||||
|
||||
shutdown()
|
||||
|
||||
|
||||
|
||||
if ( now - last_status >= cfg.status_interval ):
|
||||
capture_bytes = 0
|
||||
try:
|
||||
capture_bytes = ( session.capture_file.stat().st_size )
|
||||
except Exception:
|
||||
pass
|
||||
|
||||
#
|
||||
# контроль роста capture.pcapng
|
||||
#
|
||||
if last_capture_size:
|
||||
if capture_bytes <= last_capture_size:
|
||||
capture_stall_count += 1
|
||||
else:
|
||||
capture_stall_count = 0
|
||||
|
||||
last_capture_size = capture_bytes
|
||||
capture_size = ( capture_bytes / 1024 )
|
||||
capture_text = ( f"{capture_size:.1f}KB")
|
||||
|
||||
|
||||
|
||||
pid = "-"
|
||||
|
||||
if wifi and wifi.process:
|
||||
|
||||
pid = wifi.process.pid
|
||||
|
||||
gps_data = session.current_gps
|
||||
|
||||
|
||||
|
||||
if gps_data:
|
||||
|
||||
|
||||
logger.info(
|
||||
|
||||
"Status: "
|
||||
f"elapsed={session.elapsed()}s "
|
||||
f"nmea={session.nmea_messages} "
|
||||
f"gps={session.gps_positions} "
|
||||
f"lat={gps_data.latitude:.6f} "
|
||||
f"lon={gps_data.longitude:.6f} "
|
||||
f"capture={capture_text} "
|
||||
f"pid={pid}"
|
||||
|
||||
)
|
||||
|
||||
|
||||
|
||||
else:
|
||||
|
||||
|
||||
logger.info(
|
||||
|
||||
"Status: "
|
||||
f"elapsed={session.elapsed()}s "
|
||||
f"nmea={session.nmea_messages} "
|
||||
f"gps={session.gps_positions} "
|
||||
f"capture={capture_text} "
|
||||
f"pid={pid} "
|
||||
"gps=no signal"
|
||||
|
||||
)
|
||||
|
||||
|
||||
|
||||
|
||||
last_status = now
|
||||
|
||||
if capture_stall_count >= 3:
|
||||
|
||||
logger.warning(
|
||||
"WARNING: capture file is not growing"
|
||||
)
|
||||
|
||||
set_scanner_state(
|
||||
"WARNING"
|
||||
)
|
||||
|
||||
else:
|
||||
|
||||
set_scanner_state(
|
||||
"ACTIVE"
|
||||
)
|
||||
|
||||
time.sleep(1)
|
||||
@@ -0,0 +1,11 @@
|
||||
from dataclasses import dataclass
|
||||
from datetime import datetime
|
||||
|
||||
|
||||
@dataclass
|
||||
class GPSData:
|
||||
latitude: float
|
||||
longitude: float
|
||||
speed: float
|
||||
timestamp: datetime
|
||||
valid: bool
|
||||
+210
@@ -0,0 +1,210 @@
|
||||
import logging
|
||||
import subprocess
|
||||
|
||||
|
||||
class NetworkManagerControl:
|
||||
|
||||
|
||||
def __init__(self, interface):
|
||||
|
||||
self.interface = interface
|
||||
|
||||
self.log = logging.getLogger(
|
||||
"network"
|
||||
)
|
||||
|
||||
|
||||
self.restore_networkmanager = False
|
||||
|
||||
self.restore_wpa = False
|
||||
|
||||
|
||||
|
||||
def _run(self, command):
|
||||
|
||||
subprocess.run(
|
||||
[
|
||||
"sudo",
|
||||
"-n"
|
||||
]
|
||||
+
|
||||
command,
|
||||
stdout=subprocess.DEVNULL,
|
||||
stderr=subprocess.DEVNULL
|
||||
)
|
||||
|
||||
|
||||
|
||||
def _is_active(self, service):
|
||||
|
||||
|
||||
result = subprocess.run(
|
||||
|
||||
[
|
||||
"systemctl",
|
||||
"is-active",
|
||||
service
|
||||
],
|
||||
|
||||
capture_output=True,
|
||||
|
||||
text=True
|
||||
|
||||
)
|
||||
|
||||
|
||||
return (
|
||||
result.stdout.strip()
|
||||
==
|
||||
"active"
|
||||
)
|
||||
|
||||
|
||||
|
||||
def prepare(self):
|
||||
|
||||
|
||||
self.restore_networkmanager = self._is_active(
|
||||
"NetworkManager"
|
||||
)
|
||||
|
||||
|
||||
self.restore_wpa = self._is_active(
|
||||
"wpa_supplicant"
|
||||
)
|
||||
|
||||
|
||||
|
||||
self.log.info(
|
||||
f"NetworkManager : {'running' if self.restore_networkmanager else 'stopped'}"
|
||||
)
|
||||
|
||||
|
||||
self.log.info(
|
||||
f"wpa_supplicant : {'running' if self.restore_wpa else 'stopped'}"
|
||||
)
|
||||
|
||||
|
||||
|
||||
if self.restore_networkmanager:
|
||||
|
||||
|
||||
self._run(
|
||||
[
|
||||
"systemctl",
|
||||
"stop",
|
||||
"NetworkManager"
|
||||
]
|
||||
)
|
||||
|
||||
|
||||
|
||||
if self.restore_wpa:
|
||||
|
||||
|
||||
self._run(
|
||||
[
|
||||
"systemctl",
|
||||
"stop",
|
||||
"wpa_supplicant"
|
||||
]
|
||||
)
|
||||
|
||||
|
||||
|
||||
self.log.info(
|
||||
"Network services stopped"
|
||||
)
|
||||
|
||||
|
||||
|
||||
def restore(self):
|
||||
|
||||
self.log.info(
|
||||
"Restoring WiFi interface"
|
||||
)
|
||||
|
||||
self._run(
|
||||
[
|
||||
"ip",
|
||||
"link",
|
||||
"set",
|
||||
self.interface,
|
||||
"down"
|
||||
]
|
||||
)
|
||||
|
||||
self._run(
|
||||
[
|
||||
"iw",
|
||||
"dev",
|
||||
self.interface,
|
||||
"set",
|
||||
"type",
|
||||
"managed"
|
||||
]
|
||||
)
|
||||
|
||||
self._run(
|
||||
[
|
||||
"ip",
|
||||
"link",
|
||||
"set",
|
||||
self.interface,
|
||||
"up"
|
||||
]
|
||||
)
|
||||
|
||||
self.log.info(
|
||||
"WiFi interface restored to managed mode"
|
||||
)
|
||||
|
||||
|
||||
if self.restore_wpa:
|
||||
|
||||
self._run(
|
||||
[
|
||||
"systemctl",
|
||||
"start",
|
||||
"wpa_supplicant"
|
||||
]
|
||||
)
|
||||
|
||||
|
||||
if self.restore_networkmanager:
|
||||
|
||||
self._run(
|
||||
[
|
||||
"systemctl",
|
||||
"start",
|
||||
"NetworkManager"
|
||||
]
|
||||
)
|
||||
|
||||
|
||||
if self.restore_networkmanager:
|
||||
|
||||
self._run(
|
||||
[
|
||||
"nmcli",
|
||||
"device",
|
||||
"set",
|
||||
self.interface,
|
||||
"managed",
|
||||
"yes"
|
||||
]
|
||||
)
|
||||
|
||||
self._run(
|
||||
[
|
||||
"nmcli",
|
||||
"device",
|
||||
"connect",
|
||||
self.interface
|
||||
]
|
||||
)
|
||||
|
||||
|
||||
self.log.info(
|
||||
"Network services restored"
|
||||
)
|
||||
@@ -0,0 +1,229 @@
|
||||
import csv
|
||||
import logging
|
||||
|
||||
|
||||
class OUIImporter:
|
||||
|
||||
|
||||
def __init__(
|
||||
self,
|
||||
resolver,
|
||||
files
|
||||
):
|
||||
|
||||
self.logger = logging.getLogger(
|
||||
"oui-import"
|
||||
)
|
||||
|
||||
self.resolver = resolver
|
||||
|
||||
self.files = files
|
||||
|
||||
|
||||
# =====================================================
|
||||
# Импорт IEEE
|
||||
# =====================================================
|
||||
|
||||
def import_database(self):
|
||||
|
||||
|
||||
count = 0
|
||||
|
||||
skipped = 0
|
||||
|
||||
|
||||
stats = {
|
||||
|
||||
"MA-L": 0,
|
||||
|
||||
"MA-M": 0,
|
||||
|
||||
"MA-S": 0
|
||||
|
||||
}
|
||||
|
||||
|
||||
for filename in self.files:
|
||||
|
||||
|
||||
if not filename.exists():
|
||||
|
||||
self.logger.warning(
|
||||
f"{filename.name} not found"
|
||||
)
|
||||
|
||||
continue
|
||||
|
||||
|
||||
self.logger.info(
|
||||
f"Importing {filename.name}"
|
||||
)
|
||||
|
||||
|
||||
with open(
|
||||
|
||||
filename,
|
||||
|
||||
"r",
|
||||
|
||||
encoding="utf-8",
|
||||
|
||||
errors="ignore"
|
||||
|
||||
) as file:
|
||||
|
||||
|
||||
reader = csv.DictReader(
|
||||
file
|
||||
)
|
||||
|
||||
|
||||
for row in reader:
|
||||
|
||||
|
||||
registry = row.get(
|
||||
"Registry"
|
||||
)
|
||||
|
||||
assignment = row.get(
|
||||
"Assignment"
|
||||
)
|
||||
|
||||
organization = row.get(
|
||||
"Organization Name"
|
||||
)
|
||||
|
||||
|
||||
if not registry:
|
||||
|
||||
continue
|
||||
|
||||
|
||||
if registry not in stats:
|
||||
|
||||
continue
|
||||
|
||||
|
||||
if not assignment:
|
||||
|
||||
skipped += 1
|
||||
|
||||
continue
|
||||
|
||||
|
||||
if not organization:
|
||||
|
||||
skipped += 1
|
||||
|
||||
continue
|
||||
|
||||
|
||||
assignment = (
|
||||
|
||||
assignment
|
||||
|
||||
.replace(
|
||||
"-",
|
||||
""
|
||||
)
|
||||
|
||||
.replace(
|
||||
":",
|
||||
""
|
||||
)
|
||||
|
||||
.replace(
|
||||
".",
|
||||
""
|
||||
)
|
||||
|
||||
.strip()
|
||||
|
||||
.upper()
|
||||
|
||||
)
|
||||
|
||||
|
||||
if not all(
|
||||
|
||||
char in "0123456789ABCDEF"
|
||||
|
||||
for char in assignment
|
||||
|
||||
):
|
||||
|
||||
skipped += 1
|
||||
|
||||
continue
|
||||
|
||||
|
||||
if len(
|
||||
assignment
|
||||
) not in (
|
||||
|
||||
6,
|
||||
|
||||
7,
|
||||
|
||||
9
|
||||
|
||||
):
|
||||
|
||||
skipped += 1
|
||||
|
||||
continue
|
||||
|
||||
|
||||
result = self.resolver.add_vendor(
|
||||
|
||||
assignment,
|
||||
|
||||
organization.strip(),
|
||||
|
||||
registry
|
||||
|
||||
)
|
||||
|
||||
|
||||
if result:
|
||||
|
||||
count += 1
|
||||
|
||||
stats[
|
||||
registry
|
||||
] += 1
|
||||
|
||||
else:
|
||||
|
||||
skipped += 1
|
||||
|
||||
|
||||
self.resolver.commit()
|
||||
|
||||
|
||||
total = self.resolver.count()
|
||||
|
||||
|
||||
self.logger.info(
|
||||
f"Imported: {count}"
|
||||
)
|
||||
|
||||
self.logger.info(
|
||||
f"Skipped: {skipped}"
|
||||
)
|
||||
|
||||
self.logger.info(
|
||||
f"Database records: {total}"
|
||||
)
|
||||
|
||||
return {
|
||||
|
||||
"imported": count,
|
||||
|
||||
"skipped": skipped,
|
||||
|
||||
"total": total,
|
||||
|
||||
"stats": stats
|
||||
|
||||
}
|
||||
+1199
File diff suppressed because it is too large
Load Diff
+278
@@ -0,0 +1,278 @@
|
||||
from datetime import datetime, timezone
|
||||
from pathlib import Path
|
||||
|
||||
|
||||
|
||||
class Session:
|
||||
"""
|
||||
Управление текущей сессией захвата.
|
||||
|
||||
Одна сессия содержит:
|
||||
|
||||
- pcapng захват
|
||||
- GPS трек
|
||||
- результаты парсинга
|
||||
- hashcat файлы
|
||||
|
||||
Все данные одной поездки находятся
|
||||
внутри одного каталога.
|
||||
"""
|
||||
|
||||
|
||||
|
||||
def __init__(
|
||||
self,
|
||||
directory
|
||||
):
|
||||
|
||||
|
||||
#
|
||||
# Время запуска
|
||||
#
|
||||
self.start_time = datetime.now(
|
||||
timezone.utc
|
||||
)
|
||||
|
||||
|
||||
|
||||
#
|
||||
# Каталог сессии
|
||||
#
|
||||
name = self.start_time.strftime(
|
||||
"%Y%m%d_%H%M%S"
|
||||
)
|
||||
|
||||
|
||||
self.path = (
|
||||
Path(directory) / name
|
||||
)
|
||||
|
||||
|
||||
self.path.mkdir(
|
||||
parents=True,
|
||||
exist_ok=True
|
||||
)
|
||||
|
||||
|
||||
|
||||
# =====================================================
|
||||
# Основной захват
|
||||
# =====================================================
|
||||
|
||||
|
||||
self.capture_file = (
|
||||
self.path /
|
||||
"capture.pcapng"
|
||||
)
|
||||
|
||||
|
||||
|
||||
# =====================================================
|
||||
# GPS
|
||||
# =====================================================
|
||||
|
||||
|
||||
self.gps_file = (
|
||||
self.path /
|
||||
"gps_track.nmea"
|
||||
)
|
||||
|
||||
|
||||
|
||||
# =====================================================
|
||||
# Результаты hcxpcapngtool
|
||||
# =====================================================
|
||||
|
||||
|
||||
#
|
||||
# Список точек доступа
|
||||
#
|
||||
self.access_points_file = (
|
||||
self.path /
|
||||
"access_points.csv"
|
||||
)
|
||||
|
||||
|
||||
|
||||
#
|
||||
# Hashcat формат
|
||||
#
|
||||
# WPA-PBKDF2-PMKID+EAPOL
|
||||
#
|
||||
self.handshakes_file = (
|
||||
self.path /
|
||||
"handshakes.22000"
|
||||
)
|
||||
|
||||
|
||||
|
||||
#
|
||||
# ESSID список
|
||||
#
|
||||
self.essid_file = (
|
||||
self.path /
|
||||
"essid.txt"
|
||||
)
|
||||
|
||||
|
||||
|
||||
#
|
||||
# Identity список
|
||||
#
|
||||
self.identity_file = (
|
||||
self.path /
|
||||
"identities.txt"
|
||||
)
|
||||
|
||||
|
||||
|
||||
#
|
||||
# Лог работы парсера
|
||||
#
|
||||
self.parser_log = (
|
||||
self.path /
|
||||
"parser.log"
|
||||
)
|
||||
|
||||
|
||||
|
||||
# =====================================================
|
||||
# Статистика текущей сессии
|
||||
# =====================================================
|
||||
|
||||
|
||||
#
|
||||
# Все NMEA сообщения
|
||||
#
|
||||
self.nmea_messages = 0
|
||||
|
||||
|
||||
|
||||
#
|
||||
# Валидные GPS позиции
|
||||
#
|
||||
self.gps_positions = 0
|
||||
|
||||
|
||||
|
||||
#
|
||||
# Последняя координата
|
||||
#
|
||||
self.current_gps = None
|
||||
|
||||
@classmethod
|
||||
def from_existing(
|
||||
cls,
|
||||
path
|
||||
):
|
||||
|
||||
"""
|
||||
Открывает уже существующую
|
||||
сессию из каталога captures.
|
||||
"""
|
||||
|
||||
obj = cls.__new__(cls)
|
||||
|
||||
obj.start_time = datetime.now(
|
||||
timezone.utc
|
||||
)
|
||||
|
||||
obj.path = Path(path)
|
||||
|
||||
obj.capture_file = (
|
||||
obj.path /
|
||||
"capture.pcapng"
|
||||
)
|
||||
|
||||
obj.gps_file = (
|
||||
obj.path /
|
||||
"gps_track.nmea"
|
||||
)
|
||||
|
||||
obj.access_points_file = (
|
||||
obj.path /
|
||||
"access_points.csv"
|
||||
)
|
||||
|
||||
obj.handshakes_file = (
|
||||
obj.path /
|
||||
"handshakes.22000"
|
||||
)
|
||||
|
||||
obj.essid_file = (
|
||||
obj.path /
|
||||
"essid.txt"
|
||||
)
|
||||
|
||||
obj.identity_file = (
|
||||
obj.path /
|
||||
"identities.txt"
|
||||
)
|
||||
|
||||
obj.parser_log = (
|
||||
obj.path /
|
||||
"parser.log"
|
||||
)
|
||||
|
||||
obj.nmea_messages = 0
|
||||
|
||||
obj.gps_positions = 0
|
||||
|
||||
obj.current_gps = None
|
||||
|
||||
return obj
|
||||
|
||||
# =========================================================
|
||||
# Время работы
|
||||
# =========================================================
|
||||
|
||||
|
||||
def elapsed(
|
||||
self
|
||||
):
|
||||
|
||||
|
||||
return int(
|
||||
(
|
||||
datetime.now(
|
||||
timezone.utc
|
||||
)
|
||||
-
|
||||
self.start_time
|
||||
).total_seconds()
|
||||
)
|
||||
|
||||
|
||||
|
||||
# =========================================================
|
||||
# GPS статистика
|
||||
# =========================================================
|
||||
|
||||
|
||||
def add_nmea(self):
|
||||
|
||||
"""
|
||||
Увеличить счетчик
|
||||
полученных NMEA сообщений.
|
||||
"""
|
||||
|
||||
|
||||
self.nmea_messages += 1
|
||||
|
||||
|
||||
|
||||
def update_gps(
|
||||
self,
|
||||
gps
|
||||
):
|
||||
|
||||
"""
|
||||
Обновить последнюю GPS координату.
|
||||
"""
|
||||
|
||||
|
||||
self.current_gps = gps
|
||||
|
||||
|
||||
self.gps_positions += 1
|
||||
|
||||
+77
@@ -0,0 +1,77 @@
|
||||
import logging
|
||||
import subprocess
|
||||
import sys
|
||||
|
||||
|
||||
class SudoChecker:
|
||||
|
||||
|
||||
def __init__(self):
|
||||
|
||||
self.log = logging.getLogger(
|
||||
"sudo"
|
||||
)
|
||||
|
||||
|
||||
def check(self):
|
||||
|
||||
self.log.info(
|
||||
"Checking sudo..."
|
||||
)
|
||||
|
||||
try:
|
||||
result = subprocess.run(
|
||||
[
|
||||
"sudo",
|
||||
"-n",
|
||||
"-v"
|
||||
]
|
||||
)
|
||||
|
||||
if result.returncode != 0:
|
||||
result = subprocess.run(
|
||||
[
|
||||
"sudo",
|
||||
"-v"
|
||||
]
|
||||
)
|
||||
|
||||
except KeyboardInterrupt:
|
||||
|
||||
self.log.error(
|
||||
"Sudo authentication cancelled."
|
||||
)
|
||||
|
||||
raise SystemExit(1)
|
||||
|
||||
if result.returncode != 0:
|
||||
|
||||
self.log.error(
|
||||
"Sudo authentication is not available."
|
||||
)
|
||||
|
||||
raise SystemExit(1)
|
||||
|
||||
self.log.info(
|
||||
"Sudo: OK"
|
||||
)
|
||||
|
||||
|
||||
def refresh(self):
|
||||
|
||||
try:
|
||||
result = subprocess.run(
|
||||
[
|
||||
"sudo",
|
||||
"-n",
|
||||
"-v"
|
||||
],
|
||||
stdout=subprocess.DEVNULL,
|
||||
stderr=subprocess.DEVNULL
|
||||
)
|
||||
|
||||
except Exception:
|
||||
|
||||
return False
|
||||
|
||||
return result.returncode == 0
|
||||
+704
@@ -0,0 +1,704 @@
|
||||
import sqlite3
|
||||
|
||||
from pathlib import Path
|
||||
|
||||
|
||||
class VendorResolver:
|
||||
|
||||
|
||||
def __init__(
|
||||
self,
|
||||
database
|
||||
):
|
||||
|
||||
self.db_path = Path(database)
|
||||
|
||||
|
||||
self.db_path.parent.mkdir(
|
||||
parents=True,
|
||||
exist_ok=True
|
||||
)
|
||||
|
||||
|
||||
self.conn = sqlite3.connect(
|
||||
self.db_path
|
||||
)
|
||||
|
||||
|
||||
self.create_tables()
|
||||
|
||||
|
||||
|
||||
# =====================================================
|
||||
# Создание структуры
|
||||
# =====================================================
|
||||
|
||||
def create_tables(self):
|
||||
|
||||
|
||||
self.conn.execute(
|
||||
"""
|
||||
CREATE TABLE IF NOT EXISTS oui
|
||||
(
|
||||
|
||||
prefix TEXT PRIMARY KEY,
|
||||
|
||||
vendor TEXT NOT NULL,
|
||||
|
||||
confidence TEXT NOT NULL,
|
||||
|
||||
prefix_length INTEGER NOT NULL
|
||||
|
||||
)
|
||||
"""
|
||||
)
|
||||
|
||||
self.conn.execute(
|
||||
"""
|
||||
CREATE TABLE IF NOT EXISTS metadata
|
||||
(
|
||||
|
||||
key TEXT PRIMARY KEY,
|
||||
|
||||
value TEXT NOT NULL
|
||||
|
||||
)
|
||||
"""
|
||||
)
|
||||
|
||||
self.conn.execute(
|
||||
"""
|
||||
CREATE TABLE IF NOT EXISTS metadata
|
||||
(
|
||||
|
||||
key TEXT PRIMARY KEY,
|
||||
|
||||
value TEXT
|
||||
|
||||
)
|
||||
"""
|
||||
)
|
||||
|
||||
self.conn.execute(
|
||||
"""
|
||||
CREATE INDEX IF NOT EXISTS idx_prefix
|
||||
|
||||
ON oui(prefix)
|
||||
"""
|
||||
)
|
||||
|
||||
self.conn.execute(
|
||||
"""
|
||||
CREATE TABLE IF NOT EXISTS metadata
|
||||
(
|
||||
|
||||
key TEXT PRIMARY KEY,
|
||||
|
||||
value TEXT
|
||||
|
||||
)
|
||||
"""
|
||||
)
|
||||
|
||||
self.conn.commit()
|
||||
|
||||
|
||||
# =====================================================
|
||||
# Определение производителя
|
||||
# =====================================================
|
||||
|
||||
def lookup(
|
||||
self,
|
||||
mac
|
||||
):
|
||||
|
||||
if not mac:
|
||||
|
||||
return None
|
||||
|
||||
|
||||
mac = self.normalize(
|
||||
mac
|
||||
)
|
||||
|
||||
|
||||
for length in (
|
||||
9,
|
||||
7,
|
||||
6
|
||||
):
|
||||
|
||||
prefix = mac[:length]
|
||||
|
||||
|
||||
cursor = self.conn.execute(
|
||||
"""
|
||||
SELECT vendor
|
||||
|
||||
FROM oui
|
||||
|
||||
WHERE prefix=?
|
||||
|
||||
""",
|
||||
(
|
||||
prefix,
|
||||
)
|
||||
)
|
||||
|
||||
|
||||
row = cursor.fetchone()
|
||||
|
||||
|
||||
if row:
|
||||
|
||||
return row[0]
|
||||
|
||||
|
||||
return "Unknown"
|
||||
|
||||
|
||||
# =====================================================
|
||||
# Добавление производителя
|
||||
# =====================================================
|
||||
|
||||
def add_vendor(
|
||||
self,
|
||||
prefix,
|
||||
vendor,
|
||||
confidence="IEEE"
|
||||
):
|
||||
|
||||
prefix = self.normalize(prefix)
|
||||
|
||||
|
||||
if not prefix:
|
||||
|
||||
return False
|
||||
|
||||
|
||||
prefix_length = len(prefix)
|
||||
|
||||
|
||||
if prefix_length not in (6,7,9):
|
||||
|
||||
return False
|
||||
|
||||
|
||||
|
||||
self.conn.execute(
|
||||
"""
|
||||
INSERT OR REPLACE INTO oui
|
||||
(
|
||||
prefix,
|
||||
vendor,
|
||||
confidence,
|
||||
prefix_length
|
||||
)
|
||||
|
||||
VALUES (?,?,?,?)
|
||||
|
||||
""",
|
||||
|
||||
(
|
||||
prefix,
|
||||
vendor,
|
||||
confidence,
|
||||
prefix_length
|
||||
)
|
||||
)
|
||||
|
||||
return True
|
||||
|
||||
|
||||
|
||||
# =====================================================
|
||||
# Сохранение изменений
|
||||
# =====================================================
|
||||
|
||||
def commit(self):
|
||||
|
||||
self.conn.commit()
|
||||
|
||||
|
||||
# =====================================================
|
||||
# Количество записей
|
||||
# =====================================================
|
||||
|
||||
def count(self):
|
||||
|
||||
cursor = self.conn.execute(
|
||||
"SELECT COUNT(*) FROM oui"
|
||||
)
|
||||
|
||||
return cursor.fetchone()[0]
|
||||
|
||||
# =====================================================
|
||||
# Metadata
|
||||
# =====================================================
|
||||
|
||||
def get_metadata(
|
||||
self,
|
||||
key,
|
||||
default=None
|
||||
):
|
||||
|
||||
cursor = self.conn.execute(
|
||||
|
||||
"""
|
||||
SELECT value
|
||||
|
||||
FROM metadata
|
||||
|
||||
WHERE key=?
|
||||
|
||||
""",
|
||||
|
||||
(
|
||||
key,
|
||||
)
|
||||
|
||||
)
|
||||
|
||||
|
||||
row = cursor.fetchone()
|
||||
|
||||
|
||||
if row:
|
||||
|
||||
return row[0]
|
||||
|
||||
|
||||
return default
|
||||
|
||||
|
||||
|
||||
def set_metadata(
|
||||
self,
|
||||
key,
|
||||
value
|
||||
):
|
||||
|
||||
self.conn.execute(
|
||||
|
||||
"""
|
||||
INSERT OR REPLACE INTO metadata
|
||||
(
|
||||
key,
|
||||
value
|
||||
)
|
||||
|
||||
VALUES (?,?)
|
||||
|
||||
""",
|
||||
|
||||
(
|
||||
key,
|
||||
str(value)
|
||||
)
|
||||
|
||||
)
|
||||
|
||||
# =====================================================
|
||||
# Получить значение metadata
|
||||
# =====================================================
|
||||
|
||||
def get_metadata(
|
||||
self,
|
||||
key
|
||||
):
|
||||
|
||||
cursor = self.conn.execute(
|
||||
"""
|
||||
SELECT value
|
||||
|
||||
FROM metadata
|
||||
|
||||
WHERE key=?
|
||||
|
||||
""",
|
||||
(
|
||||
key,
|
||||
)
|
||||
)
|
||||
|
||||
row = cursor.fetchone()
|
||||
|
||||
if row:
|
||||
|
||||
return row[0]
|
||||
|
||||
return None
|
||||
|
||||
# =====================================================
|
||||
# Сохранение metadata
|
||||
# =====================================================
|
||||
|
||||
def set_metadata(
|
||||
self,
|
||||
key,
|
||||
value
|
||||
):
|
||||
|
||||
self.conn.execute(
|
||||
"""
|
||||
INSERT OR REPLACE INTO metadata
|
||||
(
|
||||
key,
|
||||
value
|
||||
)
|
||||
|
||||
VALUES (?,?)
|
||||
""",
|
||||
(
|
||||
key,
|
||||
str(value)
|
||||
)
|
||||
)
|
||||
|
||||
# =====================================================
|
||||
# Записать значение metadata
|
||||
# =====================================================
|
||||
|
||||
def set_metadata(
|
||||
self,
|
||||
key,
|
||||
value
|
||||
):
|
||||
|
||||
self.conn.execute(
|
||||
"""
|
||||
INSERT OR REPLACE INTO metadata
|
||||
(
|
||||
key,
|
||||
value
|
||||
)
|
||||
|
||||
VALUES
|
||||
(
|
||||
?,
|
||||
?
|
||||
)
|
||||
""",
|
||||
(
|
||||
key,
|
||||
str(value)
|
||||
)
|
||||
)
|
||||
|
||||
# =====================================================
|
||||
# Удаление metadata
|
||||
# =====================================================
|
||||
|
||||
def delete_metadata(
|
||||
self,
|
||||
key
|
||||
):
|
||||
|
||||
self.conn.execute(
|
||||
"""
|
||||
DELETE
|
||||
|
||||
FROM metadata
|
||||
|
||||
WHERE key=?
|
||||
""",
|
||||
(
|
||||
key,
|
||||
)
|
||||
)
|
||||
|
||||
# =====================================================
|
||||
# Есть ли база производителей
|
||||
# =====================================================
|
||||
|
||||
def has_database(self):
|
||||
|
||||
cursor = self.conn.execute(
|
||||
"""
|
||||
SELECT COUNT(*)
|
||||
|
||||
FROM oui
|
||||
"""
|
||||
)
|
||||
|
||||
return cursor.fetchone()[0] > 0
|
||||
|
||||
|
||||
# =====================================================
|
||||
# Требуется обновление
|
||||
# =====================================================
|
||||
|
||||
def update_available(self):
|
||||
|
||||
value = self.get_metadata(
|
||||
"update_available"
|
||||
)
|
||||
|
||||
return value == "1"
|
||||
|
||||
# =====================================================
|
||||
# Получение параметра metadata
|
||||
# =====================================================
|
||||
|
||||
def get_metadata(
|
||||
|
||||
self,
|
||||
|
||||
key
|
||||
|
||||
):
|
||||
|
||||
|
||||
cursor = self.conn.execute(
|
||||
|
||||
"""
|
||||
SELECT value
|
||||
|
||||
FROM metadata
|
||||
|
||||
WHERE key=?
|
||||
|
||||
""",
|
||||
|
||||
(
|
||||
key,
|
||||
)
|
||||
|
||||
)
|
||||
|
||||
|
||||
row = cursor.fetchone()
|
||||
|
||||
|
||||
if row:
|
||||
|
||||
return row[0]
|
||||
|
||||
|
||||
return None
|
||||
|
||||
|
||||
|
||||
# =====================================================
|
||||
# Запись параметра metadata
|
||||
# =====================================================
|
||||
|
||||
def set_metadata(
|
||||
|
||||
self,
|
||||
|
||||
key,
|
||||
|
||||
value
|
||||
|
||||
):
|
||||
|
||||
|
||||
self.conn.execute(
|
||||
|
||||
"""
|
||||
INSERT OR REPLACE INTO metadata
|
||||
|
||||
(
|
||||
|
||||
key,
|
||||
|
||||
value
|
||||
|
||||
)
|
||||
|
||||
VALUES
|
||||
|
||||
(
|
||||
|
||||
?,
|
||||
|
||||
?
|
||||
|
||||
)
|
||||
|
||||
""",
|
||||
|
||||
(
|
||||
|
||||
key,
|
||||
|
||||
str(value)
|
||||
|
||||
)
|
||||
|
||||
)
|
||||
|
||||
|
||||
|
||||
# =====================================================
|
||||
# Получение всех параметров metadata
|
||||
# =====================================================
|
||||
|
||||
def get_all_metadata(
|
||||
|
||||
self
|
||||
|
||||
):
|
||||
|
||||
|
||||
cursor = self.conn.execute(
|
||||
|
||||
"""
|
||||
SELECT
|
||||
|
||||
key,
|
||||
|
||||
value
|
||||
|
||||
FROM metadata
|
||||
|
||||
"""
|
||||
)
|
||||
|
||||
|
||||
result = {}
|
||||
|
||||
|
||||
for row in cursor.fetchall():
|
||||
|
||||
result[
|
||||
row[0]
|
||||
] = row[1]
|
||||
|
||||
|
||||
return result
|
||||
|
||||
|
||||
|
||||
# =====================================================
|
||||
# Удаление параметра metadata
|
||||
# =====================================================
|
||||
|
||||
def delete_metadata(
|
||||
|
||||
self,
|
||||
|
||||
key
|
||||
|
||||
):
|
||||
|
||||
|
||||
self.conn.execute(
|
||||
|
||||
"""
|
||||
DELETE
|
||||
|
||||
FROM metadata
|
||||
|
||||
WHERE key=?
|
||||
|
||||
""",
|
||||
|
||||
(
|
||||
|
||||
key,
|
||||
|
||||
)
|
||||
|
||||
)
|
||||
|
||||
# =====================================================
|
||||
# Проверка metadata
|
||||
# =====================================================
|
||||
|
||||
def has_metadata(
|
||||
self,
|
||||
key
|
||||
):
|
||||
|
||||
cursor = self.conn.execute(
|
||||
"""
|
||||
SELECT 1
|
||||
|
||||
FROM metadata
|
||||
|
||||
WHERE key=?
|
||||
|
||||
LIMIT 1
|
||||
""",
|
||||
(
|
||||
key,
|
||||
)
|
||||
)
|
||||
|
||||
return cursor.fetchone() is not None
|
||||
|
||||
# =====================================================
|
||||
# Приведение MAC
|
||||
# =====================================================
|
||||
|
||||
def normalize(
|
||||
self,
|
||||
mac
|
||||
):
|
||||
|
||||
if not mac:
|
||||
|
||||
return None
|
||||
|
||||
|
||||
mac = mac.replace(
|
||||
":",
|
||||
""
|
||||
)
|
||||
|
||||
mac = mac.replace(
|
||||
"-",
|
||||
""
|
||||
)
|
||||
|
||||
mac = mac.replace(
|
||||
".",
|
||||
""
|
||||
)
|
||||
|
||||
|
||||
mac = mac.upper()
|
||||
|
||||
|
||||
return mac
|
||||
|
||||
# =====================================================
|
||||
# Получение metadata
|
||||
# =====================================================
|
||||
|
||||
def get_metadata(
|
||||
self,
|
||||
key,
|
||||
default=None
|
||||
):
|
||||
|
||||
cursor = self.conn.execute(
|
||||
"""
|
||||
SELECT value
|
||||
|
||||
FROM metadata
|
||||
|
||||
WHERE key=?
|
||||
""",
|
||||
(
|
||||
key,
|
||||
)
|
||||
)
|
||||
|
||||
row = cursor.fetchone()
|
||||
|
||||
if row:
|
||||
|
||||
return row[0]
|
||||
|
||||
return default
|
||||
|
||||
# =====================================================
|
||||
# Закрытие
|
||||
# =====================================================
|
||||
|
||||
def close(self):
|
||||
|
||||
self.conn.close()
|
||||
@@ -0,0 +1,314 @@
|
||||
import logging
|
||||
import urllib.request
|
||||
import datetime
|
||||
import time
|
||||
|
||||
from pathlib import Path
|
||||
|
||||
from vendor import VendorResolver
|
||||
from oui_import import OUIImporter
|
||||
|
||||
|
||||
PROJECT_ROOT = (
|
||||
Path(__file__).resolve().parent.parent
|
||||
)
|
||||
|
||||
|
||||
DATABASE_DIR = (
|
||||
PROJECT_ROOT
|
||||
/
|
||||
"database"
|
||||
)
|
||||
|
||||
|
||||
OUI_DATABASE = (
|
||||
DATABASE_DIR
|
||||
/
|
||||
"oui.sqlite"
|
||||
)
|
||||
|
||||
|
||||
HTTP_HEADERS = {
|
||||
|
||||
"User-Agent":
|
||||
|
||||
"Mozilla/5.0 (X11; Linux x86_64) "
|
||||
|
||||
"AppleWebKit/537.36 "
|
||||
|
||||
"(KHTML, like Gecko) "
|
||||
|
||||
"Chrome/138.0 Safari/537.36"
|
||||
|
||||
}
|
||||
|
||||
|
||||
DOWNLOAD_RETRIES = 3
|
||||
|
||||
DOWNLOAD_TIMEOUT = 60
|
||||
|
||||
CSV_FILES = {
|
||||
|
||||
"oui.csv": "oui",
|
||||
|
||||
"mam.csv": "mam",
|
||||
|
||||
"oui36.csv": "oui36",
|
||||
|
||||
}
|
||||
|
||||
|
||||
class VendorImporter:
|
||||
|
||||
|
||||
def __init__(
|
||||
self,
|
||||
config
|
||||
):
|
||||
|
||||
self.config = config
|
||||
|
||||
self.log = logging.getLogger(
|
||||
"vendor_import"
|
||||
)
|
||||
|
||||
DATABASE_DIR.mkdir(
|
||||
parents=True,
|
||||
exist_ok=True
|
||||
)
|
||||
|
||||
# ---------------------------------------------------------
|
||||
# Загрузка IEEE CSV
|
||||
# ---------------------------------------------------------
|
||||
|
||||
def download_csv_files(self):
|
||||
|
||||
for filename, key in CSV_FILES.items():
|
||||
|
||||
url = self.config.vendor_sources[key]
|
||||
|
||||
destination = (
|
||||
DATABASE_DIR
|
||||
/
|
||||
filename
|
||||
)
|
||||
|
||||
success = False
|
||||
|
||||
for attempt in range(
|
||||
1,
|
||||
DOWNLOAD_RETRIES + 1
|
||||
):
|
||||
|
||||
self.log.info(
|
||||
|
||||
f"Downloading {filename} "
|
||||
|
||||
f"(attempt {attempt}/{DOWNLOAD_RETRIES})"
|
||||
|
||||
)
|
||||
|
||||
try:
|
||||
|
||||
request = urllib.request.Request(
|
||||
url,
|
||||
headers=HTTP_HEADERS
|
||||
)
|
||||
|
||||
with urllib.request.urlopen(
|
||||
request,
|
||||
timeout=DOWNLOAD_TIMEOUT
|
||||
) as response:
|
||||
|
||||
if response.status != 200:
|
||||
|
||||
raise RuntimeError(
|
||||
f"HTTP {response.status}"
|
||||
)
|
||||
|
||||
data = response.read()
|
||||
|
||||
if len(data) < 1000:
|
||||
|
||||
raise RuntimeError(
|
||||
"Downloaded file is too small"
|
||||
)
|
||||
|
||||
text = data.decode(
|
||||
"utf-8",
|
||||
errors="ignore"
|
||||
)
|
||||
|
||||
if "Assignment" not in text:
|
||||
|
||||
raise RuntimeError(
|
||||
"Invalid IEEE CSV"
|
||||
)
|
||||
|
||||
destination.write_bytes(
|
||||
data
|
||||
)
|
||||
|
||||
size = (
|
||||
destination.stat().st_size
|
||||
/ 1024
|
||||
/ 1024
|
||||
)
|
||||
|
||||
self.log.info(
|
||||
|
||||
f"{filename} downloaded "
|
||||
|
||||
f"({size:.2f} MB)"
|
||||
|
||||
)
|
||||
|
||||
success = True
|
||||
|
||||
break
|
||||
|
||||
except KeyboardInterrupt:
|
||||
|
||||
self.log.info(
|
||||
"CSV download cancelled"
|
||||
)
|
||||
|
||||
raise
|
||||
|
||||
except Exception as error:
|
||||
|
||||
self.log.warning(
|
||||
f"{filename}: {error}"
|
||||
)
|
||||
|
||||
if destination.exists():
|
||||
|
||||
destination.unlink()
|
||||
|
||||
if attempt < DOWNLOAD_RETRIES:
|
||||
|
||||
time.sleep(2)
|
||||
|
||||
if not success:
|
||||
|
||||
raise RuntimeError(
|
||||
f"Unable to download {filename}"
|
||||
)
|
||||
|
||||
# ---------------------------------------------------------
|
||||
# Полное создание IEEE базы
|
||||
# ---------------------------------------------------------
|
||||
|
||||
def bootstrap(self):
|
||||
|
||||
OUI_DATABASE.unlink(
|
||||
missing_ok=True
|
||||
)
|
||||
|
||||
self.download_csv_files()
|
||||
|
||||
resolver = VendorResolver(
|
||||
OUI_DATABASE
|
||||
)
|
||||
|
||||
importer = OUIImporter(
|
||||
|
||||
resolver,
|
||||
|
||||
[
|
||||
DATABASE_DIR
|
||||
/
|
||||
filename
|
||||
|
||||
for filename
|
||||
|
||||
in CSV_FILES
|
||||
]
|
||||
|
||||
)
|
||||
|
||||
result = importer.import_database()
|
||||
|
||||
total = result["total"]
|
||||
|
||||
stats = result["stats"]
|
||||
|
||||
if (
|
||||
|
||||
stats["MA-L"] < 35000
|
||||
|
||||
or
|
||||
|
||||
stats["MA-M"] < 5000
|
||||
|
||||
or
|
||||
|
||||
stats["MA-S"] < 5000
|
||||
|
||||
):
|
||||
|
||||
resolver.close()
|
||||
|
||||
OUI_DATABASE.unlink(
|
||||
missing_ok=True
|
||||
)
|
||||
|
||||
raise RuntimeError(
|
||||
|
||||
"IEEE database verification failed.\n\n"
|
||||
|
||||
f"MA-L: {stats['MA-L']}\n"
|
||||
|
||||
f"MA-M: {stats['MA-M']}\n"
|
||||
|
||||
f"MA-S: {stats['MA-S']}"
|
||||
|
||||
)
|
||||
|
||||
resolver.set_metadata(
|
||||
|
||||
"last_import",
|
||||
datetime.datetime.now(
|
||||
datetime.timezone.utc
|
||||
).isoformat().replace(
|
||||
"+00:00",
|
||||
"Z"
|
||||
)
|
||||
|
||||
)
|
||||
|
||||
resolver.set_metadata(
|
||||
|
||||
"records",
|
||||
|
||||
total
|
||||
|
||||
)
|
||||
|
||||
resolver.set_metadata(
|
||||
|
||||
"schema_version",
|
||||
|
||||
1
|
||||
|
||||
)
|
||||
|
||||
resolver.set_metadata(
|
||||
|
||||
"import_status",
|
||||
|
||||
"ok"
|
||||
|
||||
)
|
||||
|
||||
resolver.commit()
|
||||
|
||||
resolver.close()
|
||||
|
||||
self.log.info(
|
||||
|
||||
"IEEE database created: "
|
||||
|
||||
f"{total} records"
|
||||
|
||||
)
|
||||
File diff suppressed because it is too large
Load Diff
@@ -0,0 +1,373 @@
|
||||
import logging
|
||||
import urllib.request
|
||||
|
||||
from pathlib import Path
|
||||
|
||||
from vendor import VendorResolver
|
||||
from vendor_import import (
|
||||
VendorImporter,
|
||||
CSV_FILES
|
||||
)
|
||||
|
||||
|
||||
logger = logging.getLogger(
|
||||
"vendor-update"
|
||||
)
|
||||
|
||||
|
||||
class VendorUpdater:
|
||||
|
||||
|
||||
def __init__(
|
||||
self,
|
||||
cfg
|
||||
):
|
||||
|
||||
self.cfg = cfg
|
||||
|
||||
|
||||
self.project_root = (
|
||||
|
||||
Path(__file__)
|
||||
|
||||
.resolve()
|
||||
|
||||
.parent
|
||||
|
||||
.parent
|
||||
|
||||
)
|
||||
|
||||
|
||||
self.database = (
|
||||
|
||||
self.project_root
|
||||
|
||||
/ "database"
|
||||
|
||||
/ "oui.sqlite"
|
||||
|
||||
)
|
||||
|
||||
|
||||
self.csv_files = [
|
||||
|
||||
self.project_root
|
||||
/ "database"
|
||||
/ filename
|
||||
|
||||
for filename
|
||||
|
||||
in CSV_FILES
|
||||
|
||||
]
|
||||
|
||||
# =====================================================
|
||||
# Проверка CSV
|
||||
# =====================================================
|
||||
|
||||
def csv_exists(
|
||||
self
|
||||
):
|
||||
|
||||
for file in self.csv_files:
|
||||
|
||||
if not file.exists():
|
||||
|
||||
return False
|
||||
|
||||
return True
|
||||
|
||||
# =====================================================
|
||||
# Проверка базы
|
||||
# =====================================================
|
||||
|
||||
def database_exists(
|
||||
self
|
||||
):
|
||||
|
||||
return self.database.exists()
|
||||
|
||||
# =====================================================
|
||||
# Проверка metadata
|
||||
# =====================================================
|
||||
|
||||
def metadata_exists(
|
||||
self
|
||||
):
|
||||
|
||||
resolver = VendorResolver(
|
||||
self.database
|
||||
)
|
||||
|
||||
|
||||
result = resolver.has_metadata(
|
||||
"last_import"
|
||||
)
|
||||
|
||||
|
||||
resolver.close()
|
||||
|
||||
return result
|
||||
|
||||
# =====================================================
|
||||
# Создание базы IEEE
|
||||
# =====================================================
|
||||
|
||||
def create_database(
|
||||
self
|
||||
):
|
||||
|
||||
logger.info(
|
||||
"Creating IEEE OUI database..."
|
||||
)
|
||||
|
||||
|
||||
importer = VendorImporter(
|
||||
|
||||
self.cfg
|
||||
|
||||
)
|
||||
|
||||
|
||||
importer.import_database()
|
||||
|
||||
|
||||
logger.info(
|
||||
"IEEE database created"
|
||||
)
|
||||
|
||||
# =====================================================
|
||||
# Проверка IEEE базы
|
||||
# =====================================================
|
||||
|
||||
def check(
|
||||
self
|
||||
):
|
||||
|
||||
logger.info(
|
||||
"Checking IEEE vendor database..."
|
||||
)
|
||||
|
||||
|
||||
#
|
||||
# База уже существует
|
||||
#
|
||||
|
||||
if self.database_exists():
|
||||
|
||||
if self.database.stat().st_size < 10000:
|
||||
|
||||
logger.warning(
|
||||
"IEEE database corrupted"
|
||||
)
|
||||
|
||||
self.database.unlink()
|
||||
|
||||
self.check()
|
||||
|
||||
return
|
||||
|
||||
logger.info(
|
||||
"IEEE database found"
|
||||
)
|
||||
|
||||
|
||||
if self.metadata_exists():
|
||||
|
||||
logger.info(
|
||||
"IEEE metadata found"
|
||||
)
|
||||
|
||||
return
|
||||
|
||||
|
||||
logger.warning(
|
||||
"IEEE metadata missing"
|
||||
)
|
||||
|
||||
|
||||
resolver = VendorResolver(
|
||||
self.database
|
||||
)
|
||||
|
||||
if resolver.count() == 0:
|
||||
|
||||
resolver.close()
|
||||
|
||||
logger.warning(
|
||||
"IEEE database is empty"
|
||||
)
|
||||
|
||||
self.database.unlink()
|
||||
|
||||
self.check()
|
||||
|
||||
return
|
||||
|
||||
resolver.set_metadata(
|
||||
"last_import",
|
||||
"unknown"
|
||||
)
|
||||
|
||||
|
||||
resolver.commit()
|
||||
|
||||
resolver.close()
|
||||
|
||||
|
||||
logger.info(
|
||||
"IEEE metadata restored"
|
||||
)
|
||||
|
||||
return
|
||||
|
||||
|
||||
#
|
||||
# Базы нет
|
||||
#
|
||||
|
||||
logger.warning(
|
||||
"IEEE database not found"
|
||||
)
|
||||
|
||||
|
||||
#
|
||||
# Проверяем CSV
|
||||
#
|
||||
|
||||
if not self.csv_exists():
|
||||
|
||||
logger.warning(
|
||||
"IEEE CSV files not found"
|
||||
)
|
||||
|
||||
self.download_csv()
|
||||
|
||||
|
||||
logger.info(
|
||||
"IEEE CSV files found"
|
||||
)
|
||||
|
||||
|
||||
#
|
||||
# Создаем базу
|
||||
#
|
||||
|
||||
self.create_database()
|
||||
|
||||
# =====================================================
|
||||
# Загрузка IEEE CSV
|
||||
# =====================================================
|
||||
|
||||
def download_csv(
|
||||
self
|
||||
):
|
||||
|
||||
|
||||
logger.info(
|
||||
"Downloading IEEE CSV files..."
|
||||
)
|
||||
|
||||
self.database.parent.mkdir(
|
||||
|
||||
parents=True,
|
||||
|
||||
exist_ok=True
|
||||
|
||||
)
|
||||
|
||||
downloads = [
|
||||
|
||||
(
|
||||
self.cfg.vendor_sources[key],
|
||||
|
||||
self.project_root
|
||||
/
|
||||
"database"
|
||||
/
|
||||
filename
|
||||
)
|
||||
|
||||
for filename, key
|
||||
|
||||
in CSV_FILES.items()
|
||||
|
||||
]
|
||||
|
||||
|
||||
for url, filename in downloads:
|
||||
|
||||
|
||||
logger.info(
|
||||
f"Downloading {filename.name}"
|
||||
)
|
||||
|
||||
|
||||
try:
|
||||
|
||||
urllib.request.urlretrieve(
|
||||
|
||||
url,
|
||||
|
||||
filename
|
||||
|
||||
)
|
||||
|
||||
except Exception as error:
|
||||
|
||||
logger.error(
|
||||
|
||||
f"Download failed: {filename.name}"
|
||||
|
||||
)
|
||||
|
||||
raise RuntimeError(
|
||||
|
||||
str(error)
|
||||
|
||||
)
|
||||
|
||||
|
||||
if not filename.exists():
|
||||
|
||||
raise RuntimeError(
|
||||
|
||||
f"{filename.name} download failed"
|
||||
|
||||
)
|
||||
|
||||
|
||||
if filename.stat().st_size < 1000:
|
||||
|
||||
raise RuntimeError(
|
||||
|
||||
f"{filename.name} is too small"
|
||||
|
||||
)
|
||||
|
||||
|
||||
size = (
|
||||
|
||||
filename.stat().st_size
|
||||
|
||||
/ 1024
|
||||
|
||||
/ 1024
|
||||
|
||||
)
|
||||
|
||||
|
||||
logger.info(
|
||||
|
||||
f"{filename.name} downloaded "
|
||||
|
||||
f"({size:.2f} MB)"
|
||||
|
||||
)
|
||||
|
||||
|
||||
logger.info(
|
||||
"IEEE CSV download finished"
|
||||
)
|
||||
|
||||
+194
@@ -0,0 +1,194 @@
|
||||
import logging
|
||||
import subprocess
|
||||
import signal
|
||||
import shlex
|
||||
|
||||
|
||||
class WiFiManager:
|
||||
|
||||
|
||||
def __init__(
|
||||
self,
|
||||
config,
|
||||
session,
|
||||
interface
|
||||
):
|
||||
|
||||
self.config = config
|
||||
|
||||
self.session = session
|
||||
|
||||
self.interface = interface
|
||||
|
||||
self.process = None
|
||||
|
||||
self.log = logging.getLogger(
|
||||
"wifi"
|
||||
)
|
||||
|
||||
|
||||
cmd = [
|
||||
"sudo",
|
||||
"-n",
|
||||
str(self.config.hcxdumptool),
|
||||
"-i",
|
||||
self.interface,
|
||||
"-w",
|
||||
str(self.session.capture_file),
|
||||
]
|
||||
|
||||
|
||||
|
||||
#
|
||||
# Каналы WiFi
|
||||
#
|
||||
# Каналы собираются отдельно для каждого
|
||||
# включённого диапазона.
|
||||
#
|
||||
# a - диапазон 2.4 GHz
|
||||
# b - диапазон 5 GHz
|
||||
# c - диапазон 6 GHz
|
||||
#
|
||||
|
||||
channels = []
|
||||
|
||||
|
||||
if self.config.wifi_enable_2_4ghz:
|
||||
|
||||
if self.config.wifi_channels_2_4ghz:
|
||||
|
||||
channels.append(
|
||||
self.config.wifi_channels_2_4ghz
|
||||
)
|
||||
|
||||
|
||||
if self.config.wifi_enable_5ghz:
|
||||
|
||||
if self.config.wifi_channels_5ghz:
|
||||
|
||||
channels.append(
|
||||
self.config.wifi_channels_5ghz
|
||||
)
|
||||
|
||||
|
||||
if self.config.wifi_enable_6ghz:
|
||||
|
||||
if self.config.wifi_channels_6ghz:
|
||||
|
||||
channels.append(
|
||||
self.config.wifi_channels_6ghz
|
||||
)
|
||||
|
||||
|
||||
if channels:
|
||||
|
||||
cmd.extend(
|
||||
[
|
||||
"-c",
|
||||
",".join(channels)
|
||||
]
|
||||
)
|
||||
|
||||
|
||||
|
||||
#
|
||||
# Дополнительные параметры
|
||||
#
|
||||
# Берутся из config.yaml
|
||||
#
|
||||
# Позволяют добавлять новые ключи
|
||||
# без изменения программы
|
||||
#
|
||||
|
||||
if self.config.wifi_extra_args:
|
||||
|
||||
|
||||
cmd.extend(
|
||||
shlex.split(
|
||||
self.config.wifi_extra_args
|
||||
)
|
||||
)
|
||||
|
||||
|
||||
|
||||
self.cmd = cmd
|
||||
|
||||
|
||||
def start(self):
|
||||
|
||||
if self.process is not None:
|
||||
|
||||
return
|
||||
|
||||
self.log.info(
|
||||
"Starting hcxdumptool"
|
||||
)
|
||||
|
||||
self.log.debug(
|
||||
"Command: %s",
|
||||
" ".join(self.cmd)
|
||||
)
|
||||
|
||||
self.process = subprocess.Popen(
|
||||
self.cmd
|
||||
)
|
||||
|
||||
self.log.info(
|
||||
"hcxdumptool started, pid=%s",
|
||||
self.process.pid
|
||||
)
|
||||
|
||||
|
||||
def stop(self):
|
||||
|
||||
|
||||
if not self.process:
|
||||
|
||||
return
|
||||
|
||||
|
||||
|
||||
self.log.info(
|
||||
"Stopping hcxdumptool"
|
||||
)
|
||||
|
||||
|
||||
|
||||
self.process.send_signal(
|
||||
signal.SIGTERM
|
||||
)
|
||||
|
||||
|
||||
|
||||
try:
|
||||
|
||||
self.process.wait(
|
||||
timeout=10
|
||||
)
|
||||
|
||||
|
||||
self.log.info(
|
||||
|
||||
"hcxdumptool stopped with code %s",
|
||||
|
||||
self.process.returncode
|
||||
|
||||
)
|
||||
|
||||
|
||||
except subprocess.TimeoutExpired:
|
||||
|
||||
|
||||
self.log.warning(
|
||||
"hcxdumptool did not stop, killing..."
|
||||
)
|
||||
|
||||
|
||||
self.process.kill()
|
||||
|
||||
self.process.wait(
|
||||
timeout=5
|
||||
)
|
||||
|
||||
|
||||
self.process = None
|
||||
@@ -0,0 +1,94 @@
|
||||
from pathlib import Path
|
||||
|
||||
|
||||
class WiFiInterfaceDetector:
|
||||
|
||||
|
||||
def detect(self):
|
||||
|
||||
interfaces = []
|
||||
|
||||
network_directory = Path(
|
||||
"/sys/class/net"
|
||||
)
|
||||
|
||||
|
||||
for interface in sorted(
|
||||
network_directory.iterdir()
|
||||
):
|
||||
|
||||
wireless_directory = (
|
||||
interface
|
||||
/
|
||||
"wireless"
|
||||
)
|
||||
|
||||
if wireless_directory.exists():
|
||||
|
||||
interfaces.append(
|
||||
interface.name
|
||||
)
|
||||
|
||||
|
||||
if not interfaces:
|
||||
|
||||
raise RuntimeError(
|
||||
"No WiFi interfaces found."
|
||||
)
|
||||
|
||||
|
||||
if len(interfaces) == 1:
|
||||
|
||||
return interfaces[0]
|
||||
|
||||
|
||||
print()
|
||||
|
||||
print(
|
||||
"Available WiFi interfaces:"
|
||||
)
|
||||
|
||||
print()
|
||||
|
||||
|
||||
for index, interface in enumerate(
|
||||
interfaces,
|
||||
start=1
|
||||
):
|
||||
|
||||
print(
|
||||
f"{index}. {interface}"
|
||||
)
|
||||
|
||||
|
||||
print()
|
||||
|
||||
|
||||
while True:
|
||||
|
||||
answer = input(
|
||||
"Select interface: "
|
||||
)
|
||||
|
||||
try:
|
||||
|
||||
number = int(
|
||||
answer
|
||||
)
|
||||
|
||||
except ValueError:
|
||||
|
||||
continue
|
||||
|
||||
|
||||
if (
|
||||
1
|
||||
<=
|
||||
number
|
||||
<=
|
||||
len(interfaces)
|
||||
):
|
||||
|
||||
return interfaces[
|
||||
number - 1
|
||||
]
|
||||
+2732
File diff suppressed because it is too large
Load Diff
Reference in New Issue
Block a user