/data and /tmp standarization

This commit is contained in:
Adam Outler
2025-11-04 22:26:35 +00:00
parent 90a07c61eb
commit 5b871865db
250 changed files with 7462 additions and 4940 deletions

View File

@@ -15,9 +15,22 @@
<?php
require 'php/templates/header.php';
// check permissions
$dbPath = "../db/app.db";
$confPath = "../config/app.conf";
// Use environment-aware paths with fallback to legacy locations
$dbFolderPath = rtrim(getenv('NETALERTX_DB') ?: '/data/db', '/');
$configFolderPath = rtrim(getenv('NETALERTX_CONFIG') ?: '/data/config', '/');
$dbPath = $dbFolderPath . '/app.db';
$confPath = $configFolderPath . '/app.conf';
// Fallback to legacy paths if new locations don't exist
if (!file_exists($dbPath) && file_exists('../db/app.db')) {
$dbPath = '../db/app.db';
}
if (!file_exists($confPath) && file_exists('../config/app.conf')) {
$confPath = '../config/app.conf';
}
checkPermissions([$dbPath, $confPath]);
?>

View File

@@ -17,11 +17,12 @@
// Size and last mod of DB ------------------------------------------------------
$nax_db = str_replace('front', 'db', getcwd()).'/app.db';
$nax_wal = str_replace('front', 'db', getcwd()).'/app.db-wal';
$nax_db_size = number_format((filesize($nax_db) / 1000000),2,",",".") . ' MB';
$nax_wal_size = number_format((filesize($nax_wal) / 1000000),2,",",".") . ' MB';
$nax_db_mod = date ("F d Y H:i:s", filemtime($nax_db));
$dbBasePath = rtrim(getenv('NETALERTX_DB') ?: '/data/db', '/');
$nax_db = $dbBasePath . '/app.db';
$nax_wal = $dbBasePath . '/app.db-wal';
$nax_db_size = file_exists($nax_db) ? number_format((filesize($nax_db) / 1000000),2,",",".") . ' MB' : '0 MB';
$nax_wal_size = file_exists($nax_wal) ? number_format((filesize($nax_wal) / 1000000),2,",",".") . ' MB' : '0 MB';
$nax_db_mod = file_exists($nax_db) ? date ("F d Y H:i:s", filemtime($nax_db)) : 'N/A';
// Table sizes -----------------------------------------------------------------
@@ -334,7 +335,7 @@ $db->close();
var emptyArr = ['undefined', "", undefined, null];
var selectedTab = 'tab_DBTools_id';
initializeTabs();
// initializeTabs() is called in window.onload
// -----------------------------------------------------------
// delete devices with emty macs
@@ -704,7 +705,7 @@ function renderLogs(customData) {
window.onload = function asyncFooter() {
renderLogs();
// initializeTabs();
initializeTabs();
try {
$("#lastCommit").append('<a href="https://github.com/jokob-sk/NetAlertX/commits" target="_blank"><img alt="GitHub last commit" src="https://img.shields.io/github/last-commit/jokob-sk/netalertx/main?logo=github"></a>');

View File

@@ -2,30 +2,59 @@
require '../server/init.php';
$logBasePath = rtrim(getenv('NETALERTX_LOG') ?: '/tmp/log', '/');
function resolveLogPath($path)
{
global $logBasePath;
if ($path === null || $path === '') {
return $path;
}
$placeholder = '__NETALERTX_LOG__';
if (strpos($path, $placeholder) === 0) {
return $logBasePath . substr($path, strlen($placeholder));
}
return $path;
}
//------------------------------------------------------------------------------
// check if authenticated
require_once $_SERVER['DOCUMENT_ROOT'] . '/php/templates/security.php';
// Function to render the log area component
function renderLogArea($params) {
global $logBasePath;
$fileName = isset($params['fileName']) ? $params['fileName'] : '';
$filePath = isset($params['filePath']) ? $params['filePath'] : '';
$textAreaCssClass = isset($params['textAreaCssClass']) ? $params['textAreaCssClass'] : '';
$buttons = isset($params['buttons']) ? $params['buttons'] : [];
$content = "";
if (filesize($filePath) > 2000000) {
$filePath = resolveLogPath($filePath);
if (!is_file($filePath)) {
$content = "";
$fileSizeMb = 0.0;
} elseif (filesize($filePath) > 2000000) {
$content = file_get_contents($filePath, false, null, -2000000);
$fileSizeMb = filesize($filePath) / 1000000;
} else {
$content = file_get_contents($filePath);
$fileSizeMb = filesize($filePath) / 1000000;
}
// Prepare the download button HTML if filePath starts with /app
// Prepare the download button HTML if filePath resides under the active log base path
$downloadButtonHtml = '';
if (strpos($filePath, '/app') === 0) {
$logPrefix = $logBasePath . '/';
if ($logPrefix !== '/' && strpos($filePath, $logPrefix) === 0) {
$downloadName = basename($filePath);
$downloadButtonHtml = '
<span class="span-padding">
<a href="' . htmlspecialchars(str_replace('/app/log/', '/php/server/query_logs.php?file=', $filePath)) . '" target="_blank">
<a href="' . htmlspecialchars('/php/server/query_logs.php?file=' . rawurlencode($downloadName)) . '" target="_blank">
<i class="fa fa-download"></i>
</a>
</span>';
@@ -63,7 +92,7 @@ function renderLogArea($params) {
</div>
<div class="row logs-row">
<div class="log-file col-sm-6 col-xs-12">' . htmlspecialchars($filePath) . '
<div class="logs-size">' . number_format((filesize($filePath) / 1000000), 2, ",", ".") . ' MB'
<div class="logs-size">' . number_format($fileSizeMb, 2, ",", ".") . ' MB'
. $downloadButtonHtml .
'</div>
</div>

View File

@@ -10,8 +10,8 @@
"event": "askRestartBackend()"
}
],
"fileName": "app.log",
"filePath": "/app/log/app.log",
"fileName": "app.log",
"filePath": "__NETALERTX_LOG__/app.log",
"textAreaCssClass": "logs"
},
@@ -22,8 +22,8 @@
"event": "logManage('app_front.log', 'cleanLog')"
}
],
"fileName": "app_front.log",
"filePath": "/app/log/app_front.log",
"fileName": "app_front.log",
"filePath": "__NETALERTX_LOG__/app_front.log",
"textAreaCssClass": "logs logs-small"
},
{
@@ -33,8 +33,8 @@
"event": "logManage('app.php_errors.log', 'cleanLog')"
}
],
"fileName": "app.php_errors.log",
"filePath": "/app/log/app.php_errors.log",
"fileName": "app.php_errors.log",
"filePath": "__NETALERTX_LOG__/app.php_errors.log",
"textAreaCssClass": "logs logs-small"
},
{
@@ -44,15 +44,19 @@
"event": "logManage('execution_queue.log', 'cleanLog')"
}
],
"fileName": "execution_queue.log",
"filePath": "/app/log/execution_queue.log",
"fileName": "execution_queue.log",
"filePath": "__NETALERTX_LOG__/execution_queue.log",
"textAreaCssClass": "logs logs-small"
},
{
"buttons": [
{
"labelStringCode": "Maint_PurgeLog",
"event": "logManage('nginx-error.log', 'cleanLog')"
}
],
"fileName": "nginx/error.log",
"filePath": "/var/log/nginx/error.log",
"fileName": "nginx-error.log",
"filePath": "__NETALERTX_LOG__/nginx-error.log",
"textAreaCssClass": "logs logs-small"
},
{
@@ -62,8 +66,8 @@
"event": "logManage('db_is_locked.log', 'cleanLog')"
}
],
"fileName": "db_is_locked.log",
"filePath": "/app/log/db_is_locked.log",
"fileName": "db_is_locked.log",
"filePath": "__NETALERTX_LOG__/db_is_locked.log",
"textAreaCssClass": "logs logs-small"
},
{
@@ -73,8 +77,8 @@
"event": "logManage('stdout.log', 'cleanLog')"
}
],
"fileName": "stdout.log",
"filePath": "/app/log/stdout.log",
"fileName": "stdout.log",
"filePath": "__NETALERTX_LOG__/stdout.log",
"textAreaCssClass": "logs logs-small"
},
{
@@ -84,8 +88,30 @@
"event": "logManage('stderr.log', 'cleanLog')"
}
],
"fileName": "stderr.log",
"filePath": "/app/log/stderr.log",
"fileName": "stderr.log",
"filePath": "__NETALERTX_LOG__/stderr.log",
"textAreaCssClass": "logs logs-small"
},
{
"buttons": [
{
"labelStringCode": "Maint_PurgeLog",
"event": "logManage('IP_changes.log', 'cleanLog')"
}
],
"fileName": "IP_changes.log",
"filePath": "__NETALERTX_LOG__/IP_changes.log",
"textAreaCssClass": "logs logs-small"
},
{
"buttons": [
{
"labelStringCode": "Maint_PurgeLog",
"event": "logManage('crond.log', 'cleanLog')"
}
],
"fileName": "crond.log",
"filePath": "__NETALERTX_LOG__/crond.log",
"textAreaCssClass": "logs logs-small"
}
]

View File

@@ -13,8 +13,35 @@
// $DBFILE = dirname(__FILE__).'/../../../db/app.db';
// $DBFILE_LOCKED_FILE = dirname(__FILE__).'/../../../log/db_is_locked.log';
$scriptDir = realpath(dirname(__FILE__)); // Resolves symlinks to the actual physical path
$DBFILE = $scriptDir . '/../../../db/app.db';
$DBFILE_LOCKED_FILE = $scriptDir . '/../../../log/db_is_locked.log';
$legacyDbPath = $scriptDir . '/../../../db/app.db';
$legacyLogDir = $scriptDir . '/../../../log';
$dbFolderPath = rtrim(getenv('NETALERTX_DB') ?: '/data/db', '/');
$logFolderPath = rtrim(getenv('NETALERTX_LOG') ?: '/tmp/log', '/');
// Fallback to legacy layout if the new location is missing but the legacy file still exists
if (!is_dir($dbFolderPath) && file_exists($legacyDbPath)) {
$dbFolderPath = dirname($legacyDbPath);
}
if (!is_dir($dbFolderPath)) {
@mkdir($dbFolderPath, 0775, true);
}
$DBFILE = rtrim($dbFolderPath, '/') . '/app.db';
if (!file_exists($DBFILE) && file_exists($legacyDbPath)) {
$DBFILE = $legacyDbPath;
}
if (!is_dir($logFolderPath) && is_dir($legacyLogDir)) {
$logFolderPath = $legacyLogDir;
}
if (!is_dir($logFolderPath)) {
@mkdir($logFolderPath, 0775, true);
}
$DBFILE_LOCKED_FILE = rtrim($logFolderPath, '/') . '/db_is_locked.log';
//------------------------------------------------------------------------------
@@ -39,8 +66,10 @@ function SQLite3_connect($trytoreconnect = true, $retryCount = 0) {
if (!file_exists($DBFILE)) {
die("Database file not found: $DBFILE");
}
if (!file_exists(dirname($DBFILE_LOCKED_FILE))) {
die("Log directory not found: " . dirname($DBFILE_LOCKED_FILE));
$lockDir = dirname($DBFILE_LOCKED_FILE);
if (!is_dir($lockDir) && !@mkdir($lockDir, 0775, true)) {
die("Log directory not found and could not be created: $lockDir");
}
@@ -130,6 +159,7 @@ class CustomDatabaseWrapper {
$message = 'Error executing query (attempts: ' . $attempts . '), query: ' . $query;
// write_notification($message);
error_log("Query failed after {$this->maxRetries} attempts: " . $this->sqlite->lastErrorMsg());
return false;
}
public function query_log_add($query)
@@ -187,7 +217,7 @@ function OpenDB($DBPath = null) {
if (strlen($DBFILE) == 0) {
$message = 'Database not available';
echo '<script>alert('.$message.')</script>';
echo '<script>alert("'.$message.'")</script>';
write_notification($message);
die('<div style="padding-left:150px">'.$message.'</div>');
@@ -197,7 +227,7 @@ function OpenDB($DBPath = null) {
$db = new CustomDatabaseWrapper($DBFILE);
} catch (Exception $e) {
$message = "Error connecting to the database";
echo '<script>alert('.$message.'": ' . $e->getMessage() . '")</script>';
echo '<script>alert("'.$message.': '.$e->getMessage().'")</script>';
write_notification($message);
die('<div style="padding-left:150px">'.$message.'</div>');
}

View File

@@ -1,5 +1,6 @@
<?php
ini_set('error_log', '../../log/app.php_errors.log'); // initializing the app.php_errors.log file for the maintenance section
$logPath = rtrim(getenv('NETALERTX_LOG') ?: '/tmp/log', '/') . '/app.php_errors.log';
ini_set('error_log', $logPath); // initializing the app.php_errors.log file for the maintenance section
require dirname(__FILE__).'/../templates/globals.php';
require dirname(__FILE__).'/db.php';
require dirname(__FILE__).'/util.php';

View File

@@ -18,7 +18,8 @@ if ($_SERVER['REQUEST_METHOD'] === 'GET') {
// Check if file parameter is provided
if ($file) {
// Define the folder where files are located
$filePath = "/app/config/" . basename($file);
$configRoot = getenv('NETALERTX_CONFIG') ?: '/data/config';
$filePath = rtrim($configRoot, '/') . "/" . basename($file);
// Check if the file exists and is readable
if (file_exists($filePath) && is_readable($filePath)) {

View File

@@ -11,6 +11,8 @@ require dirname(__FILE__).'/../server/init.php';
//------------------------------------------------------------------------------
// Handle incoming requests
if ($_SERVER['REQUEST_METHOD'] === 'GET') {
$configRoot = getenv('NETALERTX_CONFIG') ?: '/data/config';
$apiRoot = getenv('NETALERTX_API') ?: '/tmp/api';
// Get query string parameter ?file=settings_table.json
$file = isset($_GET['file']) ? $_GET['file'] : null;
@@ -19,10 +21,10 @@ if ($_SERVER['REQUEST_METHOD'] === 'GET') {
// Define the folder where files are located
if ($file == "workflows.json")
{
$filePath = "/app/config/" . basename($file);
$filePath = rtrim($configRoot, '/') . "/" . basename($file);
} else
{
$filePath = "/app/api/" . basename($file);
$filePath = rtrim($apiRoot, '/') . "/" . basename($file);
}
// Check if the file exists
@@ -59,7 +61,8 @@ if ($_SERVER['REQUEST_METHOD'] === 'GET') {
}
$file = $_GET['file'];
$filePath = "/app/config/" . basename($file);
$configRoot = getenv('NETALERTX_CONFIG') ?: '/data/config';
$filePath = rtrim($configRoot, '/') . "/" . basename($file);
// Save new workflows.json (replace existing content)
if (file_put_contents($filePath, json_encode($decodedData, JSON_PRETTY_PRINT))) {

View File

@@ -16,8 +16,9 @@ if ($_SERVER['REQUEST_METHOD'] === 'GET') {
// Check if file parameter is provided
if ($file) {
// Define the folder where files are located
$filePath = "/app/log/" . basename($file);
// Define the folder where files are located
$logBasePath = rtrim(getenv('NETALERTX_LOG') ?: '/tmp/log', '/');
$filePath = $logBasePath . '/' . basename($file);
// Check if the file exists
if (file_exists($filePath)) {

View File

@@ -11,6 +11,7 @@
require dirname(__FILE__).'/../templates/globals.php';
require dirname(__FILE__).'/../templates/skinUI.php';
//------------------------------------------------------------------------------
// check if authenticated
require_once $_SERVER['DOCUMENT_ROOT'] . '/php/templates/security.php';
@@ -263,7 +264,7 @@ function cleanLog($logFile)
$path = "";
$allowedFiles = ['app.log', 'app_front.log', 'IP_changes.log', 'stdout.log', 'stderr.log', 'app.php_errors.log', 'execution_queue.log', 'db_is_locked.log'];
$allowedFiles = ['app.log', 'app_front.log', 'IP_changes.log', 'stdout.log', 'stderr.log', 'app.php_errors.log', 'execution_queue.log', 'db_is_locked.log', 'nginx-error.log', 'crond.log'];
if(in_array($logFile, $allowedFiles))
{
@@ -312,7 +313,7 @@ function saveSettings()
$txt = $txt."#-----------------AUTOGENERATED FILE-----------------#\n";
$txt = $txt."# #\n";
$txt = $txt."# Generated: ".$timestamp." #\n";
$txt = $txt."# Generated: ".$timestamp." #\n";
$txt = $txt."# #\n";
$txt = $txt."# Config file for the LAN intruder detection app: #\n";
$txt = $txt."# https://github.com/jokob-sk/NetAlertX #\n";
@@ -321,7 +322,12 @@ function saveSettings()
// collect all groups
$decodedSettings = json_decode($SETTINGS, true);
$decodedSettings = json_decode((string)$SETTINGS, true);
if ($decodedSettings === null) {
echo "Error: Invalid JSON in settings data.";
return;
}
foreach ($decodedSettings as $setting) {
if( in_array($setting[0] , $groups) == false) {
@@ -431,8 +437,9 @@ function getString ($setKey, $default) {
}
// -------------------------------------------------------------------------------------------
function getSettingValue($setKey) {
// Define the JSON endpoint URL
$url = dirname(__FILE__).'/../../../api/table_settings.json';
// Define the JSON endpoint URL
$apiRoot = rtrim(getenv('NETALERTX_API') ?: '/tmp/api', '/');
$url = $apiRoot . '/table_settings.json';
// Fetch the JSON data
$json = file_get_contents($url);

View File

@@ -7,6 +7,11 @@
require dirname(__FILE__).'/../templates/globals.php';
function get_notification_store_path(): string {
$apiRoot = getenv('NETALERTX_API') ?: '/tmp/api';
return rtrim($apiRoot, '/') . '/user_notifications.json';
}
//------------------------------------------------------------------------------
// check if authenticated
require_once $_SERVER['DOCUMENT_ROOT'] . '/php/templates/security.php';
@@ -69,7 +74,7 @@ function generate_guid() {
// ----------------------------------------------------------------------------------------
// Logs a notification in in-app notification system
function write_notification($content, $level = "interrupt") {
$NOTIFICATION_API_FILE = '/app/api/user_notifications.json';
$NOTIFICATION_API_FILE = get_notification_store_path();
// Generate GUID
$guid = generate_guid();
@@ -102,7 +107,7 @@ function write_notification($content, $level = "interrupt") {
// ----------------------------------------------------------------------------------------
// Removes a notification based on GUID
function remove_notification($guid) {
$NOTIFICATION_API_FILE = '/app/api/user_notifications.json';
$NOTIFICATION_API_FILE = get_notification_store_path();
// Read existing notifications
$notifications = json_decode(file_get_contents($NOTIFICATION_API_FILE), true);
@@ -119,7 +124,7 @@ function remove_notification($guid) {
// ----------------------------------------------------------------------------------------
// Deletes all notifications
function notifications_clear() {
$NOTIFICATION_API_FILE = '/app/api/user_notifications.json';
$NOTIFICATION_API_FILE = get_notification_store_path();
// Clear notifications by writing an empty array to the file
file_put_contents($NOTIFICATION_API_FILE, json_encode(array()));
@@ -128,7 +133,7 @@ function notifications_clear() {
// ----------------------------------------------------------------------------------------
// Mark a notification read based on GUID
function mark_notification_as_read($guid) {
$NOTIFICATION_API_FILE = '/app/api/user_notifications.json';
$NOTIFICATION_API_FILE = get_notification_store_path();
$max_attempts = 3;
$attempts = 0;
@@ -177,7 +182,7 @@ function notifications_mark_all_read() {
// ----------------------------------------------------------------------------------------
function get_unread_notifications() {
$NOTIFICATION_API_FILE = '/app/api/user_notifications.json';
$NOTIFICATION_API_FILE = get_notification_store_path();
// Read existing notifications
if (file_exists($NOTIFICATION_API_FILE) && is_readable($NOTIFICATION_API_FILE)) {

View File

@@ -15,7 +15,19 @@ if (isset($_SESSION["login"]) && $_SESSION["login"] == 1) {
// Check if a valid cookie is present
$CookieSaveLoginName = "NetAlertX_SaveLogin";
$config_file = "../../../config/app.conf"; // depends on where this file is called from
// Use environment-aware config path
$configFolderPath = rtrim(getenv('NETALERTX_CONFIG') ?: '/data/config', '/');
$config_file = $configFolderPath . '/app.conf';
// Fallback to legacy path if new location doesn't exist
if (!file_exists($config_file)) {
$legacyPath = "../../../config/app.conf";
if (file_exists($legacyPath)) {
$config_file = $legacyPath;
}
}
$config_file_lines = file($config_file);
$config_file_lines = array_values(preg_grep('/^SETPWD_password.*=/', $config_file_lines));
$password_line = explode("'", $config_file_lines[0]);

View File

@@ -4,8 +4,8 @@
// ## Global constants and TimeZone processing
// ######################################################################
$configFolderPath = "/app/config/";
$logFolderPath = "/app/log/";
$configFolderPath = rtrim(getenv('NETALERTX_CONFIG') ?: '/data/config', '/') . '/';
$logFolderPath = rtrim(getenv('NETALERTX_LOG') ?: '/tmp/log', '/') . '/';
$config_file = "app.conf";
$workflows_file = "workflows.json";

View File

@@ -674,7 +674,7 @@
"Systeminfo_System_Uptime": "Uptime:",
"Systeminfo_This_Client": "Aquest Client",
"Systeminfo_USB_Devices": "Dispositius USB",
"TICKER_MIGRATE_TO_NETALERTX": "⚠ S'han detectat punts muntatge antics. Ves a <a href=\"https://github.com/jokob-sk/NetAlertX/blob/main/docs/MIGRATION.md\" target=\"_blank\">aquesta guia</a> per migrar les noves <code>/app/config</code> i <code>/app/db</code> carpetes i al <code>netalertx</code> contenidor.",
"TICKER_MIGRATE_TO_NETALERTX": "⚠ S'han detectat punts muntatge antics. Ves a <a href=\"https://github.com/jokob-sk/NetAlertX/blob/main/docs/MIGRATION.md\" target=\"_blank\">aquesta guia</a> per migrar les noves <code>/data/config</code> i <code>/data/db</code> carpetes i al <code>netalertx</code> contenidor.",
"TIMEZONE_description": "Fus horari per mostrar les estadístiques correctament. <a target=\"_blank\" href=\"https://en.wikipedia.org/wiki/List_of_tz_database_time_zones\" rel=\"nofollow\">aquí</a>.",
"TIMEZONE_name": "Fus horari",
"UI_DEV_SECTIONS_description": "Seleccioneu quins elements de la interfície d'usuari per ocultar a les pàgines de dispositius.",

View File

@@ -674,7 +674,7 @@
"Systeminfo_System_Uptime": "Uptime:",
"Systeminfo_This_Client": "This Client",
"Systeminfo_USB_Devices": "USB devices",
"TICKER_MIGRATE_TO_NETALERTX": "⚠ Old mount locations detected. Follow <a href=\"https://github.com/jokob-sk/NetAlertX/blob/main/docs/MIGRATION.md\" target=\"_blank\">this guide</a> to migrate to the new <code>/app/config</code> and <code>/app/db</code> folders and the <code>netalertx</code> container.",
"TICKER_MIGRATE_TO_NETALERTX": "⚠ Old mount locations detected. Follow <a href=\"https://github.com/jokob-sk/NetAlertX/blob/main/docs/MIGRATION.md\" target=\"_blank\">this guide</a> to migrate to the new <code>/data/config</code> and <code>/data/db</code> folders and the <code>netalertx</code> container.",
"TIMEZONE_description": "Time zone to display stats correctly. Find your time zone <a target=\"_blank\" href=\"https://en.wikipedia.org/wiki/List_of_tz_database_time_zones\" rel=\"nofollow\">here</a>.",
"TIMEZONE_name": "Time zone",
"UI_DEV_SECTIONS_description": "Select which UI elements to hide in the devices pages.",

View File

@@ -734,7 +734,7 @@
"Systeminfo_System_Uptime": "Tiempo de actividad:",
"Systeminfo_This_Client": "Este cliente",
"Systeminfo_USB_Devices": "Dispositivos USB",
"TICKER_MIGRATE_TO_NETALERTX": "⚠ Ubicaciones de montaje antiguas detectadas. Siga <a href=\"https://github.com/jokob-sk/NetAlertX/blob/main/docs/MIGRATION.md\" target=\"_blank\">esta guía</a> para migrar a las nuevas carpetas <code>/app/config</code> y <code>/app/db</code> y el contenedor <code>netalertx</code>.",
"TICKER_MIGRATE_TO_NETALERTX": "⚠ Ubicaciones de montaje antiguas detectadas. Siga <a href=\"https://github.com/jokob-sk/NetAlertX/blob/main/docs/MIGRATION.md\" target=\"_blank\">esta guía</a> para migrar a las nuevas carpetas <code>/data/config</code> y <code>/data/db</code> y el contenedor <code>netalertx</code>.",
"TIMEZONE_description": "La zona horaria para mostrar las estadísticas correctamente. Encuentra tu zona horaria <a target=\"_blank\" href=\"https://en.wikipedia.org/wiki/List_of_tz_database_time_zones\" rel=\"nofollow\">aquí</a>.",
"TIMEZONE_name": "Zona horaria",
"UI_DEV_SECTIONS_description": "Seleccione los elementos de la interfaz de usuario que desea ocultar en las páginas de dispositivos.",

View File

@@ -674,7 +674,7 @@
"Systeminfo_System_Uptime": "Durée d'activité:",
"Systeminfo_This_Client": "Ce client",
"Systeminfo_USB_Devices": "Appareils USB",
"TICKER_MIGRATE_TO_NETALERTX": "⚠ Emplacement de point de montage obsolète détecté. Suivez <a href=\"https://github.com/jokob-sk/NetAlertX/blob/main/docs/MIGRATION.md\" target=\"_blank\">ce guide</a> pour migrer vers les nouveaux dossiers <code>/app/config</code> and <code>/app/db</code> et le container <code>netalertx</code>.",
"TICKER_MIGRATE_TO_NETALERTX": "⚠ Emplacement de point de montage obsolète détecté. Suivez <a href=\"https://github.com/jokob-sk/NetAlertX/blob/main/docs/MIGRATION.md\" target=\"_blank\">ce guide</a> pour migrer vers les nouveaux dossiers <code>/data/config</code> and <code>/data/db</code> et le container <code>netalertx</code>.",
"TIMEZONE_description": "Fuseau horaire pour afficher correctement les statistiques. Trouvez votre fuseau horaire <a target=\"_blank\" href=\"https://en.wikipedia.org/wiki/List_of_tz_database_time_zones\" rel=\"nofollow\">ici</a>.",
"TIMEZONE_name": "Fuseau horaire",
"UI_DEV_SECTIONS_description": "Slecetionnez quels éléments de l'interface graphique masquer dans les pages des appareils.",

View File

@@ -674,7 +674,7 @@
"Systeminfo_System_Uptime": "Tempo di attività:",
"Systeminfo_This_Client": "Questo client",
"Systeminfo_USB_Devices": "Dispositivi USB",
"TICKER_MIGRATE_TO_NETALERTX": "⚠ Rilevate vecchie posizioni di montaggio. Segui <a href=\"https://github.com/jokob-sk/NetAlertX/blob/main/docs/MIGRATION.md\" target=\"_blank\">questa guida</a> per migrare alle nuove cartelle <code> /app/config</code> e <code>/app/db</code> e al contenitore <code>netalertx</code>.",
"TICKER_MIGRATE_TO_NETALERTX": "⚠ Rilevate vecchie posizioni di montaggio. Segui <a href=\"https://github.com/jokob-sk/NetAlertX/blob/main/docs/MIGRATION.md\" target=\"_blank\">questa guida</a> per migrare alle nuove cartelle <code> /data/config</code> e <code>/data/db</code> e al contenitore <code>netalertx</code>.",
"TIMEZONE_description": "Fuso orario per visualizzare correttamente le statistiche. Trova il tuo fuso orario <a target=\"_blank\" href=\"https://en.wikipedia.org/wiki/List_of_tz_database_time_zones\" rel=\"nofollow\">qui</a>.",
"TIMEZONE_name": "Fuso orario",
"UI_DEV_SECTIONS_description": "Seleziona quali elementi della UI nascondere nella pagina dei dispositivi.",

View File

@@ -674,7 +674,7 @@
"Systeminfo_System_Uptime": "Oppetid:",
"Systeminfo_This_Client": "Denne klienten",
"Systeminfo_USB_Devices": "USB-enheter",
"TICKER_MIGRATE_TO_NETALERTX": "⚠ Eldre Mount-lokasjoner oppdaget. Følg <a href=\"https://github.com/jokob-sk/NetAlertX/blob/main/docs/MIGRATION.md\" target=\"_blank\">denne guiden</a> for å migrere til den nye <code>/app/config</code> og <code>/app/db </code> mappene og <code>netalertx</code> containeren.",
"TICKER_MIGRATE_TO_NETALERTX": "⚠ Eldre Mount-lokasjoner oppdaget. Følg <a href=\"https://github.com/jokob-sk/NetAlertX/blob/main/docs/MIGRATION.md\" target=\"_blank\">denne guiden</a> for å migrere til den nye <code>/data/config</code> og <code>/data/db </code> mappene og <code>netalertx</code> containeren.",
"TIMEZONE_description": "Tidssone for å vise statistikk riktig. Finn din tidssone <a target=\"_blank\" href=\"https://en.wikipedia.org/wiki/List_of_tz_database_time_zones\" rel=\"nofollow\">her</a>.",
"TIMEZONE_name": "Tidssone",
"UI_DEV_SECTIONS_description": "Velg hvilke UI -elementer du vil skjule på enhetssiden.",

View File

@@ -674,7 +674,7 @@
"Systeminfo_System_Uptime": "Czas pracy:",
"Systeminfo_This_Client": "Ten klient",
"Systeminfo_USB_Devices": "Urządzenia USB",
"TICKER_MIGRATE_TO_NETALERTX": "⚠ Wykryto stare lokalizacje montowania. Skorzystaj z <a href=\"https://github.com/jokob-sk/NetAlertX/blob/main/docs/MIGRATION.md\" target=\"_blank\">tego przewodnika</a>, aby przeprowadzić migrację do nowych folderów <code>/app/config</code> i <code>/app/db</code> oraz kontenera <code>netalertx</code>.",
"TICKER_MIGRATE_TO_NETALERTX": "⚠ Wykryto stare lokalizacje montowania. Skorzystaj z <a href=\"https://github.com/jokob-sk/NetAlertX/blob/main/docs/MIGRATION.md\" target=\"_blank\">tego przewodnika</a>, aby przeprowadzić migrację do nowych folderów <code>/data/config</code> i <code>/data/db</code> oraz kontenera <code>netalertx</code>.",
"TIMEZONE_description": "Ustaw strefę czasową, aby statystyki były wyświetlane poprawnie. Znajdź swoją strefę czasową <a target=\"_blank\" href=\"https://en.wikipedia.org/wiki/List_of_tz_database_time_zones\" rel=\"nofollow\">tutaj</a>.",
"TIMEZONE_name": "Strefa czasowa",
"UI_DEV_SECTIONS_description": "Wybierz elementy interfejsu użytkownika (UI), które chcesz ukryć na stronach Urządzeń.",

View File

@@ -674,7 +674,7 @@
"Systeminfo_System_Uptime": "Время работы:",
"Systeminfo_This_Client": "Этот клиент",
"Systeminfo_USB_Devices": "USB-устройства",
"TICKER_MIGRATE_TO_NETALERTX": "⚠ Обнаружены устаревшие местоположения. Следуйте этому руководству <a href=\"https://github.com/jokob-sk/NetAlertX/blob/main/docs/MIGRATION.md\" target=\"_blank\"></a>, чтобы перейти на новые <code>/app/config</code> и <code>/app/db</code> папки и контейнер <code>netalertx</code>.",
"TICKER_MIGRATE_TO_NETALERTX": "⚠ Обнаружены устаревшие местоположения. Следуйте этому руководству <a href=\"https://github.com/jokob-sk/NetAlertX/blob/main/docs/MIGRATION.md\" target=\"_blank\"></a>, чтобы перейти на новые <code>/data/config</code> и <code>/data/db</code> папки и контейнер <code>netalertx</code>.",
"TIMEZONE_description": "Часовой пояс для корректного отображения статистики. Найдите свой часовой пояс <a target=\"_blank\" href=\"https://en.wikipedia.org/wiki/List_of_tz_database_time_zones\" rel=\"nofollow\">здесь</a>.",
"TIMEZONE_name": "Часовой пояс",
"UI_DEV_SECTIONS_description": "Выберите, какие элементы интерфейса нужно скрыть на страницах «Устройства».",

View File

@@ -674,7 +674,7 @@
"Systeminfo_System_Uptime": "Час роботи:",
"Systeminfo_This_Client": "Цей клієнт",
"Systeminfo_USB_Devices": "USB-пристрої",
"TICKER_MIGRATE_TO_NETALERTX": "⚠ Виявлено старі місця монтування. Дотримуйтеся <a href=\"https://github.com/jokob-sk/NetAlertX/blob/main/docs/MIGRATION.md\" target=\"_blank\">цього посібника</a>, щоб перейти на новий <code> папки /app/config</code> і <code>/app/db</code> і контейнер <code>netalertx</code>.",
"TICKER_MIGRATE_TO_NETALERTX": "⚠ Виявлено старі місця монтування. Дотримуйтеся <a href=\"https://github.com/jokob-sk/NetAlertX/blob/main/docs/MIGRATION.md\" target=\"_blank\">цього посібника</a>, щоб перейти на нові папки <code>/data/config</code> і <code>/data/db</code> та контейнер <code>netalertx</code>.",
"TIMEZONE_description": "Часовий пояс для правильного відображення статистики. Знайдіть свій часовий пояс <a target=\"_blank\" href=\"https://en.wikipedia.org/wiki/List_of_tz_database_time_zones\" rel=\"nofollow\">тут</a>.",
"TIMEZONE_name": "Часовий пояс",
"UI_DEV_SECTIONS_description": "Виберіть, які елементи інтерфейсу користувача приховати на сторінках пристроїв.",

View File

@@ -674,7 +674,7 @@
"Systeminfo_System_Uptime": "正常运行时间:",
"Systeminfo_This_Client": "此客户",
"Systeminfo_USB_Devices": "USB 设备",
"TICKER_MIGRATE_TO_NETALERTX": "⚠ 检测到旧的挂载位置。请按照<a href=\"https://github.com/jokob-sk/NetAlertX/blob/main/docs/MIGRATION.md\" target=\"_blank\">本指南</a>迁移到新的 <code>/app/config</code> 和 <code>/app/db</code> 文件夹以及 <code>netalertx</code> 容器。",
"TICKER_MIGRATE_TO_NETALERTX": "⚠ 检测到旧的挂载位置。请按照<a href=\"https://github.com/jokob-sk/NetAlertX/blob/main/docs/MIGRATION.md\" target=\"_blank\">本指南</a>迁移到新的 <code>/data/config</code> 和 <code>/data/db</code> 文件夹以及 <code>netalertx</code> 容器。",
"TIMEZONE_description": "时区可正确显示统计数据。在<a target=\"_blank\" href=\"https://en.wikipedia.org/wiki/List_of_tz_database_time_zones\" rel=\"nofollow\">此处</a>查找您的时区。",
"TIMEZONE_name": "时区",
"UI_DEV_SECTIONS_description": "选择在设备页面中隐藏哪些 UI 元素。",

View File

@@ -1,7 +1,18 @@
<?php
// Constants
define('CONFIG_PATH', $_SERVER['DOCUMENT_ROOT'] . "/../config/app.conf");
$configFolderPath = rtrim(getenv('NETALERTX_CONFIG') ?: '/data/config', '/');
$legacyConfigPath = $_SERVER['DOCUMENT_ROOT'] . "/../config/app.conf";
// Use environment variable path, fallback to legacy
if (file_exists($configFolderPath . '/app.conf')) {
define('CONFIG_PATH', $configFolderPath . '/app.conf');
} else if (file_exists($legacyConfigPath)) {
define('CONFIG_PATH', $legacyConfigPath);
} else {
define('CONFIG_PATH', $configFolderPath . '/app.conf'); // default to new location
}
define('COOKIE_SAVE_LOGIN_NAME', "NetAlertX_SaveLogin");
// Utility Functions
@@ -48,7 +59,7 @@ if (!empty($_REQUEST['action']) && $_REQUEST['action'] == 'logout') {
// Load configuration
if (!file_exists(CONFIG_PATH)) {
die("Configuration file not found in " . $_SERVER['DOCUMENT_ROOT'] . "/../config/app.conf");
die("Configuration file not found in " . CONFIG_PATH);
}
$configLines = file(CONFIG_PATH);

View File

@@ -1,23 +1,18 @@
#!/usr/bin/env python
import os
import pathlib
import sys
import json
import sqlite3
from pytz import timezone
# Define the installation path and extend the system path for plugin imports
INSTALL_PATH = "/app"
INSTALL_PATH = os.getenv('NETALERTX_APP', '/app')
sys.path.extend([f"{INSTALL_PATH}/front/plugins", f"{INSTALL_PATH}/server"])
from plugin_helper import Plugin_Object, Plugin_Objects, decodeBase64
from plugin_utils import get_plugins_configs
from plugin_helper import Plugin_Objects
from logger import mylog, Logger
from const import pluginsPath, fullDbPath, logPath
from helper import timeNowTZ, get_setting_value
from const import logPath
from helper import get_setting_value
from messaging.in_app import write_notification
import conf
# Make sure the TIMEZONE for logging is correct
@@ -54,26 +49,27 @@ def main():
# insert devices into the lats_result.log
# make sure the below mapping is mapped in config.json, for example:
#"database_column_definitions": [
# "database_column_definitions": [
# {
# "column": "Object_PrimaryID", <--------- the value I save into primaryId
# "mapped_to_column": "cur_MAC", <--------- gets inserted into the CurrentScan DB table column cur_MAC
# "column": "Object_PrimaryID", <--------- the value I save into primaryId
# "mapped_to_column": "cur_MAC", <--------- gets inserted into the CurrentScan DB
# table column cur_MAC
#
for device in device_data:
plugin_objects.add_object(
primaryId = device['mac_address'],
secondaryId = device['ip_address'],
watched1 = device['hostname'],
watched2 = device['vendor'],
watched3 = device['device_type'],
watched4 = device['last_seen'],
extra = '',
foreignKey = device['mac_address']
# helpVal1 = "Something1", # Optional Helper values to be passed for mapping into the app
# helpVal2 = "Something1", # If you need to use even only 1, add the remaining ones too
# helpVal3 = "Something1", # and set them to 'null'. Check the the docs for details:
# helpVal4 = "Something1", # https://github.com/jokob-sk/NetAlertX/blob/main/docs/PLUGINS_DEV.md
)
plugin_objects.add_object(
primaryId = device['mac_address'],
secondaryId = device['ip_address'],
watched1 = device['hostname'],
watched2 = device['vendor'],
watched3 = device['device_type'],
watched4 = device['last_seen'],
extra = '',
foreignKey = device['mac_address']
# helpVal1 = "Something1", # Optional Helper values to be passed for mapping into the app
# helpVal2 = "Something1", # If you need to use even only 1, add the remaining ones too
# helpVal3 = "Something1", # and set them to 'null'. Check the the docs for details:
# helpVal4 = "Something1", # https://github.com/jokob-sk/NetAlertX/blob/main/docs/PLUGINS_DEV.md
)
mylog('verbose', [f'[{pluginName}] New entries: "{len(device_data)}"'])

View File

@@ -1,31 +1,20 @@
#!/usr/bin/env python
# Just a testing library plugin for development purposes
import json
import subprocess
import argparse
import os
import pathlib
import sys
from datetime import datetime
import time
import re
import hashlib
import sqlite3
# Register NetAlertX directories
INSTALL_PATH="/app"
INSTALL_PATH = os.getenv('NETALERTX_APP', '/app')
sys.path.extend([f"{INSTALL_PATH}/front/plugins", f"{INSTALL_PATH}/server"])
# NetAlertX modules
import conf
from const import apiPath, confFileName, logPath
from plugin_utils import getPluginObject
from const import logPath
from plugin_helper import Plugin_Objects
from logger import mylog, Logger, append_line_to_file
from helper import timeNowTZ, get_setting_value, bytes_to_string, sanitize_string, cleanDeviceName
from models.notification_instance import NotificationInstance
from database import DB, get_device_stats
from logger import mylog
from helper import get_setting_value
pluginName = 'TESTONLY'

View File

@@ -2,45 +2,45 @@
import json
import subprocess
import argparse
import os
import pathlib
import sys
from datetime import datetime
# Register NetAlertX directories
INSTALL_PATH="/app"
INSTALL_PATH = os.getenv("NETALERTX_APP", "/app")
sys.path.extend([f"{INSTALL_PATH}/front/plugins", f"{INSTALL_PATH}/server"])
import conf
from const import confFileName, logPath
from plugin_helper import Plugin_Objects
from logger import mylog, Logger, append_line_to_file
from logger import mylog, Logger
from helper import timeNowTZ, get_setting_value
from models.notification_instance import NotificationInstance
from database import DB
from pytz import timezone
# Make sure the TIMEZONE for logging is correct
conf.tz = timezone(get_setting_value('TIMEZONE'))
conf.tz = timezone(get_setting_value("TIMEZONE"))
# Make sure log level is initialized correctly
Logger(get_setting_value('LOG_LEVEL'))
Logger(get_setting_value("LOG_LEVEL"))
pluginName = 'APPRISE'
LOG_PATH = logPath + '/plugins'
RESULT_FILE = os.path.join(LOG_PATH, f'last_result.{pluginName}.log')
pluginName = "APPRISE"
LOG_PATH = logPath + "/plugins"
RESULT_FILE = os.path.join(LOG_PATH, f"last_result.{pluginName}.log")
def main():
mylog('verbose', [f'[{pluginName}](publisher) In script'])
mylog("verbose", [f"[{pluginName}](publisher) In script"])
# Check if basic config settings supplied
if check_config() == False:
mylog('none', [f'[{pluginName}] ⚠ ERROR: Publisher notification gateway not set up correctly. Check your {confFileName} {pluginName}_* variables.'])
mylog(
"none",
[
f"[{pluginName}] ⚠ ERROR: Publisher notification gateway not set up correctly. Check your {confFileName} {pluginName}_* variables."
],
)
return
# Create a database connection
@@ -58,47 +58,50 @@ def main():
# Process the new notifications (see the Notifications DB table for structure or check the /php/server/query_json.php?file=table_notifications.json endpoint)
for notification in new_notifications:
# Send notification
result = send(notification["HTML"], notification["Text"])
result = send(notification["HTML"], notification["Text"])
# Log result
plugin_objects.add_object(
primaryId = pluginName,
secondaryId = timeNowTZ(),
watched1 = notification["GUID"],
watched2 = result,
watched3 = 'null',
watched4 = 'null',
extra = 'null',
foreignKey = notification["GUID"]
primaryId=pluginName,
secondaryId=timeNowTZ(),
watched1=notification["GUID"],
watched2=result,
watched3="null",
watched4="null",
extra="null",
foreignKey=notification["GUID"],
)
plugin_objects.write_result_file()
#-------------------------------------------------------------------------------
# -------------------------------------------------------------------------------
def check_config():
if get_setting_value('APPRISE_HOST') == '' or (get_setting_value('APPRISE_URL') == '' and get_setting_value('APPRISE_TAG') == ''):
return False
else:
return True
if get_setting_value("APPRISE_HOST") == "" or (
get_setting_value("APPRISE_URL") == ""
and get_setting_value("APPRISE_TAG") == ""
):
return False
else:
return True
#-------------------------------------------------------------------------------
# -------------------------------------------------------------------------------
def send(html, text):
payloadData = ''
result = ''
payloadData = ""
result = ""
# limit = 1024 * 1024 # 1MB limit (1024 bytes * 1024 bytes = 1MB)
limit = get_setting_value('APPRISE_SIZE')
limit = get_setting_value("APPRISE_SIZE")
# truncate size
if get_setting_value('APPRISE_PAYLOAD') == 'html':
if get_setting_value("APPRISE_PAYLOAD") == "html":
if len(html) > limit:
payloadData = html[:limit] + "<h1>(text was truncated)</h1>"
else:
payloadData = html
if get_setting_value('APPRISE_PAYLOAD') == 'text':
if get_setting_value("APPRISE_PAYLOAD") == "text":
if len(text) > limit:
payloadData = text[:limit] + " (text was truncated)"
else:
@@ -106,36 +109,55 @@ def send(html, text):
# Define Apprise compatible payload (https://github.com/caronc/apprise-api#stateless-solution)
target_key = "tag" if get_setting_value('APPRISE_TARGETTYPE') == 'tag' else "urls"
target_value = get_setting_value('APPRISE_TAG') if target_key == 'tag' else get_setting_value('APPRISE_URL')
target_key = "tag" if get_setting_value("APPRISE_TARGETTYPE") == "tag" else "urls"
target_value = (
get_setting_value("APPRISE_TAG")
if target_key == "tag"
else get_setting_value("APPRISE_URL")
)
_json_payload = {
target_key: target_value,
"title": "NetAlertX Notifications",
"format": get_setting_value('APPRISE_PAYLOAD'),
"body": payloadData
"format": get_setting_value("APPRISE_PAYLOAD"),
"body": payloadData,
}
try:
# try runnning a subprocess
p = subprocess.Popen(["curl","-i","-X", "POST" ,"-H", "Content-Type:application/json" ,"-d", json.dumps(_json_payload), get_setting_value('APPRISE_HOST')], stdout=subprocess.PIPE, stderr=subprocess.STDOUT)
p = subprocess.Popen(
[
"curl",
"-i",
"-X",
"POST",
"-H",
"Content-Type:application/json",
"-d",
json.dumps(_json_payload),
get_setting_value("APPRISE_HOST"),
],
stdout=subprocess.PIPE,
stderr=subprocess.STDOUT,
)
stdout, stderr = p.communicate()
# write stdout and stderr into .log files for debugging if needed
# Log the stdout and stderr
mylog('debug', [stdout, stderr])
mylog("debug", [stdout, stderr])
# log result
result = stdout
except subprocess.CalledProcessError as e:
# An error occurred, handle it
mylog('none', [e.output])
mylog("none", [e.output])
# log result
result = e.output
return result
if __name__ == '__main__':
if __name__ == "__main__":
sys.exit(main())

View File

@@ -1,12 +1,7 @@
#!/usr/bin/env python
import json
import subprocess
import argparse
import os
import pathlib
import sys
import re
from datetime import datetime
from email.mime.multipart import MIMEMultipart
from email.mime.text import MIMEText
from email.header import Header
@@ -17,14 +12,14 @@ import socket
import ssl
# Register NetAlertX directories
INSTALL_PATH="/app"
INSTALL_PATH = os.getenv('NETALERTX_APP', '/app')
sys.path.extend([f"{INSTALL_PATH}/front/plugins", f"{INSTALL_PATH}/server"])
# NetAlertX modules
import conf
from const import confFileName, logPath
from plugin_helper import Plugin_Objects
from logger import mylog, Logger, append_line_to_file
from logger import mylog, Logger
from helper import timeNowTZ, get_setting_value, hide_email
from models.notification_instance import NotificationInstance
from database import DB
@@ -66,15 +61,15 @@ def main():
new_notifications = notifications.getNew()
# mylog('verbose', [f'[{pluginName}] new_notifications: ', new_notifications])
mylog('verbose', [f'[{pluginName}] SMTP_SERVER: ', get_setting_value("SMTP_SERVER")])
mylog('verbose', [f'[{pluginName}] SMTP_PORT: ', get_setting_value("SMTP_PORT")])
mylog('verbose', [f'[{pluginName}] SMTP_SKIP_LOGIN: ', get_setting_value("SMTP_SKIP_LOGIN")])
# mylog('verbose', [f'[{pluginName}] SMTP_USER: ', get_setting_value("SMTP_USER")])
mylog('verbose', [f'[{pluginName}] SMTP_SERVER: ', get_setting_value("SMTP_SERVER")])
mylog('verbose', [f'[{pluginName}] SMTP_PORT: ', get_setting_value("SMTP_PORT")])
mylog('verbose', [f'[{pluginName}] SMTP_SKIP_LOGIN: ', get_setting_value("SMTP_SKIP_LOGIN")])
# mylog('verbose', [f'[{pluginName}] SMTP_USER: ', get_setting_value("SMTP_USER")])
# mylog('verbose', [f'[{pluginName}] SMTP_PASS: ', get_setting_value("SMTP_PASS")])
mylog('verbose', [f'[{pluginName}] SMTP_SKIP_TLS: ', get_setting_value("SMTP_SKIP_TLS")])
mylog('verbose', [f'[{pluginName}] SMTP_FORCE_SSL: ', get_setting_value("SMTP_FORCE_SSL")])
# mylog('verbose', [f'[{pluginName}] SMTP_REPORT_TO: ', get_setting_value("SMTP_REPORT_TO")])
# mylog('verbose', [f'[{pluginName}] SMTP_REPORT_FROM: ', get_setting_value("SMTP_REPORT_FROM")])
mylog('verbose', [f'[{pluginName}] SMTP_SKIP_TLS: ', get_setting_value("SMTP_SKIP_TLS")])
mylog('verbose', [f'[{pluginName}] SMTP_FORCE_SSL: ', get_setting_value("SMTP_FORCE_SSL")])
# mylog('verbose', [f'[{pluginName}] SMTP_REPORT_TO: ', get_setting_value("SMTP_REPORT_TO")])
# mylog('verbose', [f'[{pluginName}] SMTP_REPORT_FROM: ', get_setting_value("SMTP_REPORT_FROM")])
# Process the new notifications (see the Notifications DB table for structure or check the /php/server/query_json.php?file=table_notifications.json endpoint)

View File

@@ -14,7 +14,7 @@ from pytz import timezone
# Register NetAlertX directories
INSTALL_PATH = "/app"
INSTALL_PATH = os.getenv('NETALERTX_APP', '/app')
sys.path.extend([f"{INSTALL_PATH}/front/plugins", f"{INSTALL_PATH}/server"])
# NetAlertX modules
@@ -364,7 +364,6 @@ def mqtt_create_client():
return
except Exception as err:
mylog('verbose', [f"[{pluginName}] {err} Reconnect failed. Retrying..."])
pass
reconnect_delay *= RECONNECT_RATE
reconnect_delay = min(reconnect_delay, MAX_RECONNECT_DELAY)

View File

@@ -2,23 +2,19 @@
#!/usr/bin/env python
import json
import subprocess
import argparse
import os
import pathlib
import sys
import requests
from datetime import datetime
from base64 import b64encode
# Register NetAlertX directories
INSTALL_PATH="/app"
INSTALL_PATH = os.getenv('NETALERTX_APP', '/app')
sys.path.extend([f"{INSTALL_PATH}/front/plugins", f"{INSTALL_PATH}/server"])
import conf
from const import confFileName, logPath
from plugin_helper import Plugin_Objects, handleEmpty
from logger import mylog, Logger, append_line_to_file
from logger import mylog, Logger
from helper import timeNowTZ, get_setting_value
from models.notification_instance import NotificationInstance
from database import DB
@@ -63,7 +59,7 @@ def main():
for notification in new_notifications:
# Send notification
response_text, response_status_code = send(notification["HTML"], notification["Text"])
response_text, response_status_code = send(notification["HTML"], notification["Text"])
# Log result
plugin_objects.add_object(

View File

@@ -1,12 +1,15 @@
#!/usr/bin/env python3
import conf
from const import confFileName, logPath
from pytz import timezone
import os
import pathlib
import sys
import json
import requests
# Register NetAlertX directories
INSTALL_PATH="/app"
INSTALL_PATH = os.getenv("NETALERTX_APP", "/app")
sys.path.extend([f"{INSTALL_PATH}/front/plugins", f"{INSTALL_PATH}/server"])
from plugin_helper import Plugin_Objects, handleEmpty # noqa: E402
@@ -14,20 +17,17 @@ from logger import mylog, Logger # noqa: E402
from helper import timeNowTZ, get_setting_value, hide_string # noqa: E402
from models.notification_instance import NotificationInstance # noqa: E402
from database import DB # noqa: E402
import conf
from const import confFileName, logPath
from pytz import timezone
# Make sure the TIMEZONE for logging is correct
conf.tz = timezone(get_setting_value('TIMEZONE'))
conf.tz = timezone(get_setting_value("TIMEZONE"))
# Make sure log level is initialized correctly
Logger(get_setting_value('LOG_LEVEL'))
Logger(get_setting_value("LOG_LEVEL"))
pluginName = "PUSHOVER"
LOG_PATH = logPath + '/plugins'
RESULT_FILE = os.path.join(LOG_PATH, f'last_result.{pluginName}.log')
LOG_PATH = logPath + "/plugins"
RESULT_FILE = os.path.join(LOG_PATH, f"last_result.{pluginName}.log")
def main():

View File

@@ -2,23 +2,18 @@
#!/usr/bin/env python
import json
import subprocess
import argparse
import os
import pathlib
import sys
import requests
from datetime import datetime
from base64 import b64encode
# Register NetAlertX directories
INSTALL_PATH="/app"
INSTALL_PATH = os.getenv('NETALERTX_APP', '/app')
sys.path.extend([f"{INSTALL_PATH}/front/plugins", f"{INSTALL_PATH}/server"])
import conf
from const import confFileName, logPath
from plugin_helper import Plugin_Objects, handleEmpty
from logger import mylog, Logger, append_line_to_file
from logger import mylog, Logger
from helper import timeNowTZ, get_setting_value, hide_string
from models.notification_instance import NotificationInstance
from database import DB

View File

@@ -1,21 +1,17 @@
#!/usr/bin/env python
import json
import subprocess
import argparse
import os
import pathlib
import sys
from datetime import datetime
# Register NetAlertX directories
INSTALL_PATH = "/app"
INSTALL_PATH = os.getenv('NETALERTX_APP', '/app')
sys.path.extend([f"{INSTALL_PATH}/front/plugins", f"{INSTALL_PATH}/server"])
import conf
from const import confFileName, logPath
from plugin_helper import Plugin_Objects
from logger import mylog, Logger, append_line_to_file
from logger import mylog, Logger
from helper import timeNowTZ, get_setting_value
from models.notification_instance import NotificationInstance
from database import DB

View File

@@ -3,26 +3,21 @@
import json
import subprocess
import argparse
import os
import pathlib
import sys
import requests
from datetime import datetime
from base64 import b64encode
import hashlib
import hmac
# Register NetAlertX directories
INSTALL_PATH="/app"
INSTALL_PATH = os.getenv('NETALERTX_APP', '/app')
sys.path.extend([f"{INSTALL_PATH}/front/plugins", f"{INSTALL_PATH}/server"])
import conf
from const import logPath, confFileName
from plugin_helper import Plugin_Objects, handleEmpty
from logger import mylog, Logger, append_line_to_file
from helper import timeNowTZ, get_setting_value, hide_string, write_file
from logger import mylog, Logger
from helper import timeNowTZ, get_setting_value, write_file
from models.notification_instance import NotificationInstance
from database import DB
from pytz import timezone

View File

@@ -1,100 +1,90 @@
#!/usr/bin/env python
import os
import time
import pathlib
import argparse
import sys
import re
import base64
import subprocess
from time import strftime
# Register NetAlertX directories
INSTALL_PATH="/app"
sys.path.extend([f"{INSTALL_PATH}/front/plugins", f"{INSTALL_PATH}/server"])
from database import DB
from plugin_helper import Plugin_Object, Plugin_Objects, handleEmpty
from logger import mylog, Logger, append_line_to_file
from helper import timeNowTZ, get_setting_value
from const import logPath, applicationPath
from plugin_helper import Plugin_Objects, handleEmpty
from logger import mylog, Logger
from helper import get_setting_value
from const import logPath
import conf
from pytz import timezone
import os
import time
import argparse
import re
import base64
import subprocess
# Make sure the TIMEZONE for logging is correct
conf.tz = timezone(get_setting_value('TIMEZONE'))
conf.tz = timezone(get_setting_value("TIMEZONE"))
# Make sure log level is initialized correctly
Logger(get_setting_value('LOG_LEVEL'))
Logger(get_setting_value("LOG_LEVEL"))
pluginName = 'ARPSCAN'
LOG_PATH = logPath + '/plugins'
LOG_FILE = os.path.join(LOG_PATH, f'script.{pluginName}.log')
RESULT_FILE = os.path.join(LOG_PATH, f'last_result.{pluginName}.log')
pluginName = "ARPSCAN"
LOG_PATH = logPath + "/plugins"
LOG_FILE = os.path.join(LOG_PATH, f"script.{pluginName}.log")
RESULT_FILE = os.path.join(LOG_PATH, f"last_result.{pluginName}.log")
def main():
parser = argparse.ArgumentParser(description='Import devices from settings')
parser.add_argument('userSubnets', nargs='+', help="list of subnets with options")
values = parser.parse_args()
parser = argparse.ArgumentParser(description="Import devices from settings")
parser.add_argument("userSubnets", nargs="+", help="list of subnets with options")
values = parser.parse_args()
# Assuming Plugin_Objects is a class or function that reads data from the RESULT_FILE
# and returns a list of objects called 'devices'.
plugin_objects = Plugin_Objects(RESULT_FILE)
# Print a message to indicate that the script is starting.
mylog('verbose', [f'[{pluginName}] In script '])
mylog("verbose", [f"[{pluginName}] In script "])
# holds a list of user-submitted subnets.
# mylog('verbose', ['[ARP Scan] values.userSubnets: ', values.userSubnets])
# holds a list of user-submitted subnets.
# mylog('verbose', ['[ARP Scan] values.userSubnets: ', values.userSubnets])
# Extract the base64-encoded subnet information from the first element of the userSubnets list.
# The format of the element is assumed to be like 'userSubnets=b<base64-encoded-data>'.
userSubnetsParamBase64 = values.userSubnets[0].split('userSubnets=b')[1]
# The format of the element is assumed to be like 'userSubnets=<base64-encoded-data>'.
userSubnetsParamBase64 = values.userSubnets[0].split("userSubnets=")[1]
# Printing the extracted base64-encoded subnet information.
# mylog('verbose', ['[ARP Scan] userSubnetsParamBase64: ', userSubnetsParamBase64])
# mylog('verbose', ['[ARP Scan] userSubnetsParamBase64: ', userSubnetsParamBase64])
# Decode the base64-encoded subnet information to get the actual subnet information in ASCII format.
userSubnetsParam = base64.b64decode(userSubnetsParamBase64).decode('ascii')
userSubnetsParam = base64.b64decode(userSubnetsParamBase64).decode("ascii")
# Print the decoded subnet information.
mylog('verbose', [f'[{pluginName}] userSubnetsParam: ', userSubnetsParam])
mylog("verbose", [f"[{pluginName}] userSubnetsParam: ", userSubnetsParam])
# Check if the decoded subnet information contains multiple subnets separated by commas.
# If it does, split the string into a list of individual subnets.
# Otherwise, create a list with a single element containing the subnet information.
if ',' in userSubnetsParam:
subnets_list = userSubnetsParam.split(',')
if "," in userSubnetsParam:
subnets_list = userSubnetsParam.split(",")
else:
subnets_list = [userSubnetsParam]
# Create a database connection
db = DB() # instance of class DB
db.open()
# Execute the ARP scanning process on the list of subnets (whether it's one or multiple subnets).
# The function 'execute_arpscan' is assumed to be defined elsewhere in the code.
unique_devices = execute_arpscan(subnets_list)
for device in unique_devices:
plugin_objects.add_object(
primaryId = handleEmpty(device['mac']), # MAC (Device Name)
secondaryId = handleEmpty(device['ip']), # IP Address
watched1 = handleEmpty(device['ip']), # Device Name
watched2 = handleEmpty(device.get('hw', '')), # Vendor (assuming it's in the 'hw' field)
watched3 = handleEmpty(device.get('interface', '')), # Add the interface
watched4 = '',
extra = pluginName,
foreignKey = "")
primaryId=handleEmpty(device["mac"]), # MAC (Device Name)
secondaryId=handleEmpty(device["ip"]), # IP Address
watched1=handleEmpty(device["ip"]), # Device Name
watched2=handleEmpty(
device.get("hw", "")
), # Vendor (assuming it's in the 'hw' field)
watched3=handleEmpty(device.get("interface", "")), # Add the interface
watched4="",
extra=pluginName,
foreignKey="",
)
plugin_objects.write_result_file()
@@ -107,17 +97,19 @@ def execute_arpscan(userSubnets):
devices_list = []
# scan each interface
for interface in userSubnets :
arpscan_output = execute_arpscan_on_interface (interface)
for interface in userSubnets:
arpscan_output = execute_arpscan_on_interface(interface)
mylog("verbose", [f"[{pluginName}] arpscan_output: ", arpscan_output])
mylog('verbose', [f'[{pluginName}] arpscan_output: ', arpscan_output])
# Search IP + MAC + Vendor as regular expresion
re_ip = r'(?P<ip>((2[0-5]|1[0-9]|[0-9])?[0-9]\.){3}((2[0-5]|1[0-9]|[0-9])?[0-9]))'
re_mac = r'(?P<mac>([0-9a-fA-F]{2}[:-]){5}([0-9a-fA-F]{2}))'
re_hw = r'(?P<hw>.*)'
re_ip = (
r"(?P<ip>((2[0-5]|1[0-9]|[0-9])?[0-9]\.){3}((2[0-5]|1[0-9]|[0-9])?[0-9]))"
)
re_mac = r"(?P<mac>([0-9a-fA-F]{2}[:-]){5}([0-9a-fA-F]{2}))"
re_hw = r"(?P<hw>.*)"
re_pattern = re.compile(rf"{re_ip}\s+{re_mac}\s{re_hw}")
devices_list_tmp = [
@@ -127,44 +119,61 @@ def execute_arpscan(userSubnets):
devices_list += devices_list_tmp
# mylog('debug', ['[ARP Scan] Found: Devices including duplicates ', len(devices_list) ])
# Delete duplicate MAC
unique_mac = []
unique_devices = []
# mylog('debug', ['[ARP Scan] Found: Devices including duplicates ', len(devices_list) ])
for device in devices_list :
if device['mac'] not in unique_mac:
unique_mac.append(device['mac'])
unique_devices.append(device)
# Delete duplicate MAC
unique_mac = []
unique_devices = []
for device in devices_list:
if device["mac"] not in unique_mac:
unique_mac.append(device["mac"])
unique_devices.append(device)
# return list
mylog('verbose', [f'[{pluginName}] All devices List len:', len(devices_list)])
mylog('verbose', [f'[{pluginName}] Devices List:', devices_list])
mylog("verbose", [f"[{pluginName}] All devices List len:", len(devices_list)])
mylog("verbose", [f"[{pluginName}] Devices List:", devices_list])
mylog('verbose', [f'[{pluginName}] Found: Devices without duplicates ', len(unique_devices) ])
mylog(
"verbose",
[f"[{pluginName}] Found: Devices without duplicates ", len(unique_devices)],
)
return unique_devices
def execute_arpscan_on_interface(interface):
# Prepare command arguments
arpscan_args = get_setting_value('ARPSCAN_ARGS').split() + interface.split()
arpscan_args = get_setting_value("ARPSCAN_ARGS").split() + interface.split()
# Optional duration in seconds (0 = run once)
try:
scan_duration = int(get_setting_value('ARPSCAN_DURATION'))
scan_duration = int(get_setting_value("ARPSCAN_DURATION"))
except Exception:
scan_duration = 0 # default: single run
# Get timeout from plugin settings (default 30 seconds if not set)
try:
timeout_seconds = int(get_setting_value("ARPSCAN_RUN_TIMEOUT"))
except Exception:
timeout_seconds = 30
results = []
start_time = time.time()
while True:
try:
result = subprocess.check_output(arpscan_args, universal_newlines=True)
result = subprocess.check_output(
arpscan_args, universal_newlines=True, timeout=timeout_seconds
)
results.append(result)
except subprocess.CalledProcessError as e:
except subprocess.CalledProcessError:
result = ""
except subprocess.TimeoutExpired:
mylog(
"warning",
[f"[{pluginName}] arp-scan timed out after {timeout_seconds}s"],
)
result = ""
# stop looping if duration not set or expired
if scan_duration == 0 or (time.time() - start_time) > scan_duration:
@@ -175,10 +184,10 @@ def execute_arpscan_on_interface(interface):
return "\n".join(results)
# ===============================================================================
# BEGIN
# ===============================================================================
#===============================================================================
# BEGIN
#===============================================================================
if __name__ == '__main__':
if __name__ == "__main__":
main()

View File

@@ -2,7 +2,7 @@
import os
import sys
INSTALL_PATH = "/app"
INSTALL_PATH = os.getenv('NETALERTX_APP', '/app')
sys.path.extend([f"{INSTALL_PATH}/front/plugins", f"{INSTALL_PATH}/server"])
pluginName = "ASUSWRT"
@@ -15,8 +15,7 @@ from asusrouter.modules.connection import ConnectionState
from const import logPath
from helper import get_setting_value
from logger import Logger, mylog
from plugin_helper import (Plugin_Object, Plugin_Objects, decodeBase64,
handleEmpty)
from plugin_helper import (Plugin_Objects, handleEmpty)
from pytz import timezone
conf.tz = timezone(get_setting_value("TIMEZONE"))

View File

@@ -1,13 +1,11 @@
#!/usr/bin/env python3
import os
import sys
import json
import socket
import ipaddress
from zeroconf import Zeroconf, ServiceBrowser, ServiceInfo, InterfaceChoice, IPVersion
from zeroconf.asyncio import AsyncZeroconf
from zeroconf import Zeroconf
INSTALL_PATH = "/app"
INSTALL_PATH = os.getenv('NETALERTX_APP', '/app')
sys.path.extend([f"{INSTALL_PATH}/front/plugins", f"{INSTALL_PATH}/server"])
from plugin_helper import Plugin_Objects

View File

@@ -344,7 +344,7 @@
}
]
},
"default_value": "/app/config",
"default_value": "/data/config",
"options": [],
"localized": [
"name",
@@ -367,15 +367,15 @@
"description": [
{
"language_code": "en_us",
"string": "Where the <code>devices.csv</code> file should be saved. For example <code>/app/config</code>."
"string": "Where the <code>devices.csv</code> file should be saved. For example <code>/data/config</code>."
},
{
"language_code": "es_es",
"string": "Donde se debe guardar el archivo <code>devices.csv</code>. Por ejemplo <code>/app/config</code>."
"string": "Donde se debe guardar el archivo <code>devices.csv</code>. Por ejemplo <code>/data/config</code>."
},
{
"language_code": "de_de",
"string": "Wo die Datei <code>devices.csv</code> gespeichert werden soll. Zum Beispiel <code>/app/config</code>."
"string": "Wo die Datei <code>devices.csv</code> gespeichert werden soll. Zum Beispiel <code>/data/config</code>."
}
]
}

View File

@@ -1,23 +1,19 @@
#!/usr/bin/env python
import os
import pathlib
import argparse
import sys
import hashlib
import csv
import sqlite3
from io import StringIO
from datetime import datetime
# Register NetAlertX directories
INSTALL_PATH="/app"
INSTALL_PATH = os.getenv('NETALERTX_APP', '/app')
sys.path.extend([f"{INSTALL_PATH}/front/plugins", f"{INSTALL_PATH}/server"])
from plugin_helper import Plugin_Object, Plugin_Objects, decodeBase64
from logger import mylog, Logger, append_line_to_file
from helper import timeNowTZ, get_setting_value
from const import logPath, applicationPath, fullDbPath
from logger import mylog, Logger
from helper import get_setting_value
from const import logPath, fullDbPath
import conf
from pytz import timezone

View File

@@ -1,88 +1,110 @@
#!/usr/bin/env python
import os
import pathlib
import argparse
import sys
import hashlib
import csv
import sqlite3
from io import StringIO
from datetime import datetime
# Register NetAlertX directories
INSTALL_PATH="/app"
INSTALL_PATH = os.getenv("NETALERTX_APP", "/app")
sys.path.extend([f"{INSTALL_PATH}/front/plugins", f"{INSTALL_PATH}/server"])
from plugin_helper import Plugin_Object, Plugin_Objects, decodeBase64
from logger import mylog, Logger, append_line_to_file
from helper import timeNowTZ, get_setting_value
from const import logPath, applicationPath, fullDbPath
from logger import mylog, Logger
from helper import get_setting_value
from const import logPath, fullDbPath
import conf
from pytz import timezone
# Make sure the TIMEZONE for logging is correct
conf.tz = timezone(get_setting_value('TIMEZONE'))
conf.tz = timezone(get_setting_value("TIMEZONE"))
# Make sure log level is initialized correctly
Logger(get_setting_value('LOG_LEVEL'))
Logger(get_setting_value("LOG_LEVEL"))
pluginName = 'DBCLNP'
LOG_PATH = logPath + '/plugins'
LOG_FILE = os.path.join(LOG_PATH, f'script.{pluginName}.log')
RESULT_FILE = os.path.join(LOG_PATH, f'last_result.{pluginName}.log')
pluginName = "DBCLNP"
LOG_PATH = logPath + "/plugins"
LOG_FILE = os.path.join(LOG_PATH, f"script.{pluginName}.log")
RESULT_FILE = os.path.join(LOG_PATH, f"last_result.{pluginName}.log")
def main():
PLUGINS_KEEP_HIST = int(get_setting_value("PLUGINS_KEEP_HIST"))
HRS_TO_KEEP_NEWDEV = int(get_setting_value("HRS_TO_KEEP_NEWDEV"))
HRS_TO_KEEP_OFFDEV = int(get_setting_value("HRS_TO_KEEP_OFFDEV"))
DAYS_TO_KEEP_EVENTS = int(get_setting_value("DAYS_TO_KEEP_EVENTS"))
CLEAR_NEW_FLAG = get_setting_value("CLEAR_NEW_FLAG")
mylog('verbose', [f'[{pluginName}] In script'])
PLUGINS_KEEP_HIST = int(get_setting_value("PLUGINS_KEEP_HIST"))
HRS_TO_KEEP_NEWDEV = int(get_setting_value("HRS_TO_KEEP_NEWDEV"))
HRS_TO_KEEP_OFFDEV = int(get_setting_value("HRS_TO_KEEP_OFFDEV"))
DAYS_TO_KEEP_EVENTS = int(get_setting_value("DAYS_TO_KEEP_EVENTS"))
CLEAR_NEW_FLAG = get_setting_value("CLEAR_NEW_FLAG")
mylog("verbose", [f"[{pluginName}] In script"])
# Execute cleanup/upkeep
cleanup_database(
fullDbPath,
DAYS_TO_KEEP_EVENTS,
HRS_TO_KEEP_NEWDEV,
HRS_TO_KEEP_OFFDEV,
PLUGINS_KEEP_HIST,
CLEAR_NEW_FLAG,
)
mylog("verbose", [f"[{pluginName}] Cleanup complete"])
# Execute cleanup/upkeep
cleanup_database(fullDbPath, DAYS_TO_KEEP_EVENTS, HRS_TO_KEEP_NEWDEV, HRS_TO_KEEP_OFFDEV, PLUGINS_KEEP_HIST, CLEAR_NEW_FLAG)
mylog('verbose', [f'[{pluginName}] Cleanup complete'])
return 0
#===============================================================================
# ===============================================================================
# Cleanup / upkeep database
#===============================================================================
def cleanup_database (dbPath, DAYS_TO_KEEP_EVENTS, HRS_TO_KEEP_NEWDEV, HRS_TO_KEEP_OFFDEV, PLUGINS_KEEP_HIST, CLEAR_NEW_FLAG):
# ===============================================================================
def cleanup_database(
dbPath,
DAYS_TO_KEEP_EVENTS,
HRS_TO_KEEP_NEWDEV,
HRS_TO_KEEP_OFFDEV,
PLUGINS_KEEP_HIST,
CLEAR_NEW_FLAG,
):
"""
Cleaning out old records from the tables that don't need to keep all data.
"""
mylog('verbose', [f'[{pluginName}] Upkeep Database:' ])
mylog("verbose", [f"[{pluginName}] Upkeep Database:"])
# Connect to the App database
conn = sqlite3.connect(dbPath, timeout=30)
cursor = conn.cursor()
conn = sqlite3.connect(dbPath, timeout=30)
cursor = conn.cursor()
# -----------------------------------------------------
# Cleanup Online History
mylog('verbose', [f'[{pluginName}] Online_History: Delete all but keep latest 150 entries'])
cursor.execute ("""DELETE from Online_History where "Index" not in (
mylog(
"verbose",
[f"[{pluginName}] Online_History: Delete all but keep latest 150 entries"],
)
cursor.execute(
"""DELETE from Online_History where "Index" not in (
SELECT "Index" from Online_History
order by Scan_Date desc limit 150)""")
order by Scan_Date desc limit 150)"""
)
# -----------------------------------------------------
# Cleanup Events
mylog('verbose', [f'[{pluginName}] Events: Delete all older than {str(DAYS_TO_KEEP_EVENTS)} days (DAYS_TO_KEEP_EVENTS setting)'])
cursor.execute (f"""DELETE FROM Events
WHERE eve_DateTime <= date('now', '-{str(DAYS_TO_KEEP_EVENTS)} day')""")
# -----------------------------------------------------
mylog(
"verbose",
[
f"[{pluginName}] Events: Delete all older than {str(DAYS_TO_KEEP_EVENTS)} days (DAYS_TO_KEEP_EVENTS setting)"
],
)
cursor.execute(
f"""DELETE FROM Events
WHERE eve_DateTime <= date('now', '-{str(DAYS_TO_KEEP_EVENTS)} day')"""
)
# -----------------------------------------------------
# Trim Plugins_History entries to less than PLUGINS_KEEP_HIST setting per unique "Plugin" column entry
mylog('verbose', [f'[{pluginName}] Plugins_History: Trim Plugins_History entries to less than {str(PLUGINS_KEEP_HIST)} per Plugin (PLUGINS_KEEP_HIST setting)'])
mylog(
"verbose",
[
f"[{pluginName}] Plugins_History: Trim Plugins_History entries to less than {str(PLUGINS_KEEP_HIST)} per Plugin (PLUGINS_KEEP_HIST setting)"
],
)
# Build the SQL query to delete entries that exceed the limit per unique "Plugin" column entry
delete_query = f"""DELETE FROM Plugins_History
@@ -101,11 +123,16 @@ def cleanup_database (dbPath, DAYS_TO_KEEP_EVENTS, HRS_TO_KEEP_NEWDEV, HRS_TO_KE
# -----------------------------------------------------
# Trim Notifications entries to less than DBCLNP_NOTIFI_HIST setting
histCount = get_setting_value('DBCLNP_NOTIFI_HIST')
histCount = get_setting_value("DBCLNP_NOTIFI_HIST")
mylog('verbose', [f'[{pluginName}] Plugins_History: Trim Notifications entries to less than {histCount}'])
mylog(
"verbose",
[
f"[{pluginName}] Plugins_History: Trim Notifications entries to less than {histCount}"
],
)
# Build the SQL query to delete entries
# Build the SQL query to delete entries
delete_query = f"""DELETE FROM Notifications
WHERE "Index" NOT IN (
SELECT "Index"
@@ -119,14 +146,13 @@ def cleanup_database (dbPath, DAYS_TO_KEEP_EVENTS, HRS_TO_KEEP_NEWDEV, HRS_TO_KE
cursor.execute(delete_query)
# -----------------------------------------------------
# Trim Workflow entries to less than WORKFLOWS_AppEvents_hist setting
histCount = get_setting_value('WORKFLOWS_AppEvents_hist')
histCount = get_setting_value("WORKFLOWS_AppEvents_hist")
mylog('verbose', [f'[{pluginName}] Trim AppEvents to less than {histCount}'])
mylog("verbose", [f"[{pluginName}] Trim AppEvents to less than {histCount}"])
# Build the SQL query to delete entries
# Build the SQL query to delete entries
delete_query = f"""DELETE FROM AppEvents
WHERE "Index" NOT IN (
SELECT "Index"
@@ -141,38 +167,52 @@ def cleanup_database (dbPath, DAYS_TO_KEEP_EVENTS, HRS_TO_KEEP_NEWDEV, HRS_TO_KE
cursor.execute(delete_query)
conn.commit()
# -----------------------------------------------------
# Cleanup New Devices
if HRS_TO_KEEP_NEWDEV != 0:
mylog('verbose', [f'[{pluginName}] Devices: Delete all New Devices older than {str(HRS_TO_KEEP_NEWDEV)} hours (HRS_TO_KEEP_NEWDEV setting)'])
mylog(
"verbose",
[
f"[{pluginName}] Devices: Delete all New Devices older than {str(HRS_TO_KEEP_NEWDEV)} hours (HRS_TO_KEEP_NEWDEV setting)"
],
)
query = f"""DELETE FROM Devices WHERE devIsNew = 1 AND devFirstConnection < date('now', '-{str(HRS_TO_KEEP_NEWDEV)} hour')"""
mylog('verbose', [f'[{pluginName}] Query: {query} '])
cursor.execute (query)
mylog("verbose", [f"[{pluginName}] Query: {query} "])
cursor.execute(query)
# -----------------------------------------------------
# Cleanup Offline Devices
if HRS_TO_KEEP_OFFDEV != 0:
mylog('verbose', [f'[{pluginName}] Devices: Delete all New Devices older than {str(HRS_TO_KEEP_OFFDEV)} hours (HRS_TO_KEEP_OFFDEV setting)'])
mylog(
"verbose",
[
f"[{pluginName}] Devices: Delete all New Devices older than {str(HRS_TO_KEEP_OFFDEV)} hours (HRS_TO_KEEP_OFFDEV setting)"
],
)
query = f"""DELETE FROM Devices WHERE devPresentLastScan = 0 AND devLastConnection < date('now', '-{str(HRS_TO_KEEP_OFFDEV)} hour')"""
mylog('verbose', [f'[{pluginName}] Query: {query} '])
cursor.execute (query)
mylog("verbose", [f"[{pluginName}] Query: {query} "])
cursor.execute(query)
# -----------------------------------------------------
# Clear New Flag
if CLEAR_NEW_FLAG != 0:
mylog('verbose', [f'[{pluginName}] Devices: Clear "New Device" flag for all devices older than {str(CLEAR_NEW_FLAG)} hours (CLEAR_NEW_FLAG setting)'])
mylog(
"verbose",
[
f'[{pluginName}] Devices: Clear "New Device" flag for all devices older than {str(CLEAR_NEW_FLAG)} hours (CLEAR_NEW_FLAG setting)'
],
)
query = f"""UPDATE Devices SET devIsNew = 0 WHERE devIsNew = 1 AND date(devFirstConnection, '+{str(CLEAR_NEW_FLAG)} hour') < date('now')"""
# select * from Devices where devIsNew = 1 AND date(devFirstConnection, '+3 hour' ) < date('now')
mylog('verbose', [f'[{pluginName}] Query: {query} '])
# select * from Devices where devIsNew = 1 AND date(devFirstConnection, '+3 hour' ) < date('now')
mylog("verbose", [f"[{pluginName}] Query: {query} "])
cursor.execute(query)
# -----------------------------------------------------
# De-dupe (de-duplicate) from the Plugins_Objects table
# TODO This shouldn't be necessary - probably a concurrency bug somewhere in the code :(
mylog('verbose', [f'[{pluginName}] Plugins_Objects: Delete all duplicates'])
cursor.execute("""
# De-dupe (de-duplicate) from the Plugins_Objects table
# TODO This shouldn't be necessary - probably a concurrency bug somewhere in the code :(
mylog("verbose", [f"[{pluginName}] Plugins_Objects: Delete all duplicates"])
cursor.execute(
"""
DELETE FROM Plugins_Objects
WHERE rowid > (
SELECT MIN(rowid) FROM Plugins_Objects p2
@@ -181,8 +221,8 @@ def cleanup_database (dbPath, DAYS_TO_KEEP_EVENTS, HRS_TO_KEEP_NEWDEV, HRS_TO_KE
AND Plugins_Objects.Object_SecondaryID = p2.Object_SecondaryID
AND Plugins_Objects.UserData = p2.UserData
)
""")
"""
)
conn.commit()
@@ -190,18 +230,18 @@ def cleanup_database (dbPath, DAYS_TO_KEEP_EVENTS, HRS_TO_KEEP_NEWDEV, HRS_TO_KE
cursor.execute("PRAGMA wal_checkpoint(TRUNCATE);")
cursor.execute("PRAGMA wal_checkpoint(FULL);")
mylog('verbose', [f'[{pluginName}] WAL checkpoint executed to truncate file.'])
mylog("verbose", [f"[{pluginName}] WAL checkpoint executed to truncate file."])
# Shrink DB
mylog('verbose', [f'[{pluginName}] Shrink Database'])
cursor.execute ("VACUUM;")
mylog("verbose", [f"[{pluginName}] Shrink Database"])
cursor.execute("VACUUM;")
# Close the database connection
conn.close()
conn.close()
#===============================================================================
# ===============================================================================
# BEGIN
#===============================================================================
if __name__ == '__main__':
main()
# ===============================================================================
if __name__ == "__main__":
main()

View File

@@ -1,26 +1,17 @@
#!/usr/bin/env python
import os
import pathlib
import argparse
import sys
import hashlib
import csv
import subprocess
import re
import base64
import sqlite3
from io import StringIO
from datetime import datetime
# Register NetAlertX directories
INSTALL_PATH="/app"
INSTALL_PATH = os.getenv('NETALERTX_APP', '/app')
sys.path.extend([f"{INSTALL_PATH}/front/plugins", f"{INSTALL_PATH}/server"])
from plugin_helper import Plugin_Object, Plugin_Objects, decodeBase64
from logger import mylog, Logger, append_line_to_file
from helper import timeNowTZ, get_setting_value, check_IP_format
from const import logPath, applicationPath, fullDbPath
from logger import mylog, Logger
from helper import get_setting_value, check_IP_format
from const import logPath
import conf
from pytz import timezone

View File

@@ -1,21 +1,19 @@
#!/usr/bin/env python
from __future__ import unicode_literals
import pathlib
import subprocess
import argparse
import os
import sys
import chardet
# Register NetAlertX directories
INSTALL_PATH="/app"
INSTALL_PATH = os.getenv('NETALERTX_APP', '/app')
sys.path.extend([f"{INSTALL_PATH}/front/plugins", f"{INSTALL_PATH}/server"])
from plugin_helper import Plugin_Object, Plugin_Objects, handleEmpty, is_mac
from plugin_helper import Plugin_Objects, handleEmpty, is_mac
from logger import mylog, Logger
from dhcp_leases import DhcpLeases
from helper import timeNowTZ, get_setting_value
from helper import get_setting_value
import conf
from const import logPath
from pytz import timezone

View File

@@ -8,12 +8,12 @@ from datetime import datetime
import sys
# Register NetAlertX directories
INSTALL_PATH="/app"
INSTALL_PATH = os.getenv('NETALERTX_APP', '/app')
sys.path.extend([f"{INSTALL_PATH}/front/plugins", f"{INSTALL_PATH}/server"])
from plugin_helper import Plugin_Objects, Plugin_Object
from logger import mylog, Logger
from helper import timeNowTZ, get_setting_value
from helper import get_setting_value
import conf
from pytz import timezone
from const import logPath

View File

@@ -1,22 +1,17 @@
#!/usr/bin/env python
import os
import pathlib
import sys
import json
import sqlite3
import subprocess
# Define the installation path and extend the system path for plugin imports
INSTALL_PATH = "/app"
INSTALL_PATH = os.getenv('NETALERTX_APP', '/app')
sys.path.extend([f"{INSTALL_PATH}/front/plugins", f"{INSTALL_PATH}/server"])
from plugin_helper import Plugin_Object, Plugin_Objects, decodeBase64
from plugin_utils import get_plugins_configs
from plugin_helper import Plugin_Objects
from logger import mylog, Logger
from const import pluginsPath, fullDbPath, logPath
from helper import timeNowTZ, get_setting_value
from messaging.in_app import write_notification
from const import logPath
from helper import get_setting_value
from database import DB
from models.device_instance import DeviceInstance
import conf
@@ -118,7 +113,7 @@ def execute_name_lookup (ip, timeout):
except subprocess.CalledProcessError as e:
mylog('verbose', [f'[{pluginName}] ⚠ ERROR - {e.output}'])
except subprocess.TimeoutExpired as timeErr:
except subprocess.TimeoutExpired:
mylog('verbose', [f'[{pluginName}] TIMEOUT - the process forcefully terminated as timeout reached'])
if output == "": # check if the subprocess failed

View File

@@ -1,10 +1,7 @@
#!/usr/bin/env python
import os
import pathlib
import sys
import json
import sqlite3
from pytz import timezone
import asyncio
from datetime import datetime
@@ -17,15 +14,13 @@ from aiofreepybox.api.lan import Lan
from aiofreepybox.exceptions import NotOpenError, AuthorizationError
# Define the installation path and extend the system path for plugin imports
INSTALL_PATH = "/app"
INSTALL_PATH = os.getenv('NETALERTX_APP', '/app')
sys.path.extend([f"{INSTALL_PATH}/front/plugins", f"{INSTALL_PATH}/server"])
from plugin_helper import Plugin_Object, Plugin_Objects, decodeBase64
from plugin_utils import get_plugins_configs
from plugin_helper import Plugin_Objects
from logger import mylog, Logger
from const import pluginsPath, fullDbPath, logPath
from helper import timeNowTZ, get_setting_value
from messaging.in_app import write_notification
from const import logPath
from helper import get_setting_value
import conf
# Make sure the TIMEZONE for logging is correct
@@ -86,7 +81,8 @@ def map_device_type(type: str):
async def get_device_data(api_version: int, api_address: str, api_port: int):
# ensure existence of db path
data_dir = Path("/app/config/freeboxdb")
config_base = Path(os.getenv("NETALERTX_CONFIG", "/data/config"))
data_dir = config_base / "freeboxdb"
data_dir.mkdir(parents=True, exist_ok=True)
# Instantiate Freepybox class using default application descriptor

View File

@@ -3,25 +3,18 @@
# tbc
import os
import pathlib
import argparse
import subprocess
import sys
import hashlib
import csv
import sqlite3
import re
from io import StringIO
from datetime import datetime
# Register NetAlertX directories
INSTALL_PATH="/app"
INSTALL_PATH = os.getenv('NETALERTX_APP', '/app')
sys.path.extend([f"{INSTALL_PATH}/front/plugins", f"{INSTALL_PATH}/server"])
from plugin_helper import Plugin_Object, Plugin_Objects, decodeBase64
from logger import mylog, Logger, append_line_to_file
from helper import timeNowTZ, get_setting_value
from const import logPath, applicationPath, fullDbPath
from plugin_helper import Plugin_Objects
from logger import mylog, Logger
from helper import get_setting_value
from const import logPath
from database import DB
from models.device_instance import DeviceInstance
import conf
@@ -157,7 +150,7 @@ def execute_scan (ip, timeout, args):
return False, output
except subprocess.TimeoutExpired as timeErr:
except subprocess.TimeoutExpired:
mylog('verbose', [f'[{pluginName}] TIMEOUT - the process forcefully terminated as timeout reached'])
return False, output

View File

@@ -2,26 +2,19 @@
import os
import time
import pathlib
import argparse
import sys
import hashlib
import csv
import subprocess
import re
import base64
import sqlite3
from io import StringIO
from datetime import datetime
# Register NetAlertX directories
INSTALL_PATH="/app"
INSTALL_PATH = os.getenv('NETALERTX_APP', '/app')
sys.path.extend([f"{INSTALL_PATH}/front/plugins", f"{INSTALL_PATH}/server"])
from plugin_helper import Plugin_Object, Plugin_Objects, decodeBase64
from plugin_helper import Plugin_Objects
from logger import mylog, Logger, append_line_to_file
from helper import timeNowTZ, check_IP_format, get_setting_value
from const import logPath, applicationPath, fullDbPath
from const import logPath
import conf
from pytz import timezone

View File

@@ -2,17 +2,15 @@
import argparse
import os
import pathlib
import sys
from datetime import datetime
import speedtest
# Register NetAlertX directories
INSTALL_PATH="/app"
INSTALL_PATH = os.getenv('NETALERTX_APP', '/app')
sys.path.extend([f"{INSTALL_PATH}/front/plugins", f"{INSTALL_PATH}/server"])
from plugin_helper import Plugin_Objects
from logger import mylog, Logger, append_line_to_file
from logger import mylog, Logger
from helper import timeNowTZ, get_setting_value
import conf
from pytz import timezone

View File

@@ -1,25 +1,20 @@
#!/usr/bin/env python
import os
import pathlib
import sys
import json
import sqlite3
import subprocess
from datetime import datetime
from pytz import timezone
from functools import reduce
# Define the installation path and extend the system path for plugin imports
INSTALL_PATH = "/app"
INSTALL_PATH = os.getenv('NETALERTX_APP', '/app')
sys.path.extend([f"{INSTALL_PATH}/front/plugins", f"{INSTALL_PATH}/server"])
from plugin_helper import Plugin_Object, Plugin_Objects, decodeBase64, handleEmpty
from plugin_utils import get_plugins_configs
from plugin_helper import Plugin_Objects
from logger import mylog, Logger
from const import pluginsPath, fullDbPath, logPath
from helper import timeNowTZ, get_setting_value
from messaging.in_app import write_notification
from const import logPath
from helper import get_setting_value
import conf
# Make sure the TIMEZONE for logging is correct

View File

@@ -3,14 +3,14 @@ import os
import sys
INSTALL_PATH="/app"
INSTALL_PATH = os.getenv('NETALERTX_APP', '/app')
sys.path.extend([f"{INSTALL_PATH}/front/plugins", f"{INSTALL_PATH}/server"])
pluginName = 'LUCIRPC'
from plugin_helper import Plugin_Object, Plugin_Objects, decodeBase64
from logger import mylog, Logger, append_line_to_file
from helper import timeNowTZ, get_setting_value
from const import logPath, applicationPath
from plugin_helper import Plugin_Objects
from logger import mylog, Logger
from helper import get_setting_value
from const import logPath
import conf
from pytz import timezone

View File

@@ -1,24 +1,16 @@
#!/usr/bin/env python
import os
import pathlib
import argparse
import sys
import hashlib
import csv
import sqlite3
from io import StringIO
from datetime import datetime
from collections import deque
# Register NetAlertX directories
INSTALL_PATH="/app"
INSTALL_PATH = os.getenv('NETALERTX_APP', '/app')
sys.path.extend([f"{INSTALL_PATH}/front/plugins", f"{INSTALL_PATH}/server"])
from plugin_helper import Plugin_Object, Plugin_Objects, decodeBase64
from logger import mylog, Logger, append_line_to_file
from helper import timeNowTZ, get_setting_value
from const import logPath, applicationPath
from logger import mylog, Logger
from helper import get_setting_value
from const import logPath
from messaging.in_app import remove_old
import conf
from pytz import timezone

View File

@@ -4,7 +4,7 @@ import os
import sys
# Register NetAlertX directories
INSTALL_PATH="/app"
INSTALL_PATH = os.getenv('NETALERTX_APP', '/app')
sys.path.extend([f"{INSTALL_PATH}/front/plugins", f"{INSTALL_PATH}/server"])
from plugin_helper import Plugin_Objects

View File

@@ -1,22 +1,17 @@
#!/usr/bin/env python
import os
import pathlib
import sys
import json
import sqlite3
import subprocess
# Define the installation path and extend the system path for plugin imports
INSTALL_PATH = "/app"
INSTALL_PATH = os.getenv('NETALERTX_APP', '/app')
sys.path.extend([f"{INSTALL_PATH}/front/plugins", f"{INSTALL_PATH}/server"])
from plugin_helper import Plugin_Object, Plugin_Objects, decodeBase64
from plugin_utils import get_plugins_configs
from plugin_helper import Plugin_Objects
from logger import mylog, Logger
from const import pluginsPath, fullDbPath, logPath
from helper import timeNowTZ, get_setting_value
from messaging.in_app import write_notification
from const import logPath
from helper import get_setting_value
from database import DB
from models.device_instance import DeviceInstance
import conf
@@ -139,7 +134,7 @@ def execute_name_lookup (ip, timeout):
# else:
mylog('verbose', [f'[{pluginName}] ⚠ ERROR - {e.output}'])
except subprocess.TimeoutExpired as timeErr:
except subprocess.TimeoutExpired:
mylog('verbose', [f'[{pluginName}] TIMEOUT - the process forcefully terminated as timeout reached'])
if output == "": # check if the subprocess failed

View File

@@ -3,28 +3,21 @@
# tbc
import os
import pathlib
import argparse
import subprocess
import sys
import hashlib
import csv
import sqlite3
import re
import nmap
from io import StringIO
from datetime import datetime
# Register NetAlertX directories
INSTALL_PATH="/app"
INSTALL_PATH = os.getenv('NETALERTX_APP', '/app')
sys.path.extend([f"{INSTALL_PATH}/front/plugins", f"{INSTALL_PATH}/server"])
from plugin_helper import Plugin_Object, Plugin_Objects, decodeBase64
from logger import mylog, Logger, append_line_to_file
from helper import timeNowTZ, get_setting_value, extract_between_strings, extract_ip_addresses, extract_mac_addresses
from const import logPath, applicationPath, fullDbPath
from plugin_helper import Plugin_Objects
from logger import mylog, Logger
from helper import get_setting_value
from const import logPath
from database import DB
from models.device_instance import DeviceInstance
import conf
from pytz import timezone

View File

@@ -1,22 +1,18 @@
#!/usr/bin/env python
import os
import pathlib
import argparse
import sys
import re
import base64
import subprocess
from time import strftime
# Register NetAlertX directories
INSTALL_PATH="/app"
INSTALL_PATH = os.getenv('NETALERTX_APP', '/app')
sys.path.extend([f"{INSTALL_PATH}/front/plugins", f"{INSTALL_PATH}/server"])
from plugin_helper import Plugin_Object, Plugin_Objects, decodeBase64
from plugin_helper import Plugin_Objects, decodeBase64
from logger import mylog, Logger, append_line_to_file
from helper import timeNowTZ, get_setting_value
from const import logPath, applicationPath
from const import logPath
import conf
from pytz import timezone
@@ -128,7 +124,7 @@ def performNmapScan(deviceIPs, deviceMACs, timeoutSec, args):
# An error occured, handle it
mylog('none', ["[NMAP Scan] " ,e.output])
mylog('none', ["[NMAP Scan] ⚠ ERROR - Nmap Scan - check logs", progress])
except subprocess.TimeoutExpired as timeErr:
except subprocess.TimeoutExpired:
mylog('verbose', [f'[{pluginName}] Nmap TIMEOUT - the process forcefully terminated as timeout reached for ', ip, progress])
if output == "": # check if the subprocess failed

View File

@@ -3,25 +3,18 @@
# tbc
import os
import pathlib
import argparse
import subprocess
import sys
import hashlib
import csv
import sqlite3
import re
from io import StringIO
from datetime import datetime
# Register NetAlertX directories
INSTALL_PATH="/app"
INSTALL_PATH = os.getenv('NETALERTX_APP', '/app')
sys.path.extend([f"{INSTALL_PATH}/front/plugins", f"{INSTALL_PATH}/server"])
from plugin_helper import Plugin_Object, Plugin_Objects, decodeBase64
from logger import mylog, Logger, append_line_to_file
from helper import timeNowTZ, get_setting_value
from const import logPath, applicationPath, fullDbPath
from plugin_helper import Plugin_Objects
from logger import mylog, Logger
from helper import get_setting_value
from const import logPath
from database import DB
from models.device_instance import DeviceInstance
import conf
@@ -140,7 +133,7 @@ def execute_nslookup (ip, timeout):
# Handle other errors here
# mylog('verbose', [f'[{pluginName}] ⚠ ERROR - check logs'])
except subprocess.TimeoutExpired as timeErr:
except subprocess.TimeoutExpired:
mylog('verbose', [f'[{pluginName}] TIMEOUT - the process forcefully terminated as timeout reached'])
if output == "": # check if the subprocess failed

View File

@@ -21,12 +21,7 @@ __version__ = "1.3" # fix detection of the default gateway IP address that woul
# curl -X POST -d '{"host":{"enabled":"1","hostname":"test","domain":"testdomain.com","rr":"A","mxprio":"","mx":"","server":"10.0.1.1","description":""}}' -H "Content-Type: application/json" -k -u $OPNS_KEY:$OPNS_SECRET https://$IPFW/api/unbound/settings/AddHostOverride
#
import os
import pathlib
import sys
import json
import sqlite3
import tplink_omada_client
import importlib.util
import time
import io
import re
@@ -37,15 +32,13 @@ import multiprocessing
# Define the installation path and extend the system path for plugin imports
INSTALL_PATH = "/app"
INSTALL_PATH = os.getenv('NETALERTX_APP', '/app')
sys.path.extend([f"{INSTALL_PATH}/front/plugins", f"{INSTALL_PATH}/server"])
from plugin_helper import Plugin_Object, Plugin_Objects, decodeBase64
from plugin_utils import get_plugins_configs
from plugin_helper import Plugin_Objects
from logger import mylog, Logger
from const import pluginsPath, fullDbPath, logPath
from helper import timeNowTZ, get_setting_value
from messaging.in_app import write_notification
from const import logPath
from helper import get_setting_value
from pytz import timezone
import conf
@@ -151,7 +144,7 @@ def callomada(myargs):
with redirect_stdout(mf):
bar = omada(myargs)
omada_output = mf.getvalue()
except Exception as e:
except Exception:
mylog(
"minimal",
[f"[{pluginName}] ERROR WHILE CALLING callomada:{arguments}\n {mf}"],
@@ -172,7 +165,7 @@ def extract_mac_addresses(text):
def find_default_gateway_ip():
# Get the routing table
from scapy.all import conf, Route, sr1, IP, ICMP
from scapy.all import conf
routing_table = conf.route.routes
for route in routing_table:

View File

@@ -32,7 +32,7 @@ from datetime import datetime
from typing import Literal, Any, Dict
# Define the installation path and extend the system path for plugin imports
INSTALL_PATH = "/app"
INSTALL_PATH = os.getenv('NETALERTX_APP', '/app')
sys.path.extend([f"{INSTALL_PATH}/front/plugins", f"{INSTALL_PATH}/server"])
from plugin_helper import Plugin_Objects, is_typical_router_ip, is_mac
@@ -395,7 +395,7 @@ class OmadaData:
response_result = normalized_input_data.get("response_result", {})
for entry in response_result:
if len(entry) == 0:
OmadaHelper.minimal(f"Skipping entry, missing data.")
OmadaHelper.minimal("Skipping entry, missing data.")
continue
OmadaHelper.verbose(f"Making entry for: {entry['mac_address']}")

View File

@@ -1,19 +1,19 @@
from time import strftime
import pytz
from pytz import timezone, all_timezones, UnknownTimeZoneError
from pytz import all_timezones
import sys
import os
import re
import base64
import json
from datetime import datetime
INSTALL_PATH = "/app"
INSTALL_PATH = os.getenv('NETALERTX_APP', '/app')
sys.path.append(f"{INSTALL_PATH}/front/plugins")
sys.path.append(f'{INSTALL_PATH}/server')
from logger import mylog, Logger
from const import confFileName, default_tz
from logger import mylog
from const import default_tz, fullConfPath
#-------------------------------------------------------------------------------
def read_config_file():
@@ -22,7 +22,7 @@ def read_config_file():
config_dir[key]
"""
filename = f'{INSTALL_PATH}/config/' + confFileName
filename = fullConfPath
print('[plugin_helper] reading config file')

View File

@@ -1,20 +1,19 @@
#!/usr/bin/env python
from __future__ import unicode_literals
import pathlib
import subprocess
import argparse
import os
import sys
# Register NetAlertX directories
INSTALL_PATH="/app"
INSTALL_PATH = os.getenv('NETALERTX_APP', '/app')
sys.path.extend([f"{INSTALL_PATH}/front/plugins", f"{INSTALL_PATH}/server"])
from plugin_helper import Plugin_Object, Plugin_Objects, decodeBase64, handleEmpty, normalize_mac
from plugin_helper import Plugin_Objects, handleEmpty, normalize_mac
from logger import mylog, Logger
from helper import timeNowTZ, get_setting_value
from const import logPath, applicationPath
from helper import get_setting_value
from const import logPath
import conf
from pytz import timezone
@@ -94,7 +93,7 @@ def main():
foreignKey = handleEmpty(macAddress) # Use the primary ID as the foreign key
)
else:
mylog('verbose', [f'[SNMPDSC] ipStr does not seem to contain a valid IP:', ipStr])
mylog('verbose', ['[SNMPDSC] ipStr does not seem to contain a valid IP:', ipStr])
elif line.startswith('ipNetToMediaPhysAddress'):

View File

@@ -45,7 +45,8 @@ function jsonResponse($status, $data = '', $message = '') {
if ($method === 'GET') {
checkAuthorization($method);
$file_path = "/app/api/table_devices.json";
$apiRoot = getenv('NETALERTX_API') ?: '/tmp/api';
$file_path = rtrim($apiRoot, '/') . '/table_devices.json';
$data = file_get_contents($file_path);
@@ -68,7 +69,8 @@ else if ($method === 'POST') {
$node_name = $_POST['node_name'] ?? '';
$plugin = $_POST['plugin'] ?? '';
$storage_path = "/app/log/plugins/";
$logRoot = getenv('NETALERTX_PLUGINS_LOG') ?: (rtrim(getenv('NETALERTX_LOG') ?: '/tmp/log', '/') . '/plugins');
$storage_path = rtrim($logRoot, '/');
// // check location
// if (!is_dir($storage_path)) {

View File

@@ -1,9 +1,7 @@
#!/usr/bin/env python
import os
import pathlib
import sys
import hashlib
import requests
import json
import sqlite3
@@ -11,13 +9,13 @@ import base64
# Define the installation path and extend the system path for plugin imports
INSTALL_PATH = "/app"
INSTALL_PATH = os.getenv('NETALERTX_APP', '/app')
sys.path.extend([f"{INSTALL_PATH}/front/plugins", f"{INSTALL_PATH}/server"])
from plugin_helper import Plugin_Object, Plugin_Objects, decodeBase64
from plugin_helper import Plugin_Objects
from plugin_utils import get_plugins_configs, decode_and_rename_files
from logger import mylog, Logger
from const import pluginsPath, fullDbPath, logPath
from const import fullDbPath, logPath
from helper import timeNowTZ, get_setting_value
from crypto_utils import encrypt_data
from messaging.in_app import write_notification
@@ -270,8 +268,8 @@ def main():
# ------------------------------------------------------------------
# Data retrieval methods
api_endpoints = [
f"/sync", # New Python-based endpoint
f"/plugins/sync/hub.php" # Legacy PHP endpoint
"/sync", # New Python-based endpoint
"/plugins/sync/hub.php" # Legacy PHP endpoint
]
# send data to the HUB

View File

@@ -1,24 +1,20 @@
#!/usr/bin/env python
import os
import pathlib
import sys
import json
import sqlite3
from pytz import timezone
from unifi_sm_api.api import SiteManagerAPI
# Define the installation path and extend the system path for plugin imports
INSTALL_PATH = "/app"
INSTALL_PATH = os.getenv('NETALERTX_APP', '/app')
sys.path.extend([f"{INSTALL_PATH}/front/plugins", f"{INSTALL_PATH}/server"])
from plugin_helper import Plugin_Object, Plugin_Objects, decodeBase64, decode_settings_base64
from plugin_utils import get_plugins_configs
from plugin_helper import Plugin_Objects, decode_settings_base64
from logger import mylog, Logger
from const import pluginsPath, fullDbPath, logPath
from helper import timeNowTZ, get_setting_value
from const import logPath
from helper import get_setting_value
from messaging.in_app import write_notification
import conf
# Make sure the TIMEZONE for logging is correct

View File

@@ -2,26 +2,21 @@
# Inspired by https://github.com/stevehoek/Pi.Alert
from __future__ import unicode_literals
from time import strftime
import argparse
import logging
import pathlib
import os
import json
import sys
import requests
from requests import Request, Session, packages
from requests.packages.urllib3.exceptions import InsecureRequestWarning
import urllib3
from urllib3.exceptions import InsecureRequestWarning
from pyunifi.controller import Controller
# Register NetAlertX directories
INSTALL_PATH="/app"
INSTALL_PATH = os.getenv('NETALERTX_APP', '/app')
sys.path.extend([f"{INSTALL_PATH}/front/plugins", f"{INSTALL_PATH}/server"])
from plugin_helper import Plugin_Object, Plugin_Objects, rmBadChars, is_typical_router_ip, is_mac
from plugin_helper import Plugin_Objects, rmBadChars, is_typical_router_ip, is_mac
from logger import mylog, Logger
from helper import timeNowTZ, get_setting_value, normalize_string
from helper import get_setting_value, normalize_string
import conf
from pytz import timezone
from const import logPath
@@ -39,7 +34,7 @@ LOG_FILE = os.path.join(LOG_PATH, f'script.{pluginName}.log')
RESULT_FILE = os.path.join(LOG_PATH, f'last_result.{pluginName}.log')
LOCK_FILE = os.path.join(LOG_PATH, f'full_run.{pluginName}.lock')
requests.packages.urllib3.disable_warnings(InsecureRequestWarning)
urllib3.disable_warnings(InsecureRequestWarning)

View File

@@ -1,23 +1,17 @@
#!/usr/bin/env python
import os
import pathlib
import argparse
import sys
import hashlib
import subprocess
import csv
import sqlite3
from io import StringIO
from datetime import datetime
# Register NetAlertX directories
INSTALL_PATH="/app"
INSTALL_PATH = os.getenv('NETALERTX_APP', '/app')
sys.path.extend([f"{INSTALL_PATH}/front/plugins", f"{INSTALL_PATH}/server"])
from plugin_helper import Plugin_Object, Plugin_Objects, decodeBase64, handleEmpty
from logger import mylog, Logger, append_line_to_file
from helper import timeNowTZ, get_setting_value
from plugin_helper import Plugin_Objects, handleEmpty
from logger import mylog, Logger
from helper import get_setting_value
from const import logPath, applicationPath, fullDbPath
from scan.device_handling import query_MAC_vendor
import conf

View File

@@ -1,23 +1,18 @@
#!/usr/bin/env python
import os
import pathlib
import sys
import json
import sqlite3
from pytz import timezone
from wakeonlan import send_magic_packet
# Define the installation path and extend the system path for plugin imports
INSTALL_PATH = "/app"
INSTALL_PATH = os.getenv('NETALERTX_APP', '/app')
sys.path.extend([f"{INSTALL_PATH}/front/plugins", f"{INSTALL_PATH}/server"])
from plugin_helper import Plugin_Object, Plugin_Objects, decodeBase64
from plugin_utils import get_plugins_configs
from plugin_helper import Plugin_Objects
from logger import mylog, Logger
from const import pluginsPath, fullDbPath, logPath
from helper import timeNowTZ, get_setting_value
from messaging.in_app import write_notification
from const import logPath
from helper import get_setting_value
from database import DB
from models.device_instance import DeviceInstance
import conf

View File

@@ -1,22 +1,20 @@
#!/usr/bin/env python
# Based on the work of https://github.com/leiweibau/Pi.Alert
import argparse
import requests
from requests.exceptions import SSLError, Timeout, RequestException
import pathlib
import sys
import os
from requests.packages.urllib3.exceptions import InsecureRequestWarning
import urllib3
from urllib3.exceptions import InsecureRequestWarning
# Register NetAlertX directories
INSTALL_PATH="/app"
INSTALL_PATH = os.getenv('NETALERTX_APP', '/app')
sys.path.extend([f"{INSTALL_PATH}/front/plugins", f"{INSTALL_PATH}/server"])
from plugin_helper import Plugin_Objects
from datetime import datetime
from const import logPath
from helper import timeNowTZ, get_setting_value
from helper import get_setting_value
import conf
from pytz import timezone
from logger import mylog, Logger
@@ -54,7 +52,7 @@ def check_services_health(site):
mylog('verbose', [f'[{pluginName}] Checking {site}'])
requests.packages.urllib3.disable_warnings(InsecureRequestWarning)
urllib3.disable_warnings(InsecureRequestWarning)
try:
resp = requests.get(site, verify=False, timeout=get_setting_value('WEBMON_RUN_TIMEOUT'), headers={"User-Agent": "NetAlertX"})

View File

@@ -9,15 +9,28 @@ require 'php/templates/header.php';
ini_set ('max_execution_time','30');
// check permissions
$dbPath = "../db/app.db";
$confPath = "../config/app.conf";
// Use environment-aware paths with fallback to legacy locations
$dbFolderPath = rtrim(getenv('NETALERTX_DB') ?: '/data/db', '/');
$configFolderPath = rtrim(getenv('NETALERTX_CONFIG') ?: '/data/config', '/');
$dbPath = $dbFolderPath . '/app.db';
$confPath = $configFolderPath . '/app.conf';
// Fallback to legacy paths if new locations don't exist
if (!file_exists($dbPath) && file_exists('../db/app.db')) {
$dbPath = '../db/app.db';
}
if (!file_exists($confPath) && file_exists('../config/app.conf')) {
$confPath = '../config/app.conf';
}
checkPermissions([$dbPath, $confPath]);
// get settings from the API json file
// path to your JSON file
$file = '../api/table_settings.json';
$apiRoot = rtrim(getenv('NETALERTX_API') ?: '/tmp/api', '/');
$file = $apiRoot . '/table_settings.json';
// put the content of the file in a variable
$data = file_get_contents($file);
// JSON decode