mirror of
https://github.com/jokob-sk/NetAlertX.git
synced 2025-12-07 09:36:05 -08:00
More rename work
This commit is contained in:
@@ -105,7 +105,7 @@ if ($ENABLED_DARKMODE === True) {
|
||||
<body class="hold-transition login-page">
|
||||
<div class="login-box login-custom">
|
||||
<div class="login-logo">
|
||||
<a href="/index2.php">Net<b>Alert</b><sup>X</sup></a>
|
||||
<a href="/index2.php">Net <b>Alert</b><sup>x</sup></a>
|
||||
</div>
|
||||
<!-- /.login-logo -->
|
||||
<div class="login-box-body">
|
||||
|
||||
@@ -2,7 +2,7 @@
|
||||
* NetAlertX
|
||||
* Open Source Network Guard / WIFI & LAN intrusion detector
|
||||
*
|
||||
* pialert_common.js - Front module. Common Javascript functions
|
||||
* common.js - Front module. Common Javascript functions
|
||||
*-------------------------------------------------------------------------------
|
||||
# Puche 2021 / 2022+ jokob jokob@duck.com GNU GPLv3
|
||||
----------------------------------------------------------------------------- */
|
||||
@@ -1306,7 +1306,7 @@ setTimeout(() => {
|
||||
}, 10000);
|
||||
|
||||
|
||||
console.log("init pialert_common.js");
|
||||
console.log("init common.js");
|
||||
|
||||
|
||||
|
||||
@@ -935,7 +935,7 @@ window.onload = function asyncFooter()
|
||||
scrollDown();
|
||||
initializeTabs();
|
||||
|
||||
$("#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/pi.alert/main?logo=github"></a>');
|
||||
$("#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>');
|
||||
|
||||
$("#lastDockerUpdate").append(
|
||||
'<a href="https://github.com/jokob-sk/NetAlertX/releases" target="_blank"><img alt="Docker last pushed" src="https://img.shields.io/github/v/release/jokob-sk/NetAlertX?color=0aa8d2&logoColor=fff&logo=GitHub&label=Latest"></a>');
|
||||
|
||||
@@ -331,8 +331,9 @@ function deleteActHistory() {
|
||||
//------------------------------------------------------------------------------
|
||||
function PiaBackupDBtoArchive() {
|
||||
// prepare fast Backup
|
||||
$file = '../../../db/pialert.db';
|
||||
$newfile = '../../../db/pialert.db.latestbackup';
|
||||
$dbfilename = 'pialert.db'
|
||||
$file = '../../../db/'.$dbfilename;
|
||||
$newfile = '../../../db/'.$dbfilename.'.latestbackup';
|
||||
|
||||
// copy files as a fast Backup
|
||||
if (!copy($file, $newfile)) {
|
||||
@@ -341,14 +342,14 @@ function PiaBackupDBtoArchive() {
|
||||
// Create archive with actual date
|
||||
$Pia_Archive_Name = 'pialertdb_'.date("Ymd_His").'.zip';
|
||||
$Pia_Archive_Path = '../../../db/';
|
||||
exec('zip -j '.$Pia_Archive_Path.$Pia_Archive_Name.' ../../../db/pialert.db', $output);
|
||||
exec('zip -j '.$Pia_Archive_Path.$Pia_Archive_Name.' ../../../db/'.$dbfilename, $output);
|
||||
// chheck if archive exists
|
||||
if (file_exists($Pia_Archive_Path.$Pia_Archive_Name) && filesize($Pia_Archive_Path.$Pia_Archive_Name) > 0) {
|
||||
echo lang('BackDevices_Backup_okay').': ('.$Pia_Archive_Name.')';
|
||||
unlink($newfile);
|
||||
echo("<meta http-equiv='refresh' content='1'>");
|
||||
} else {
|
||||
echo lang('BackDevices_Backup_Failed').' (pialert.db.latestbackup)';
|
||||
echo lang('BackDevices_Backup_Failed').' ('.$dbfilename.'.latestbackup)';
|
||||
}
|
||||
}
|
||||
|
||||
@@ -359,17 +360,17 @@ function PiaBackupDBtoArchive() {
|
||||
//------------------------------------------------------------------------------
|
||||
function PiaRestoreDBfromArchive() {
|
||||
// prepare fast Backup
|
||||
$file = '../../../db/pialert.db';
|
||||
$oldfile = '../../../db/pialert.db.prerestore';
|
||||
$file = '../../../db/'.$dbfilename;
|
||||
$oldfile = '../../../db/'.$dbfilename.'.prerestore';
|
||||
|
||||
// copy files as a fast Backup
|
||||
if (!copy($file, $oldfile)) {
|
||||
echo lang('BackDevices_Restore_CopError');
|
||||
} else {
|
||||
// extract latest archive and overwrite the actual pialert.db
|
||||
// extract latest archive and overwrite the actual .db
|
||||
$Pia_Archive_Path = '../../../db/';
|
||||
exec('/bin/ls -Art '.$Pia_Archive_Path.'*.zip | /bin/tail -n 1 | /usr/bin/xargs -n1 /bin/unzip -o -d ../../../db/', $output);
|
||||
// check if the pialert.db exists
|
||||
// check if the .db exists
|
||||
if (file_exists($file)) {
|
||||
echo lang('BackDevices_Restore_okay');
|
||||
unlink($oldfile);
|
||||
@@ -388,7 +389,7 @@ function PiaPurgeDBBackups() {
|
||||
|
||||
$Pia_Archive_Path = '../../../db';
|
||||
$Pia_Backupfiles = array();
|
||||
$files = array_diff(scandir($Pia_Archive_Path, SCANDIR_SORT_DESCENDING), array('.', '..', 'pialert.db', 'pialertdb-reset.zip'));
|
||||
$files = array_diff(scandir($Pia_Archive_Path, SCANDIR_SORT_DESCENDING), array('.', '..', $dbfilename, 'pialertdb-reset.zip'));
|
||||
|
||||
foreach ($files as &$item)
|
||||
{
|
||||
|
||||
@@ -292,7 +292,7 @@ function saveSettings()
|
||||
}
|
||||
|
||||
|
||||
// generate a clean pialert.conf file
|
||||
// generate a clean .conf file
|
||||
$groups = [];
|
||||
|
||||
$txt = "";
|
||||
|
||||
@@ -30,7 +30,7 @@ require dirname(__FILE__).'/security.php';
|
||||
<!-- jQuery 3 -->
|
||||
<script src="lib/AdminLTE/bower_components/jquery/dist/jquery.min.js"></script>
|
||||
|
||||
<script src="js/pialert_common.js"></script>
|
||||
<script src="js/common.js"></script>
|
||||
|
||||
<!-- Bootstrap 3.3.7 -->
|
||||
<link rel="stylesheet" href="lib/AdminLTE/bower_components/bootstrap/dist/css/bootstrap.min.css">
|
||||
|
||||
0
front/php/templates/language/de_de.json
Normal file → Executable file
0
front/php/templates/language/de_de.json
Normal file → Executable file
@@ -55,13 +55,13 @@
|
||||
|----------------------|----------------------| ----------------------|
|
||||
| ![Screen 4][screen4] | ![Screen 5][screen5] |
|
||||
|
||||
PiAlert comes with a plugin system to feed events from third-party scripts into the UI and then send notifications, if desired. The highlighted core functionality this plugin system supports, is:
|
||||
NetAlertX comes with a plugin system to feed events from third-party scripts into the UI and then send notifications, if desired. The highlighted core functionality this plugin system supports, is:
|
||||
|
||||
* dynamic creation of a simple UI to interact with the discovered objects,
|
||||
* filtering of displayed values in the Devices UI
|
||||
* surface settings of plugins in the UI,
|
||||
* different column types for reported values to e.g. link back to a device
|
||||
* import objects into existing PiAlert database tables
|
||||
* import objects into existing NetAlertX database tables
|
||||
|
||||
> (Currently, update/overwriting of existing objects is not supported.)
|
||||
|
||||
@@ -69,7 +69,7 @@ Example use cases for plugins could be:
|
||||
|
||||
* Monitor a web service and alert me if it's down
|
||||
* Import devices from dhcp.leases files instead/complementary to using PiHole or arp-scans
|
||||
* Creating ad-hoc UI tables from existing data in the PiAlert database, e.g. to show all open ports on devices, to list devices that disconnected in the last hour, etc.
|
||||
* Creating ad-hoc UI tables from existing data in the NetAlertX database, e.g. to show all open ports on devices, to list devices that disconnected in the last hour, etc.
|
||||
* Using other device discovery methods on the network and importing the data as new devices
|
||||
* Creating a script to create FAKE devices based on user input via custom settings
|
||||
* ...at this point the limitation is mostly the creativity rather than the capability (there might be edge cases and a need to support more form controls for user input off custom settings, but you probably get the idea)
|
||||
@@ -104,7 +104,7 @@ These issues will be hopefully fixed with time, so please don't report them. Ins
|
||||
|----------------------|----------------------|----------------------|
|
||||
| `config.json` | yes | Contains the plugin configuration (manifest) including the settings available to the user. |
|
||||
| `script.py` | no | The Python script itself. You may call any valid linux command. |
|
||||
| `last_result.log` | no | The file used to interface between PiAlert and the plugin. Required for a script plugin if you want to feed data into the app. |
|
||||
| `last_result.log` | no | The file used to interface between NetAlertX and the plugin. Required for a script plugin if you want to feed data into the app. |
|
||||
| `script.log` | no | Logging output (recommended) |
|
||||
| `README.md` | yes | Any setup considerations or overview |
|
||||
|
||||
@@ -124,7 +124,7 @@ More on specifics below.
|
||||
| 4 | `Watched_Value2` | no | As above |
|
||||
| 5 | `Watched_Value3` | no | As above |
|
||||
| 6 | `Watched_Value4` | no | As above |
|
||||
| 7 | `Extra` | no | Any other data you want to pass and display in PiAlert and the notifications |
|
||||
| 7 | `Extra` | no | Any other data you want to pass and display in NetAlertX and the notifications |
|
||||
| 8 | `ForeignKey` | no | A foreign key that can be used to link to the parent object (usually a MAC address) |
|
||||
|
||||
> [!NOTE]
|
||||
@@ -132,7 +132,7 @@ More on specifics below.
|
||||
|
||||
# config.json structure
|
||||
|
||||
The `config.json` file is the manifest of the plugin. It contains mainly settings definitions and the mapping of Plugin objects to PiAlert objects.
|
||||
The `config.json` file is the manifest of the plugin. It contains mainly settings definitions and the mapping of Plugin objects to NetAlertX objects.
|
||||
|
||||
## Supported data sources
|
||||
|
||||
@@ -141,7 +141,7 @@ Currently, these data sources are supported (valid `data_source` value).
|
||||
| Name | `data_source` value | Needs to return a "table"* | Overview (more details on this page below) |
|
||||
|----------------------|----------------------|----------------------|----------------------|
|
||||
| Script | `script` | no | Executes any linux command in the `CMD` setting. |
|
||||
| Pialert DB query | `pialert-db-query` | yes | Executes a SQL query on the PiAlert database in the `CMD` setting. |
|
||||
| NetAlertX DB query | `pialert-db-query` | yes | Executes a SQL query on the NetAlertX database in the `CMD` setting. |
|
||||
| Template | `template` | no | Used to generate internal settings, such as default values. |
|
||||
| External SQLite DB query | `sqlite-db-query` | yes | Executes a SQL query from the `CMD` setting on an external SQLite database mapped in the `DB_PATH` setting. |
|
||||
| Plugin type | `plugin_type` | no | Specifies the type of the plugin and in which section the Plugin settings are displayed ( one of `general/system/scanner/other/publisher` ). |
|
||||
@@ -255,7 +255,7 @@ In most cases, it is used to initialize settings. Check the `newdev_template` pl
|
||||
|
||||
### "data_source": "sqlite-db-query"
|
||||
|
||||
You can execute a SQL query on an external database connected to the current PiALert database via a temporary `EXTERNAL_<unique prefix>.` prefix.
|
||||
You can execute a SQL query on an external database connected to the current NetAlertX database via a temporary `EXTERNAL_<unique prefix>.` prefix.
|
||||
|
||||
For example for `PIHOLE` (`"unique_prefix": "PIHOLE"`) it is `EXTERNAL_PIHOLE.`. The external SQLite database file has to be mapped in the container to the path specified in the `DB_PATH` setting:
|
||||
|
||||
@@ -359,7 +359,7 @@ Plugin entries can be filtered in the UI based on values entered into filter fie
|
||||
|
||||
### 🗺 Mapping the plugin results into a database table
|
||||
|
||||
Plugin results are always inserted into the standard `Plugin_Objects` database table. Optionally, PiAlert can take the results of the plugin execution, and insert these results into an additional database table. This is enabled by with the property `"mapped_to_table"` in the `config.json` file. The mapping of the columns is defined in the `database_column_definitions` array.
|
||||
Plugin results are always inserted into the standard `Plugin_Objects` database table. Optionally, NetAlertX can take the results of the plugin execution, and insert these results into an additional database table. This is enabled by with the property `"mapped_to_table"` in the `config.json` file. The mapping of the columns is defined in the `database_column_definitions` array.
|
||||
|
||||
> [!NOTE]
|
||||
> If results are mapped to the `CurrentScan` table, the data is then included into the regular scan loop, so for example notification for devices are sent out.
|
||||
@@ -367,7 +367,7 @@ Plugin results are always inserted into the standard `Plugin_Objects` database t
|
||||
|
||||
>🔍 Example:
|
||||
>
|
||||
>For example, this approach is used to implement the `DHCPLSS` plugin. The script parses all supplied "dhcp.leases" files, gets the results in the generic table format outlined in the "Column order and values" section above, takes individual values, and inserts them into the `CurrentScan` database table in the PiAlert database. All this is achieved by:
|
||||
>For example, this approach is used to implement the `DHCPLSS` plugin. The script parses all supplied "dhcp.leases" files, gets the results in the generic table format outlined in the "Column order and values" section above, takes individual values, and inserts them into the `CurrentScan` database table in the NetAlertX database. All this is achieved by:
|
||||
>
|
||||
>1. Specifying the database table into which the results are inserted by defining `"mapped_to_table": "CurrentScan"` in the root of the `config.json` file as shown below:
|
||||
>
|
||||
@@ -382,7 +382,7 @@ Plugin results are always inserted into the standard `Plugin_Objects` database t
|
||||
> ...
|
||||
>}
|
||||
>```
|
||||
>2. Defining the target column with the `mapped_to_column` property for individual columns in the `database_column_definitions` array of the `config.json` file. For example in the `DHCPLSS` plugin, I needed to map the value of the `Object_PrimaryID` column returned by the plugin, to the `cur_MAC` column in the PiAlert database table `CurrentScan`. Notice the `"mapped_to_column": "cur_MAC"` key-value pair in the sample below.
|
||||
>2. Defining the target column with the `mapped_to_column` property for individual columns in the `database_column_definitions` array of the `config.json` file. For example in the `DHCPLSS` plugin, I needed to map the value of the `Object_PrimaryID` column returned by the plugin, to the `cur_MAC` column in the NetAlertX database table `CurrentScan`. Notice the `"mapped_to_column": "cur_MAC"` key-value pair in the sample below.
|
||||
>
|
||||
>```json
|
||||
>{
|
||||
@@ -401,7 +401,7 @@ Plugin results are always inserted into the standard `Plugin_Objects` database t
|
||||
> }
|
||||
>```
|
||||
>
|
||||
>3. That's it. PiAlert takes care of the rest. It loops thru the objects discovered by the plugin, takes the results line-by-line, and inserts them into the database table specified in `"mapped_to_table"`. The columns are translated from the generic plugin columns to the target table columns via the `"mapped_to_column"` property in the column definitions.
|
||||
>3. That's it. The app takes care of the rest. It loops thru the objects discovered by the plugin, takes the results line-by-line, and inserts them into the database table specified in `"mapped_to_table"`. The columns are translated from the generic plugin columns to the target table columns via the `"mapped_to_column"` property in the column definitions.
|
||||
|
||||
> [!NOTE]
|
||||
> You can create a column mapping with a default value via the `mapped_to_column_data` property. This means that the value of the given column will always be this value. That also menas that the `"column": "NameDoesntMatter"` is not important as there is no database source column.
|
||||
|
||||
@@ -1,722 +0,0 @@
|
||||
## 📚 Dokumente für einzelne Plugins
|
||||
|
||||
### 🏴 Community-Übersetzungen dieser Datei
|
||||
|
||||
* <a href="https://github.com/jokob-sk/NetAlertX/blob/main/front/plugins/README.md">
|
||||
<img src="https://github.com/lipis/flag-icons/blob/main/flags/4x3/us.svg" alt="README.md" style="height: 20px !important;width: 20px !important;"> English (American)
|
||||
</a>
|
||||
|
||||
* <a href="https://github.com/jokob-sk/NetAlertX/blob/main/front/plugins/README_ES.md">
|
||||
<img src="https://github.com/lipis/flag-icons/blob/main/flags/4x3/es.svg" alt="README_ES.md" style="height: 20px !important;width: 20px !important;"> Spanish (Spain)
|
||||
</a>
|
||||
|
||||
### 🔌 Plugins und 📚 Dokumente
|
||||
|
||||
| Required | CurrentScan | Unique Prefix | Plugin Type | Link + Docs |
|
||||
|-------------|-------------|-----------------------|------------------------|----------------------------------------------------------|
|
||||
| | Yes | ARPSCAN | Script | [arp_scan](/front/plugins/arp_scan/) |
|
||||
| | | CSVBCKP | Script | [csv_backup](/front/plugins/csv_backup/) |
|
||||
| | Yes | DHCPLSS | Script | [dhcp_leases](/front/plugins/dhcp_leases/) |
|
||||
| | | DHCPSRVS | Script | [dhcp_servers](/front/plugins/dhcp_servers/) |
|
||||
| Yes | | NEWDEV | Template | [newdev_template](/front/plugins/newdev_template/) |
|
||||
| | | NMAP | Script | [nmap_scan](/front/plugins/nmap_scan/) |
|
||||
| | Yes | PIHOLE | External SQLite DB | [pihole_scan](/front/plugins/pihole_scan/) |
|
||||
| | | SETPWD | Script | [set_password](/front/plugins/set_password/) |
|
||||
| | | SNMPDSC | Script | [snmp_discovery](/front/plugins/snmp_discovery/) |
|
||||
| | Yes* | UNDIS | Script | [undiscoverables](/front/plugins/undiscoverables/) |
|
||||
| | Yes | UNFIMP | Script | [unifi_import](/front/plugins/unifi_import/) |
|
||||
| | | WEBMON | Script | [website_monitor](/front/plugins/website_monitor/) |
|
||||
| N/A | | N/A | SQL query | No beispiel available, but the External SQLite based plugins work very similar |
|
||||
|
||||
>* Das Undiscoverables-Plugin (`UNDIS`) fügt nur vom Benutzer angegebene Dummy-Geräte ein.
|
||||
|
||||
> [!NOTE]
|
||||
> Sie können Plugins über die Einstellungen sanft deaktivieren oder Plugins vollständig ignorieren, indem Sie eine „ignore_plugin“-Datei im Plugin-Verzeichnis ablegen. Der Unterschied besteht darin, dass ignorierte Plugins nirgendwo in der Benutzeroberfläche angezeigt werden (Einstellungen, Gerätedetails, Plugins-Seiten). Die App überspringt ignorierte Plugins vollständig. Geräteerkennungs-Plugins fügen Werte in die Datenbanktabelle „CurrentScan“ ein. Die Plugins, die nicht erforderlich sind, können getrost ignoriert werden, es ist jedoch sinnvoll, zumindest einige Plugins zur Geräteerkennung (die Einträge in die Tabelle „CurrentScan“ einfügen) zu aktivieren, wie z. B. ARPSCAN oder PIHOLE.
|
||||
|
||||
> Es wird empfohlen, für alle Plugins, die für die Erkennung neuer Geräte zuständig sind, das gleiche Zeitplanintervall zu verwenden.
|
||||
|
||||
## 🌟 Erstellen Sie ein benutzerdefiniertes Plugin: Übersicht
|
||||
|
||||
| ![Screen 1][screen1] | ![Screen 2][screen2] | ![Screen 3][screen3] |
|
||||
|----------------------|----------------------| ----------------------|
|
||||
| ![Screen 4][screen4] | ![Screen 5][screen5] |
|
||||
|
||||
PiAlert verfügt über ein Plugin-System, um Ereignisse aus Skripten von Drittanbietern in die Benutzeroberfläche einzuspeisen und dann bei Bedarf Benachrichtigungen zu senden. Die hervorgehobene Kernfunktionalität, die dieses Plugin-System unterstützt, ist:
|
||||
|
||||
* dynamische Erstellung einer einfachen Benutzeroberfläche zur Interaktion mit den entdeckten Objekten,
|
||||
* Filterung der angezeigten Werte in der Geräte-Benutzeroberfläche
|
||||
* Oberflächeneinstellungen von Plugins in der Benutzeroberfläche,
|
||||
* verschiedene Spaltentypen für gemeldete Werte, z.B. Link zurück zu einem Gerät
|
||||
* Objekte in vorhandene PiAlert-Datenbanktabellen importieren
|
||||
|
||||
> (Derzeit wird das Aktualisieren/Überschreiben vorhandener Objekte nicht unterstützt.)
|
||||
|
||||
Beispielanwendungsfälle für Plugins könnten sein:
|
||||
|
||||
* Überwachen Sie einen Webdienst und benachrichtigen Sie mich, wenn er nicht verfügbar ist
|
||||
* Importieren Sie Geräte aus dhcp.leases-Dateien anstelle/ergänzend zur Verwendung von PiHole oder arp-scans
|
||||
* Erstellen von Ad-hoc-UI-Tabellen aus vorhandenen Daten in der PiAlert-Datenbank, z.B. um alle offenen Ports auf Geräten anzuzeigen, um Geräte aufzulisten, die in der letzten Stunde getrennt wurden usw.
|
||||
* Verwendung anderer Geräteerkennungsmethoden im Netzwerk und Importieren der Daten als neue Geräte
|
||||
* Erstellen eines Skripts zum Erstellen gefälschter Geräte basierend auf Benutzereingaben über benutzerdefinierte Einstellungen
|
||||
* ...an diesem Punkt liegt die Einschränkung hauptsächlich in der Kreativität und nicht in der Leistungsfähigkeit (es kann Randfälle geben und die Notwendigkeit, mehr Formularsteuerelemente für Benutzereingaben aus benutzerdefinierten Einstellungen zu unterstützen, aber Sie haben wahrscheinlich schon verstanden, worauf es ankommt)
|
||||
|
||||
Wenn Sie ein Plugin entwickeln möchten, prüfen Sie bitte die bestehende Plugin-Struktur. Sobald die Einstellungen vom Benutzer gespeichert wurden, müssen sie manuell aus der Datei `pialert.conf` entfernt werden, wenn Sie sie aus der `config.json` des Plugins neu initialisieren möchten.
|
||||
|
||||
Bitte lesen Sie das Folgende noch einmal sorgfältig durch, wenn Sie selbst mit einem Plugin beitragen möchten. Diese Dokumentationsdatei ist möglicherweise veraltet. Überprüfen Sie daher auch die Beispiel-Plugins noch einmal.
|
||||
|
||||
## ⚠ Haftungsausschluss
|
||||
|
||||
Befolgen Sie die nachstehenden Anweisungen sorgfältig und prüfen Sie Beispiel-Plugins, wenn Sie selbst eines schreiben möchten. Die Plugin-Benutzeroberfläche ist derzeit nicht meine Priorität. Gerne genehmige ich PRs, wenn Sie daran interessiert sind, die Benutzeroberfläche zu erweitern/verbessern (siehe [Frontend-Richtlinien](/docs/FRONTEND_DEVELOPMENT.md)). Beispielhafte Verbesserungen zum Mitnehmen:
|
||||
|
||||
* Die Tabellen sortierbar/filterbar machen
|
||||
* Verwenden des gleichen Ansatzes zum Anzeigen von Tabellendaten wie im Abschnitt "Geräte" (wird oben gelöst)
|
||||
* Hinzufügen unterstützter Formularsteuerelemente zum Anzeigen der Daten (Derzeit unterstützte Steuerelemente sind im Abschnitt "UI-Einstellungen in Datenbankspaltendefinitionen" unten aufgeführt)
|
||||
* ...
|
||||
|
||||
## ❗ Bekannte Probleme:
|
||||
|
||||
These issues will be hopefully fixed with time, so please don't report them. Instead, if you know how, feel free to investigate and submit a PR to fix the below. Keep the PRs small as it's easier to approve them:
|
||||
|
||||
* Vorhandene Plugin-Objekte werden manchmal nicht richtig interpretiert und stattdessen wird ein neues Objekt erstellt, was zu doppelten Einträgen führt. (Rennbedingung?)
|
||||
* Gelegentliches (zweimal aufgetretenes) Hängenbleiben der Verarbeitungs-Plugin-Skriptdatei.
|
||||
Die Benutzeroberfläche zeigt veraltete Werte an, bis die API-Endpunkte aktualisiert werden.
|
||||
|
||||
## Übersicht über die Plugin-Dateistruktur
|
||||
|
||||
> ⚠️Der Ordnername muss mit dem Codenamenwert in Folgendem übereinstimmen: `"code_name": "<value>"`
|
||||
> Das eindeutige Präfix muss im Vergleich zu den anderen Einstellungspräfixen eindeutig sein, z. B.: Das Präfix `APPRISE` wird bereits verwendet.
|
||||
|
||||
| File | Required (plugin type) | Description |
|
||||
|----------------------|----------------------|----------------------|
|
||||
| `config.json` | yes | Contains the plugin configuration (manifest) including the settings available to the user. |
|
||||
| `script.py` | no | The Python script itself. You may call any valid linux command. |
|
||||
| `last_result.log` | no | The file used to interface between PiAlert and the plugin. Required for a script plugin if you want to feed data into the app. |
|
||||
| `script.log` | no | Logging output (recommended) |
|
||||
| `README.md` | yes | Any setup considerations or overview |
|
||||
|
||||
Weitere Einzelheiten finden Sie weiter unten.
|
||||
|
||||
### Spaltenreihenfolge und Werte
|
||||
|
||||
| Order | Represented Column | Required | Description |
|
||||
|----------------------|----------------------|----------------------|----------------------|
|
||||
| 0 | `Object_PrimaryID` | yes | The primary ID used to group Events under. |
|
||||
| 1 | `Object_SecondaryID` | no | Optional secondary ID to create a relationship beween other entities, such as a MAC address |
|
||||
| 2 | `DateTime` | yes | When the event occured in the format `2023-01-02 15:56:30` |
|
||||
| 3 | `Watched_Value1` | yes | A value that is watched and users can receive notifications if it changed compared to the previously saved entry. For beispiel IP address |
|
||||
| 4 | `Watched_Value2` | no | As above |
|
||||
| 5 | `Watched_Value3` | no | As above |
|
||||
| 6 | `Watched_Value4` | no | As above |
|
||||
| 7 | `Extra` | no | Any other data you want to pass and display in PiAlert and the notifications |
|
||||
| 8 | `ForeignKey` | no | A foreign key that can be used to link to the parent object (usually a MAC address) |
|
||||
|
||||
> [!NOTE]
|
||||
> De-duplication is run once an hour on the `Plugins_Objects` database table and duplicate entries with the same value in columns `Object_PrimaryID`, `Object_SecondaryID`, `Plugin` (auto-filled based on `unique_prefix` of the plugin), `UserData` (can be populated with the `"type": "textbox_save"` column type) are removed.
|
||||
|
||||
# config.json structure
|
||||
|
||||
## Unterstützte Datenquellen
|
||||
|
||||
Currently, these data sources are supported (valid `data_source` value).
|
||||
|
||||
| Name | `data_source` value | Needs to return a "table" | Overview (more details on this page below) |
|
||||
|----------------------|----------------------|----------------------|----------------------|
|
||||
| Script | `script` | no | Executes any linux command in the `CMD` setting. |
|
||||
| Pialert DB query | `pialert-db-query` | yes | Executes a SQL query on the PiAlert database in the `CMD` setting. |
|
||||
| Template | `template` | no | Used to generate internal settings, such as default values. |
|
||||
| External SQLite DB query | `sqlite-db-query` | yes | Executes a SQL query from the `CMD` setting on an external SQLite database mapped in the `DB_PATH` setting. |
|
||||
|
||||
|
||||
> 🔎Beispiel
|
||||
>```json
|
||||
>"data_source": "pialert-db-query"
|
||||
>```
|
||||
If you want to display plugin objects or import devices into the app, data sources have to return a "table" of the exact structure as outlined above.
|
||||
|
||||
You can show or hide the UI on the "Plugins" page and "Plugins" tab for a plugin on devices via the `show_ui` property:
|
||||
|
||||
> 🔎Beispiel
|
||||
>```json
|
||||
> "show_ui": true,
|
||||
> ```
|
||||
|
||||
### "data_source": "script"
|
||||
|
||||
If the `data_source` is set to `script` the `CMD` setting (that you specify in the `settings` array section in the `config.json`) contains an executable Linux command, that usually generates a `last_result.log` file (not required if you don't import any data into the app). This file needs to be stored in the same folder as the plugin.
|
||||
|
||||
> [!IMPORTANT]
|
||||
> A lot of the work is taken care of by the [`plugin_helper.py` library](/front/plugins/plugin_helper.py). You don't need to manage the `last_result.log` file if using the helper objects. Check other `script.py` of other plugins for details (The [Undicoverables plugins `script.py` file](/front/plugins/undiscoverables/script.py) is a good beispiel).
|
||||
|
||||
The content of the `last_result.log` file needs to contain the columns as defined in the "Column order and values" section above. The order of columns can't be changed. After every scan it should contain only the results from the latest scan/execution.
|
||||
|
||||
- The format of the `last_result.log` is a `csv`-like file with the pipe `|` as a separator.
|
||||
- 9 (nine) values need to be supplied, so every line needs to contain 8 pipe separators. Empty values are represented by `null`.
|
||||
- Don't render "headers" for these "columns".
|
||||
Every scan result/event entry needs to be on a new line.
|
||||
- You can find which "columns" need to be present, and if the value is required or optional, in the "Column order and values" section.
|
||||
- The order of these "columns" can't be changed.
|
||||
|
||||
#### 🔎 last_result.log beispieles
|
||||
|
||||
Valid CSV:
|
||||
|
||||
```csv
|
||||
|
||||
https://www.google.com|null|2023-01-02 15:56:30|200|0.7898|null|null|null|null
|
||||
https://www.duckduckgo.com|192.168.0.1|2023-01-02 15:56:30|200|0.9898|null|null|Best search engine|ff:ee:ff:11:ff:11
|
||||
|
||||
```
|
||||
|
||||
Invalid CSV with different errors on each line:
|
||||
|
||||
```csv
|
||||
|
||||
https://www.google.com|null|2023-01-02 15:56:30|200|0.7898||null|null|null
|
||||
https://www.duckduckgo.com|null|2023-01-02 15:56:30|200|0.9898|null|null|Best search engine|
|
||||
|https://www.duckduckgo.com|null|2023-01-02 15:56:30|200|0.9898|null|null|Best search engine|null
|
||||
null|192.168.1.1|2023-01-02 15:56:30|200|0.9898|null|null|Best search engine
|
||||
https://www.duckduckgo.com|192.168.1.1|2023-01-02 15:56:30|null|0.9898|null|null|Best search engine
|
||||
https://www.google.com|null|2023-01-02 15:56:30|200|0.7898|||
|
||||
https://www.google.com|null|2023-01-02 15:56:30|200|0.7898|
|
||||
|
||||
```
|
||||
|
||||
### "data_source": "pialert-db-query"
|
||||
|
||||
If the `data_source` is set to `pialert-db-query` the `CMD` setting needs to contain a SQL query rendering the columns as defined in the "Column order and values" section above. The order of columns is important.
|
||||
|
||||
This SQL query is executed on the `pialert.db` SQLite database file.
|
||||
|
||||
> 🔎Beispiel
|
||||
>
|
||||
> SQL query Beispiel:
|
||||
>
|
||||
> ```SQL
|
||||
> SELECT dv.dev_Name as Object_PrimaryID,
|
||||
> cast(dv.dev_LastIP as VARCHAR(100)) || ':' || cast( SUBSTR(ns.Port ,0, INSTR(ns.Port , '/')) as VARCHAR(100)) as Object_SecondaryID,
|
||||
> datetime() as DateTime,
|
||||
> ns.Service as Watched_Value1,
|
||||
> ns.State as Watched_Value2,
|
||||
> 'null' as Watched_Value3,
|
||||
> 'null' as Watched_Value4,
|
||||
> ns.Extra as Extra,
|
||||
> dv.dev_MAC as ForeignKey
|
||||
> FROM
|
||||
> (SELECT * FROM Nmap_Scan) ns
|
||||
> LEFT JOIN
|
||||
> (SELECT dev_Name, dev_MAC, dev_LastIP FROM Devices) dv
|
||||
> ON ns.MAC = dv.dev_MAC
|
||||
> ```
|
||||
>
|
||||
> Required `CMD` setting beispiel with above query (you can set `"type": "label"` if you want it to make uneditable in the UI):
|
||||
>
|
||||
> ```json
|
||||
> {
|
||||
> "function": "CMD",
|
||||
> "type": "text",
|
||||
> "default_value":"SELECT dv.dev_Name as Object_PrimaryID, cast(dv.dev_LastIP as VARCHAR(100)) || ':' || cast( SUBSTR(ns.Port ,0, INSTR(ns.Port , '/')) as VARCHAR(100)) as Object_SecondaryID, datetime() as DateTime, ns.Service as Watched_Value1, ns.State as Watched_Value2, 'null' as Watched_Value3, 'null' as Watched_Value4, ns.Extra as Extra FROM (SELECT * FROM Nmap_Scan) ns LEFT JOIN (SELECT dev_Name, dev_MAC, dev_LastIP FROM Devices) dv ON ns.MAC = dv.dev_MAC",
|
||||
> "options": [],
|
||||
> "localized": ["name", "description"],
|
||||
> "name" : [{
|
||||
> "language_code":"en_us",
|
||||
> "string" : "SQL to run"
|
||||
> }],
|
||||
> "description": [{
|
||||
> "language_code":"en_us",
|
||||
> "string" : "This SQL query is used to populate the coresponding UI tables under the Plugins section."
|
||||
> }]
|
||||
> }
|
||||
> ```
|
||||
|
||||
### "data_source": "template"
|
||||
|
||||
Used to initialize internal settings. Check the `newdev_template` plugin for details.
|
||||
|
||||
### "data_source": "sqlite-db-query"
|
||||
|
||||
You can execute a SQL query on an external database connected to the current PiALert database via a temporary `EXTERNAL_<unique prefix>.` prefix. For beispiel for `PIHOLE` (`"unique_prefix": "PIHOLE"`) it is `EXTERNAL_PIHOLE.`. The external SQLite database file has to be mapped in the container to the path specified in the `DB_PATH` setting:
|
||||
|
||||
> 🔎Beispiel
|
||||
>
|
||||
>```json
|
||||
> ...
|
||||
>{
|
||||
> "function": "DB_PATH",
|
||||
> "type": "readonly",
|
||||
> "default_value":"/etc/pihole/pihole-FTL.db",
|
||||
> "options": [],
|
||||
> "localized": ["name", "description"],
|
||||
> "name" : [{
|
||||
> "language_code":"en_us",
|
||||
> "string" : "DB Path"
|
||||
> }],
|
||||
> "description": [{
|
||||
> "language_code":"en_us",
|
||||
> "string" : "Required setting for the <code>sqlite-db-query</code> plugin type. Is used to mount an external SQLite database and execute the SQL query stored in the <code>CMD</code> setting."
|
||||
> }]
|
||||
> }
|
||||
> ...
|
||||
>```
|
||||
|
||||
The actual SQL query you want to execute is then stored as a `CMD` setting, similar to the `pialert-db-query` plugin type The format has to adhere to the format outlined in the "Column order and values" section above.
|
||||
|
||||
> 🔎Beispiel
|
||||
>
|
||||
> Notice the `EXTERNAL_PIHOLE.` prefix.
|
||||
>
|
||||
>```json
|
||||
>{
|
||||
> "function": "CMD",
|
||||
> "type": "text",
|
||||
> "default_value":"SELECT hwaddr as Object_PrimaryID, cast('http://' || (SELECT ip FROM EXTERNAL_PIHOLE.network_addresses WHERE network_id = id ORDER BY lastseen DESC, ip LIMIT 1) as VARCHAR(100)) || ':' || cast( SUBSTR((SELECT name FROM EXTERNAL_PIHOLE.network_addresses WHERE network_id = id ORDER BY lastseen DESC, ip LIMIT 1), 0, INSTR((SELECT name FROM EXTERNAL_PIHOLE.network_addresses WHERE network_id = id ORDER BY lastseen DESC, ip LIMIT 1), '/')) as VARCHAR(100)) as Object_SecondaryID, datetime() as DateTime, macVendor as Watched_Value1, lastQuery as Watched_Value2, (SELECT name FROM EXTERNAL_PIHOLE.network_addresses WHERE network_id = id ORDER BY lastseen DESC, ip LIMIT 1) as Watched_Value3, 'null' as Watched_Value4, '' as Extra, hwaddr as ForeignKey FROM EXTERNAL_PIHOLE.network WHERE hwaddr NOT LIKE 'ip-%' AND hwaddr <> '00:00:00:00:00:00'; ",
|
||||
> "options": [],
|
||||
> "localized": ["name", "description"],
|
||||
> "name" : [{
|
||||
> "language_code":"en_us",
|
||||
> "string" : "SQL to run"
|
||||
> }],
|
||||
> "description": [{
|
||||
> "language_code":"en_us",
|
||||
> "string" : "This SQL query is used to populate the coresponding UI tables under the Plugins section. This particular one selects data from a mapped PiHole SQLite database and maps it to the corresponding Plugin columns."
|
||||
> }]
|
||||
> }
|
||||
> ```
|
||||
|
||||
## 🕳 Filter
|
||||
|
||||
Plugin-Einträge können in der Benutzeroberfläche basierend auf in Filterfeldern eingegebenen Werten gefiltert werden. Das Textfeld/Feld `txtMacFilter` enthält die Mac-Adresse des aktuell angezeigten Geräts oder einfach eine Mac-Adresse, die in der Abfragezeichenfolge `mac` verfügbar ist.
|
||||
|
||||
| Property | Required | Description |
|
||||
|----------------------|----------------------|----------------------|
|
||||
| `compare_column` | yes | Plugin column name that's value is used for comparison (**Left** side of the equation) |
|
||||
| `compare_operator` | yes | JavaScript comparison operator |
|
||||
| `compare_field_id` | yes | The `id` of a input text field containing a value is used for comparison (**Right** side of the equation)|
|
||||
| `compare_js_template` | yes | JavaScript code used to convert left and right side of the equation. `{value}` is replaced with input values. |
|
||||
| `compare_use_quotes` | yes | If `true` then the end result of the `compare_js_template` i swrapped in `"` quotes. Use to compare strings. |
|
||||
|
||||
Filters are only applied if a filter is specified and the `txtMacFilter` is not `undefined` or empty (`--`).
|
||||
|
||||
> 🔎Beispiel:
|
||||
>
|
||||
> ```json
|
||||
> "data_filters": [
|
||||
> {
|
||||
> "compare_column" : "Object_PrimaryID",
|
||||
> "compare_operator" : "==",
|
||||
> "compare_field_id": "txtMacFilter",
|
||||
> "compare_js_template": "'{value}'.toString()",
|
||||
> "compare_use_quotes": true
|
||||
> }
|
||||
> ],
|
||||
> ```
|
||||
>
|
||||
>1. On the `pluginsCore.php` page is an input field with the `txtMacFilter` id:
|
||||
>
|
||||
>```html
|
||||
><input class="form-control" id="txtMacFilter" type="text" value="--">
|
||||
>```
|
||||
>
|
||||
>2. This input field is initialized via the `&mac=` query string.
|
||||
>
|
||||
>3. The app then proceeds to use this Mac value from this field and compares it to the value of the `Object_PrimaryID` database field. The `compare_operator` is `==`.
|
||||
>
|
||||
>4. Both values, from the database field `Object_PrimaryID` and from the `txtMacFilter` are wrapped and evaluated with the `compare_js_template`, that is `'{value}.toString()'`.
|
||||
>
|
||||
>5. `compare_use_quotes` is set to `true` so `'{value}'.toString()` is wrappe dinto `"` quotes.
|
||||
>
|
||||
>6. Daraus ergibt sich beispielsweise dieser code:
|
||||
>
|
||||
>```javascript
|
||||
> // left part of teh expression coming from compare_column and right from the input field
|
||||
> // notice the added quotes ()") around the left and right part of teh expression
|
||||
> "eval('ac:82:ac:82:ac:82".toString()')" == "eval('ac:82:ac:82:ac:82".toString()')"
|
||||
>```
|
||||
>
|
||||
|
||||
|
||||
### 🗺 Zuordnung der Plugin-Ergebnisse zu einer Datenbanktabelle
|
||||
|
||||
Plugin results are always inserted into the standard `Plugin_Objects` database table. Optionally, PiAlert can take the results of the plugin execution and insert these results into an additional database table. This is enabled by with the property `"mapped_to_table"` in the `config.json` file. The mapping of the columns is defined in the `database_column_definitions` array.
|
||||
|
||||
> [!NOTE]
|
||||
> If results are mapped to the `CurrentScan` table, the data is then included into the regular scan loop, so for beispiel notification for devices are sent out.
|
||||
|
||||
|
||||
>🔍 Beispiel:
|
||||
>
|
||||
>For beispiel, this approach is used to implement the `DHCPLSS` plugin. The script parses all supplied "dhcp.leases" files, gets the results in the generic table format outlined in the "Column order and values" section above and takes individual values and inserts them into the `CurrentScan` database table in the PiAlert database. All this is achieved by:
|
||||
>
|
||||
>1. Specifying the database table into which the results are inserted by defining `"mapped_to_table": "CurrentScan"` in the root of the `config.json` file as shown below:
|
||||
>
|
||||
>```json
|
||||
>{
|
||||
> "code_name": "dhcp_leases",
|
||||
> "unique_prefix": "DHCPLSS",
|
||||
> ...
|
||||
> "data_source": "script",
|
||||
> "localized": ["display_name", "description", "icon"],
|
||||
> "mapped_to_table": "CurrentScan",
|
||||
> ...
|
||||
>}
|
||||
>```
|
||||
>2. Defining the target column with the `mapped_to_column` property for individual columns in the `database_column_definitions` array of the `config.json` file. For beispiel in the `DHCPLSS` plugin, I needed to map the value of the `Object_PrimaryID` column returned by the plugin, to the `cur_MAC` column in the PiAlert database `CurrentScan` table. Notice the `"mapped_to_column": "cur_MAC"` key-value pair in the sample below.
|
||||
>
|
||||
>```json
|
||||
>{
|
||||
> "column": "Object_PrimaryID",
|
||||
> "mapped_to_column": "cur_MAC",
|
||||
> "css_classes": "col-sm-2",
|
||||
> "show": true,
|
||||
> "type": "device_mac",
|
||||
> "default_value":"",
|
||||
> "options": [],
|
||||
> "localized": ["name"],
|
||||
> "name":[{
|
||||
> "language_code":"en_us",
|
||||
> "string" : "MAC address"
|
||||
> }]
|
||||
> }
|
||||
>```
|
||||
>
|
||||
>3. That's it. PiAlert takes care of the rest. It loops thru the objects discovered by the plugin, takes the results line, by line and inserts them into the database table specified in `"mapped_to_table"`. The columns are translated from the generic plugin columns to the target table via the `"mapped_to_column"` property in the column definitions.
|
||||
|
||||
> [!NOTE]
|
||||
> You can create a column mapping with a default value via the `mapped_to_column_data` property. This means that the value of the given column will always be this value. Taht also menas that the `"column": "NameDoesntMatter"` is not important as there is no database source column.
|
||||
|
||||
|
||||
>🔍 Beispiel:
|
||||
>
|
||||
>```json
|
||||
>{
|
||||
> "column": "NameDoesntMatter",
|
||||
> "mapped_to_column": "cur_ScanMethod",
|
||||
> "mapped_to_column_data": {
|
||||
> "value": "DHCPLSS"
|
||||
> },
|
||||
> "css_classes": "col-sm-2",
|
||||
> "show": true,
|
||||
> "type": "device_mac",
|
||||
> "default_value":"",
|
||||
> "options": [],
|
||||
> "localized": ["name"],
|
||||
> "name":[{
|
||||
> "language_code":"en_us",
|
||||
> "string" : "MAC address"
|
||||
> }]
|
||||
> }
|
||||
>```
|
||||
|
||||
#### params
|
||||
|
||||
The `params` array in the `config.json` is used to enable the user to change the parameters of the executed script. For beispiel, the user wants to monitor a specific URL.
|
||||
|
||||
> 🔎 Beispiel:
|
||||
> Passing user-defined settings to a command. Let's say, you want to have a script, that is called with a user-defined parameter called `urls`:
|
||||
>
|
||||
> ```bash
|
||||
> root@server# python3 /home/pi/pialert/front/plugins/website_monitor/script.py urls=https://google.com,https://duck.com
|
||||
> ```
|
||||
|
||||
* You can allow the user to add URLs to a setting with the `function` property set to a custom name, such as `urls_to_check` (this is not a reserved name from the section "Supported settings `function` values" below).
|
||||
* You specify the parameter `urls` in the `params` section of the `config.json` the following way (`WEBMON_` is the plugin prefix automatically added to all the settings):
|
||||
```json
|
||||
{
|
||||
"params" : [
|
||||
{
|
||||
"name" : "urls",
|
||||
"type" : "setting",
|
||||
"value" : "WEBMON_urls_to_check"
|
||||
}]
|
||||
}
|
||||
```
|
||||
* Then you use this setting as an input parameter for your command in the `CMD` setting. Notice `urls={urls}` in the below json:
|
||||
|
||||
```json
|
||||
{
|
||||
"function": "CMD",
|
||||
"type": "text",
|
||||
"default_value":"python3 /home/pi/pialert/front/plugins/website_monitor/script.py urls={urls}",
|
||||
"options": [],
|
||||
"localized": ["name", "description"],
|
||||
"name" : [{
|
||||
"language_code":"en_us",
|
||||
"string" : "Command"
|
||||
}],
|
||||
"description": [{
|
||||
"language_code":"en_us",
|
||||
"string" : "Command to run"
|
||||
}]
|
||||
}
|
||||
```
|
||||
|
||||
During script execution, the app will take the command `"python3 /home/pi/pialert/front/plugins/website_monitor/script.py urls={urls}"`, take the `{urls}` wildcard and replace it with the value from the `WEBMON_urls_to_check` setting. This is because:
|
||||
|
||||
1. The app checks the `params` entries
|
||||
2. It finds `"name" : "urls"`
|
||||
3. Checks the type of the `urls` params and finds `"type" : "setting"`
|
||||
4. Gets the setting name from `"value" : "WEBMON_urls_to_check"`
|
||||
- IMPORTANT: in the `config.json` this setting is identified by `"function":"urls_to_check"`, not `"function":"WEBMON_urls_to_check"`
|
||||
- You can also use a global setting, or a setting from a different plugin
|
||||
5. The app gets the user defined value from the setting with the code name `WEBMON_urls_to_check`
|
||||
- let's say the setting with the code name `WEBMON_urls_to_check` contains 2 values entered by the user:
|
||||
- `WEBMON_urls_to_check=['https://google.com','https://duck.com']`
|
||||
6. The app takes the value from `WEBMON_urls_to_check` and replaces the `{urls}` wildcard in the setting where `"function":"CMD"`, so you go from:
|
||||
- `python3 /home/pi/pialert/front/plugins/website_monitor/script.py urls={urls}`
|
||||
- to
|
||||
- `python3 /home/pi/pialert/front/plugins/website_monitor/script.py urls=https://google.com,https://duck.com`
|
||||
|
||||
Below are some general additional notes, when defining `params`:
|
||||
|
||||
- `"name":"name_value"` - is used as a wildcard replacement in the `CMD` setting value by using curly brackets `{name_value}`. The wildcard is replaced by the result of the `"value" : "param_value"` and `"type":"type_value"` combo configuration below.
|
||||
- `"type":"<sql|setting>"` - is used to specify the type of the params, currently only 2 supported (`sql`,`setting`).
|
||||
- `"type":"sql"` - will execute the SQL query specified in the `value` property. The sql query needs to return only one column. The column is flattened and separated by commas (`,`), e.g: `SELECT dev_MAC from DEVICES` -> `Internet,74:ac:74:ac:74:ac,44:44:74:ac:74:ac`. This is then used to replace the wildcards in the `CMD` setting.
|
||||
- `"type":"setting"` - The setting code name. A combination of the value from `unique_prefix` + `_` + `function` value, or otherwise the code name you can find in the Settings page under the Setting display name, e.g. `PIHOLE_RUN`.
|
||||
- `"value": "param_value"` - Needs to contain a setting code name or SQL query without wildcards.
|
||||
- `"timeoutMultiplier" : true` - used to indicate if the value should multiply the max timeout for the whole script run by the number of values in the given parameter.
|
||||
- `"base64": true` - use base64 encoding to pass the value to the script (e.g. if there are spaces)
|
||||
|
||||
|
||||
> 🔎Beispiel:
|
||||
>
|
||||
> ```json
|
||||
> {
|
||||
> "params" : [{
|
||||
> "name" : "ips",
|
||||
> "type" : "sql",
|
||||
> "value" : "SELECT dev_LastIP from DEVICES",
|
||||
> "timeoutMultiplier" : true
|
||||
> },
|
||||
> {
|
||||
> "name" : "macs",
|
||||
> "type" : "sql",
|
||||
> "value" : "SELECT dev_MAC from DEVICES"
|
||||
> },
|
||||
> {
|
||||
> "name" : "timeout",
|
||||
> "type" : "setting",
|
||||
> "value" : "NMAP_RUN_TIMEOUT"
|
||||
> },
|
||||
> {
|
||||
> "name" : "args",
|
||||
> "type" : "setting",
|
||||
> "value" : "NMAP_ARGS",
|
||||
> "base64" : true
|
||||
> }]
|
||||
> }
|
||||
> ```
|
||||
|
||||
|
||||
#### ⚙ Objektstruktur festlegen
|
||||
|
||||
> [!NOTE]
|
||||
> Der Einstellungsablauf und wann Plugin-spezifische Einstellungen angewendet werden, wird im [Einstellungssystem](/docs/SETTINGS_SYSTEM.md) beschrieben.
|
||||
|
||||
Required attributes are:
|
||||
|
||||
| Property | Description |
|
||||
| -------- | ----------- |
|
||||
| `"function"` | Specifies the function the setting drives or a simple unique code name. See Supported settings function values for options. |
|
||||
| `"type"` | Specifies the form control used for the setting displayed in the Settings page and what values are accepted. Supported options include: |
|
||||
| | - `text` |
|
||||
| | - `integer` |
|
||||
| | - `boolean` |
|
||||
| | - `password` |
|
||||
| | - `readonly` |
|
||||
| | - `integer.select` |
|
||||
| | - `text.select` |
|
||||
| | - `text.multiselect` |
|
||||
| | - `list` |
|
||||
| | - `integer.checkbox` |
|
||||
| | - `text.template` |
|
||||
| `"localized"` | A list of properties on the current JSON level that need to be localized. |
|
||||
| `"name"` | Displayed on the Settings page. An array of localized strings. See Localized strings below. |
|
||||
| `"description"` | Displayed on the Settings page. An array of localized strings. See Localized strings below. |
|
||||
| (optional) `"events"` | Specifies whether to generate an execution button next to the input field of the setting. Supported values: |
|
||||
| | - `test` |
|
||||
| | - `run` |
|
||||
| (optional) `"override_value"` | Used to determine a user-defined override for the setting. Useful for template-based plugins, where you can choose to leave the current value or override it with the value defined in the setting. (Work in progress) |
|
||||
| (optional) `"events"` | Used to trigger the plugin. Usually used on the `RUN` setting. Not fully tested in all scenarios. Will show a play button next to the setting. After clicking, an event is generated for the backend in the `Parameters` database table to process the front-end event on the next run. |
|
||||
|
||||
|
||||
##### Unterstützte Einstellungen `function` werte
|
||||
|
||||
You can have any `"function": "my_custom_name"` custom name, however, the ones listed below have a specific functionality attached to them. If you use a custom name, then the setting is mostly used as an input parameter for the `params` section.
|
||||
|
||||
| Setting | Description |
|
||||
| ------- | ----------- |
|
||||
| `RUN` | (required) Specifies when the service is executed. |
|
||||
| | Supported Options: |
|
||||
| | - "disabled" - not run |
|
||||
| | - "once" - run on app start or on settings saved |
|
||||
| | - "schedule" - if included, then a `RUN_SCHD` setting needs to be specified to determine the schedule |
|
||||
| | - "always_after_scan" - run always after a scan is finished |
|
||||
| | - "on_new_device" - run when a new device is detected |
|
||||
| | - "before_config_save" - run before the config is marked as saved. Useful if your plugin needs to modify the `pialert.conf` file. |
|
||||
| `RUN_SCHD` | (required if you include the above `RUN` function) Cron-like scheduling is used if the `RUN` setting is set to `schedule`. |
|
||||
| `CMD` | (required) Specifies the command that should be executed. |
|
||||
| `API_SQL` | (not implemented) Generates a `table_` + `code_name` + `.json` file as per [API docs](https://github.com/jokob-sk/NetAlertX/blob/main/docs/API.md). |
|
||||
| `RUN_TIMEOUT` | (optional) Specifies the maximum execution time of the script. If not specified, a default value of 10 seconds is used to prevent hanging. |
|
||||
| `WATCH` | (optional) Specifies which database columns are watched for changes for this particular plugin. If not specified, no notifications are sent. |
|
||||
| `REPORT_ON` | (optional) Specifies when to send a notification. Supported options are: |
|
||||
| | - `new` means a new unique (unique combination of PrimaryId and SecondaryId) object was discovered. |
|
||||
| | - `watched-changed` - means that selected `Watched_ValueN` columns changed |
|
||||
| | - `watched-not-changed` - reports even on events where selected `Watched_ValueN` did not change |
|
||||
| | - `missing-in-last-scan` - if the object is missing compared to previous scans |
|
||||
|
||||
|
||||
|
||||
> 🔎 Beispiel:
|
||||
>
|
||||
> ```json
|
||||
> {
|
||||
> "function": "RUN",
|
||||
> "type": "text.select",
|
||||
> "default_value":"disabled",
|
||||
> "options": ["disabled", "once", "schedule", "always_after_scan", "on_new_device"],
|
||||
> "localized": ["name", "description"],
|
||||
> "name" :[{
|
||||
> "language_code":"en_us",
|
||||
> "string" : "When to run"
|
||||
> }],
|
||||
> "description": [{
|
||||
> "language_code":"en_us",
|
||||
> "string" : "Enable a regular scan of your services. If you select <code>schedule</code> the scheduling settings from below are applied. If you select <code>once</code> the scan is run only once on start of the application (container) for the time specified in <a href=\"#WEBMON_RUN_TIMEOUT\"><code>WEBMON_RUN_TIMEOUT</code> setting</a>."
|
||||
> }]
|
||||
> }
|
||||
> ```
|
||||
|
||||
##### 🌍Lokalisierte Zeichenfolgen
|
||||
|
||||
- `"language_code":"<en_us|es_es|de_de>"` - code name of the language string. Only these three are currently supported. At least the `"language_code":"en_us"` variant has to be defined.
|
||||
- `"string"` - The string to be displayed in the given language.
|
||||
|
||||
> 🔎 Beispiel:
|
||||
>
|
||||
> ```json
|
||||
>
|
||||
> {
|
||||
> "language_code":"en_us",
|
||||
> "string" : "When to run"
|
||||
> }
|
||||
>
|
||||
> ```
|
||||
|
||||
##### UI-Einstellungen in database_column_definitions.
|
||||
|
||||
The UI will adjust how columns are displayed in the UI based on the resolvers definition of the `database_column_definitions` object. These are the supported form controls and related functionality:
|
||||
|
||||
- Only columns with `"show": true` and also with at least an English translation will be shown in the UI.
|
||||
|
||||
| Supported Types | Description |
|
||||
| -------------- | ----------- |
|
||||
| `label` | Displays a column only. |
|
||||
| `text` | Makes a column editable, and a save icon is displayed next to it. See below for information on `threshold`, `replace`. |
|
||||
| | |
|
||||
| `options` Property | Used in conjunction with types like `threshold`, `replace`, `regex`. |
|
||||
| `threshold` | The `options` array contains objects ordered from the lowest `maximum` to the highest. The corresponding `hexColor` is used for the value background color if it's less than the specified `maximum` but more than the previous one in the `options` array. |
|
||||
| `replace` | The `options` array contains objects with an `equals` property, which is compared to the "value." If the values are the same, the string in `replacement` is displayed in the UI instead of the actual "value". |
|
||||
| `regex` | Applies a regex to the value. The `options` array contains objects with an `type` (must be set to `regex`) and `param` (must contain the regex itself) property. |
|
||||
| | |
|
||||
| Type Definitions | |
|
||||
| `device_mac` | The value is considered to be a MAC address, and a link pointing to the device with the given MAC address is generated. |
|
||||
| `device_ip` | The value is considered to be an IP address. A link pointing to the device with the given IP is generated. The IP is checked against the last detected IP address and translated into a MAC address, which is then used for the link itself. |
|
||||
| `device_name_mac` | The value is considered to be a MAC address, and a link pointing to the device with the given IP is generated. The link label is resolved as the target device name. |
|
||||
| `url` | The value is considered to be a URL, so a link is generated. |
|
||||
| `textbox_save` | Generates an editable and saveable text box that saves values in the database. Primarily intended for the `UserData` database column in the `Plugins_Objects` table. |
|
||||
| `url_http_https` | Generates two links with the `https` and `http` prefix as lock icons. |
|
||||
|
||||
|
||||
> [!NOTE]
|
||||
> Unterstützt Verkettung. Sie können mehrere Resolver mit „.“ verketten. Zum Beispiel `regex.url_http_https`. Dadurch wird der Resolver `regex` und dann der Resolver `url_http_https` angewendet.
|
||||
|
||||
|
||||
|
||||
```json
|
||||
{
|
||||
"column": "Watched_Value1",
|
||||
"css_classes": "col-sm-2",
|
||||
"show": true,
|
||||
"type": "threshold",
|
||||
"default_value":"",
|
||||
"options": [
|
||||
{
|
||||
"maximum": 199,
|
||||
"hexColor": "#792D86"
|
||||
},
|
||||
{
|
||||
"maximum": 299,
|
||||
"hexColor": "#5B862D"
|
||||
},
|
||||
{
|
||||
"maximum": 399,
|
||||
"hexColor": "#7D862D"
|
||||
},
|
||||
{
|
||||
"maximum": 499,
|
||||
"hexColor": "#BF6440"
|
||||
},
|
||||
{
|
||||
"maximum": 599,
|
||||
"hexColor": "#D33115"
|
||||
}
|
||||
],
|
||||
"localized": ["name"],
|
||||
"name":[{
|
||||
"language_code":"en_us",
|
||||
"string" : "Status code"
|
||||
}]
|
||||
},
|
||||
{
|
||||
"column": "Status",
|
||||
"show": true,
|
||||
"type": "replace",
|
||||
"default_value":"",
|
||||
"options": [
|
||||
{
|
||||
"equals": "watched-not-changed",
|
||||
"replacement": "<i class='fa-solid fa-square-check'></i>"
|
||||
},
|
||||
{
|
||||
"equals": "watched-changed",
|
||||
"replacement": "<i class='fa-solid fa-triangle-exclamation'></i>"
|
||||
},
|
||||
{
|
||||
"equals": "new",
|
||||
"replacement": "<i class='fa-solid fa-circle-plus'></i>"
|
||||
}
|
||||
],
|
||||
"localized": ["name"],
|
||||
"name":[{
|
||||
"language_code":"en_us",
|
||||
"string" : "Status"
|
||||
}]
|
||||
},
|
||||
{
|
||||
"column": "Watched_Value3",
|
||||
"css_classes": "col-sm-1",
|
||||
"show": true,
|
||||
"type": "regex.url_http_https",
|
||||
"default_value":"",
|
||||
"options": [
|
||||
{
|
||||
"type": "regex",
|
||||
"param": "([\\d.:]+)"
|
||||
}
|
||||
],
|
||||
"localized": ["name"],
|
||||
"name":[{
|
||||
"language_code":"en_us",
|
||||
"string" : "HTTP/s links"
|
||||
},
|
||||
{
|
||||
"language_code":"es_es",
|
||||
"string" : "N/A"
|
||||
}]
|
||||
}
|
||||
```
|
||||
|
||||
[screen1]: https://raw.githubusercontent.com/jokob-sk/NetAlertX/main/docs/img/plugins.png "Screen 1"
|
||||
[screen2]: https://raw.githubusercontent.com/jokob-sk/NetAlertX/main/docs/img/plugins_settings.png "Screen 2"
|
||||
[screen3]: https://raw.githubusercontent.com/jokob-sk/NetAlertX/main/docs/img/plugins_json_settings.png "Screen 3"
|
||||
[screen4]: https://raw.githubusercontent.com/jokob-sk/NetAlertX/main/docs/img/plugins_json_ui.png "Screen 4"
|
||||
[screen5]: https://raw.githubusercontent.com/jokob-sk/NetAlertX/main/docs/img/plugins_device_details.png "Screen 5"
|
||||
@@ -1,631 +0,0 @@
|
||||
## 📚 Documentos para plugins individuales
|
||||
|
||||
### 🏴 Traducciones comunitarias de este archivo
|
||||
|
||||
* <a href="https://github.com/jokob-sk/NetAlertX/blob/main/front/plugins/README.md">
|
||||
<img src="https://github.com/lipis/flag-icons/blob/main/flags/4x3/us.svg" alt="README.md" style="height: 20px !important;width: 20px !important;"> Ingles (Americano)
|
||||
</a>
|
||||
|
||||
* <a href="https://github.com/jokob-sk/NetAlertX/blob/main/front/plugins/README_DE.md">
|
||||
<img src="https://github.com/lipis/flag-icons/blob/main/flags/4x3/de.svg" alt="README.md" style="height: 20px !important;width: 20px !important;"> Alemán (Alemania)
|
||||
</a>
|
||||
|
||||
### 🔌 Plugins y 📚 Documentos
|
||||
|
||||
| Requerido | CurrentScan | Prefijo único | Tipo de plugin | Enlace + Documentos |
|
||||
|-------------|-------------|-----------------------|------------------------|----------------------------------------------------------|
|
||||
| | Sí | ARPSCAN | Script | [arp_scan](/front/plugins/arp_scan/) |
|
||||
| | | CSVBCKP | Script | [csv_backup](/front/plugins/csv_backup/) |
|
||||
| | Sí | DHCPLSS | Script | [dhcp_leases](/front/plugins/dhcp_leases/) |
|
||||
| | | DHCPSRVS | Script | [dhcp_servers](/front/plugins/dhcp_servers/) |
|
||||
| Sí | | NEWDEV | Template | [newdev_template](/front/plugins/newdev_template/) |
|
||||
| | | NMAP | Script | [nmap_scan](/front/plugins/nmap_scan/) |
|
||||
| | Sí | PIHOLE | External SQLite DB | [pihole_scan](/front/plugins/pihole_scan/) |
|
||||
| | | SETPWD | Script | [set_password](/front/plugins/set_password/) |
|
||||
| | | SNMPDSC | Script | [snmp_discovery](/front/plugins/snmp_discovery/) |
|
||||
| | Sí* | UNDIS | Script | [undiscoverables](/front/plugins/undiscoverables/) |
|
||||
| | Sí | UNFIMP | Script | [unifi_import](/front/plugins/unifi_import/) |
|
||||
| | | WEBMON | Script | [website_monitor](/front/plugins/website_monitor/) |
|
||||
| N/A | | N/A | SQL query | No hay ningún ejemplo disponible, pero los complementos basados en SQLite externo funcionan de manera muy similar |
|
||||
|
||||
>* El complemento Undiscoverables (`UNDIS`) inserta solo dispositivos ficticios especificados por el usuario.
|
||||
|
||||
> [!NOTE]
|
||||
> Puede desactivar los complementos a través de Configuración o ignorarlos por completo colocando un archivo `ignore_plugin` en el directorio de complementos. La diferencia es que los complementos ignorados no aparecen en ninguna parte de la interfaz de usuario (Configuración, Detalles del dispositivo, páginas de complementos). La aplicación omite por completo los complementos ignorados. Los complementos de detección de dispositivos insertan valores en la tabla de base de datos "CurrentScan". Es seguro ignorar los complementos que no son necesarios; sin embargo, tiene sentido tener habilitados al menos algunos complementos de detección de dispositivos (que insertan entradas en la tabla `CurrentScan`), como ARPSCAN o PIHOLE.
|
||||
|
||||
> Se recomienda utilizar el mismo intervalo de programación para todos los complementos responsables de descubrir nuevos dispositivos.
|
||||
|
||||
## 🌟 Crear un plugin personalizado: Descripción general
|
||||
|
||||
| ![Screen 1][screen1] | ![Screen 2][screen2] | ![Screen 3][screen3] |
|
||||
|----------------------|----------------------| ----------------------|
|
||||
| ![Screen 4][screen4] | ![Screen 5][screen5] |
|
||||
|
||||
PiAlert viene con un sistema de complementos para enviar eventos desde scripts de terceros a la interfaz de usuario y luego enviar notificaciones, si lo desea. La funcionalidad principal destacada que admite este sistema de complementos es:
|
||||
|
||||
* creación dinámica de una interfaz de usuario simple para interactuar con los objetos descubiertos,
|
||||
* filtrado de valores mostrados en la interfaz de usuario de dispositivos
|
||||
* configuración superficial de complementos en la interfaz de usuario,
|
||||
* diferentes tipos de columnas para los valores informados, por ejemplo. vincular de nuevo a un dispositivo
|
||||
* importar objetos a tablas de bases de datos PiAlert existentes
|
||||
|
||||
> (Actualmente, no se admite la actualización/sobrescritura de objetos existentes..)
|
||||
|
||||
Ejemplos de casos de uso de plugins podrían ser:
|
||||
|
||||
* Monitorear un servicio web y avisarme si está caído
|
||||
* Importar dispositivos desde archivos dhcp.leases en lugar/complementario al uso de PiHole o arp-scans
|
||||
* Creación de tablas de UI ad-hoc a partir de datos existentes en la base de datos PiAlert, p.e. para mostrar todos los puertos abiertos en los dispositivos, para enumerar los dispositivos que se desconectaron en la última hora, etc.
|
||||
* Usar otros métodos de descubrimiento de dispositivos en la red e importar los datos como dispositivos nuevos
|
||||
* Creación de un script para crear dispositivos FALSOS según la entrada del usuario a través de configuraciones personalizadas
|
||||
* ...en este punto, la limitación es más la creatividad que la capacidad (puede haber casos extremos y la necesidad de admitir más controles de formulario para la entrada del usuario fuera de las configuraciones personalizadas, pero probablemente se entienda la idea)
|
||||
|
||||
Si desea desarrollar un plugin, verifique la estructura del complemento existente. Una vez que el usuario guarda la configuración, debe eliminarla manualmente del archivo `pialert.conf` si desea reinicializarla desde el `config.json` del complemento.
|
||||
|
||||
Nuevamente, lea atentamente lo siguiente si desea contribuir usted mismo con un complemento. Este archivo de documentación puede estar desactualizado, así que verifique también los complementos de muestra.
|
||||
|
||||
## ⚠ Aviso legal
|
||||
|
||||
Siga lo siguiente con mucho cuidado y consulte los plugin(s) de ejemplo si desea escribir uno usted mismo. La interfaz de usuario del complemento no es mi prioridad en este momento, y estaré encantado de aprobar PRs si está interesado en ampliar/mejorar la experiencia de la interfaz de usuario. Mejoras de ejemplo para tomar:
|
||||
|
||||
* Hacer que las tablas se puedan ordenar/filtrar
|
||||
* Utilizar el mismo enfoque para mostrar los datos de la tabla que en la sección Dispositivos (resuelve arriba)
|
||||
* Agregar controles de formulario admitidos para mostrar los datos (los actualmente admitidos se enumeran en la sección "Configuración de la interfaz de usuario en definiciones de columna de base de datos" a continuación)
|
||||
*...
|
||||
|
||||
## ❗ Problemas conocidos:
|
||||
|
||||
Es de esperar que estos problemas se solucionen con el tiempo, así que no los informe. En cambio, si sabe cómo, no dude en investigar y enviar un PR para solucionar lo siguiente. Mantenga los RP pequeños ya que es más fácil aprobarlos:
|
||||
|
||||
* Los objetos de plugins existentes a veces no se interpretan correctamente y en su lugar se crea un nuevo objeto, lo que genera entradas duplicadas.
|
||||
* Ocasionalmente (experimentado dos veces) se cuelga el archivo de script del complemento de procesamiento.
|
||||
La interfaz de usuario muestra valores obsoletos hasta que se actualizan los puntos finales de la API.
|
||||
|
||||
## Descripción general de la estructura del archivo del plugin
|
||||
|
||||
> ⚠️El nombre de la carpeta debe ser el mismo que el valor del nombre del código en: `"code_name": "<value>"`
|
||||
> El prefijo único debe ser único en comparación con los otros prefijos de configuración, por ejemplo: el prefijo `APPRISE` ya está en uso.
|
||||
|
||||
| Archivo | Requerido (tipo de plugin) | Descripción |
|
||||
|----------------------|----------------------|----------------------|
|
||||
| `config.json` | Sí | Contiene la configuración del complemento (manifiesto), incluida la configuración disponible para el usuario. |
|
||||
| `script.py` | Sí (script) | El script Python en sí |
|
||||
| `last_result.log` | Sí (script) |El archivo utilizado para la interfaz entre PiAlert y el plugin (script). |
|
||||
| `script.log` | No | Salida de registro (recomendado) |
|
||||
| `README.md` | No | Cualquier consideración de configuración o descripción general (recomendado) |
|
||||
|
||||
Más sobre detalles a continuación.
|
||||
|
||||
### Orden de columnas y valores
|
||||
|
||||
| Orden | Columna representada | Requerido | Descripción |
|
||||
|----------------------|----------------------|----------------------|----------------------|
|
||||
| 0 | `Object_PrimaryID` | Sí | El ID principal utilizado para agrupar eventos en. |
|
||||
| 1 | `Object_SecondaryID` | No | ID secundaria opcional para crear una relación entre otras entidades, como una dirección MAC |
|
||||
| 2 | `DateTime` | Sí | Cuando el evento ocurrió en el formato `2023-01-02 15:56:30` |
|
||||
| 3 | `Watched_Value1` | Sí | Un valor que se observa y los usuarios pueden recibir notificaciones si cambia en comparación con la entrada guardada anteriormente. Por ejemplo dirección IP |
|
||||
| 4 | `Watched_Value2` | No | Como en el caso anterior |
|
||||
| 5 | `Watched_Value3` | No | Como en el caso anterior |
|
||||
| 6 | `Watched_Value4` | No | Como en el caso anterior |
|
||||
| 7 | `Extra` | No | Cualquier otro dato que desee pasar y mostrar en PiAlert y las notificaciones |
|
||||
| 8 | `ForeignKey` | No | Una clave externa que se puede utilizar para vincular al objeto principal (normalmente una dirección MAC) |
|
||||
|
||||
> [!NOTE]
|
||||
> La deduplicación se ejecuta una vez por hora en la tabla de base de datos `Plugins_Objects` y las entradas duplicadas con el mismo valor en las columnas `Object_PrimaryID`, `Object_SecondaryID`, `Plugin` (autocompletadas según el `unique_prefix` del complemento), Se eliminan los `UserData` (que se pueden completar con el tipo de columna `"type": "textbox_save"`).
|
||||
# Estructura config.json
|
||||
|
||||
## Fuentes de datos admitidas
|
||||
|
||||
Actualmente, estas fuentes de datos son compatibles (valid `data_source` value).
|
||||
|
||||
| Nombre | `data_source` valor | Necesita devolver una "tabla" | Descripción general (más detalles en esta página a continuación) |
|
||||
|----------------------|----------------------|----------------------|----------------------|
|
||||
| Script | `script` | No | Ejecuta cualquier comando de Linux en la configuración `CMD`. |
|
||||
| Pialert DB query | `pialert-db-query` | Sí | Ejecuta una consulta SQL en la base de datos PiAlert en la configuración `CMD`. |
|
||||
| Template | `template` | No | Se utiliza para generar configuraciones internas, como valores predeterminados. |
|
||||
| External SQLite DB query | `sqlite-db-query` | Sí | Ejecuta una consulta SQL desde la configuración `CMD` en una base de datos SQLite externa asignada en la configuración `DB_PATH`. |
|
||||
|
||||
|
||||
> 🔎Ejemplo
|
||||
>```json
|
||||
>"data_source": "pialert-db-query"
|
||||
>```
|
||||
Cualquiera de las fuentes de datos anteriores debe devolver una "tabla" con la estructura exacta descrita anteriormente.
|
||||
|
||||
Puede mostrar u ocultar la interfaz de usuario en la página "Complementos" y en la pestaña "Complementos" en los dispositivos a través de la propiedad `show_ui`:
|
||||
|
||||
> 🔎Ejemplo
|
||||
>```json
|
||||
> "show_ui": true,
|
||||
> ```
|
||||
|
||||
### "data_source": "script"
|
||||
|
||||
Si `data_source` está configurado en `script`, la configuración `CMD` (que usted especifica en la sección de matriz `settings` en `config.json`) debe contener un comando ejecutable de Linux, que genera un `last_result.log `archivo. Este archivo debe almacenarse en la misma carpeta que el complemento.
|
||||
|
||||
El contenido del archivo `last_result.log` debe contener las columnas tal como se definen en la sección "Orden y valores de las columnas" anterior. El orden de las columnas no se puede cambiar. Después de cada escaneo, debe contener solo los resultados del último escaneo/ejecución.
|
||||
|
||||
- El formato de `last_result.log` es un archivo tipo `csv` con la tubería `|` como separador.
|
||||
- Es necesario suministrar 9 (nueve) valores, por lo que cada línea debe contener 8 separadores de tuberías. Los valores vacíos se representan con "nulo".
|
||||
- No muestre "encabezados" para estas "columnas".
|
||||
- Cada resultado del escaneo/entrada de evento debe estar en una nueva línea.
|
||||
- Puede encontrar qué "columnas" deben estar presentes y si el valor es obligatorio u opcional, en la sección "Orden de columnas y valores".
|
||||
- El orden de estas "columnas" no se puede cambiar.
|
||||
|
||||
### 👍 Consejos para Python script.py
|
||||
|
||||
El [Undicoverables plugins `script.py` file](/front/plugins/undiscoverables/script.py) es un ejemplo bueno y simple para comenzar si está considerando crear un complemento personalizado. Utiliza la [`plugin_helper.py` library](/front/plugins/plugin_helper.py) que simplifica significativamente la creación de su script personalizado.
|
||||
|
||||
#### 🔎 Ejemplos de last_result.log
|
||||
|
||||
CSV válido:
|
||||
|
||||
```csv
|
||||
|
||||
https://www.google.com|null|2023-01-02 15:56:30|200|0.7898|null|null|null|null
|
||||
https://www.duckduckgo.com|192.168.0.1|2023-01-02 15:56:30|200|0.9898|null|null|Best search engine|ff:ee:ff:11:ff:11
|
||||
|
||||
```
|
||||
|
||||
CSV no válido con diferentes errores en cada línea:
|
||||
|
||||
```csv
|
||||
|
||||
https://www.google.com|null|2023-01-02 15:56:30|200|0.7898||null|null|null
|
||||
https://www.duckduckgo.com|null|2023-01-02 15:56:30|200|0.9898|null|null|Best search engine|
|
||||
|https://www.duckduckgo.com|null|2023-01-02 15:56:30|200|0.9898|null|null|Best search engine|null
|
||||
null|192.168.1.1|2023-01-02 15:56:30|200|0.9898|null|null|Best search engine
|
||||
https://www.duckduckgo.com|192.168.1.1|2023-01-02 15:56:30|null|0.9898|null|null|Best search engine
|
||||
https://www.google.com|null|2023-01-02 15:56:30|200|0.7898|||
|
||||
https://www.google.com|null|2023-01-02 15:56:30|200|0.7898|
|
||||
|
||||
```
|
||||
|
||||
### "data_source": "pialert-db-query"
|
||||
|
||||
Si `data_source` está configurado en `pialert-db-query`, la configuración `CMD` debe contener una consulta SQL que represente las columnas como se define en la sección "Orden y valores de las columnas" anterior. El orden de las columnas es importante.
|
||||
|
||||
Esta consulta SQL se ejecuta en el archivo de base de datos SQLite `pialert.db`.
|
||||
|
||||
> 🔎Ejemplo
|
||||
>
|
||||
> SQL query example:
|
||||
>
|
||||
> ```SQL
|
||||
> SELECT dv.dev_Name as Object_PrimaryID,
|
||||
> cast(dv.dev_LastIP as VARCHAR(100)) || ':' || cast( SUBSTR(ns.Port ,0, INSTR(ns.Port , '/')) as VARCHAR(100)) as Object_SecondaryID,
|
||||
> datetime() as DateTime,
|
||||
> ns.Service as Watched_Value1,
|
||||
> ns.State as Watched_Value2,
|
||||
> 'null' as Watched_Value3,
|
||||
> 'null' as Watched_Value4,
|
||||
> ns.Extra as Extra,
|
||||
> dv.dev_MAC as ForeignKey
|
||||
> FROM
|
||||
> (SELECT * FROM Nmap_Scan) ns
|
||||
> LEFT JOIN
|
||||
> (SELECT dev_Name, dev_MAC, dev_LastIP FROM Devices) dv
|
||||
> ON ns.MAC = dv.dev_MAC
|
||||
> ```
|
||||
>
|
||||
> Ejemplo de configuración de `CMD` requerida con la consulta anterior (puede configurar `"type": "label"` si desea que no se pueda editar en la interfaz de usuario):
|
||||
>
|
||||
> ```json
|
||||
> {
|
||||
> "function": "CMD",
|
||||
> "type": "text",
|
||||
> "default_value":"SELECT dv.dev_Name as Object_PrimaryID, cast(dv.dev_LastIP as VARCHAR(100)) || ':' || cast( SUBSTR(ns.Port ,0, INSTR(ns.Port , '/')) as VARCHAR(100)) as Object_SecondaryID, datetime() as DateTime, ns.Service as Watched_Value1, ns.State as Watched_Value2, 'null' as Watched_Value3, 'null' as Watched_Value4, ns.Extra as Extra FROM (SELECT * FROM Nmap_Scan) ns LEFT JOIN (SELECT dev_Name, dev_MAC, dev_LastIP FROM Devices) dv ON ns.MAC = dv.dev_MAC",
|
||||
> "options": [],
|
||||
> "localized": ["name", "description"],
|
||||
> "name" : [{
|
||||
> "language_code":"en_us",
|
||||
> "string" : "SQL to run"
|
||||
> }],
|
||||
> "description": [{
|
||||
> "language_code":"en_us",
|
||||
> "string" : "This SQL query is used to populate the coresponding UI tables under the Plugins section."
|
||||
> }]
|
||||
> }
|
||||
> ```
|
||||
|
||||
### "data_source": "template"
|
||||
|
||||
Se utiliza para inicializar la configuración interna. Consulte el plugin `newdev_template` para obtener más detalles.
|
||||
|
||||
### "data_source": "sqlite-db-query"
|
||||
|
||||
Puede ejecutar una consulta SQL en una base de datos externa conectada a la base de datos PiALert actual mediante un prefijo temporal `EXTERNAL.`. El archivo de base de datos SQLite externo debe asignarse en el contenedor a la ruta especificada en la configuración `DB_PATH`:
|
||||
|
||||
> 🔎Ejemplo
|
||||
>
|
||||
>```json
|
||||
> ...
|
||||
>{
|
||||
> "function": "DB_PATH",
|
||||
> "type": "readonly",
|
||||
> "default_value":"/etc/pihole/pihole-FTL.db",
|
||||
> "options": [],
|
||||
> "localized": ["name", "description"],
|
||||
> "name" : [{
|
||||
> "language_code":"en_us",
|
||||
> "string" : "DB Path"
|
||||
> }],
|
||||
> "description": [{
|
||||
> "language_code":"en_us",
|
||||
> "string" : "Required setting for the <code>sqlite-db-query</code> plugin type. Is used to mount an external SQLite database and execute the SQL query stored in the <code>CMD</code> setting."
|
||||
> }]
|
||||
> }
|
||||
> ...
|
||||
>```
|
||||
|
||||
La consulta SQL real que desea ejecutar se almacena como una configuración "CMD", similar al tipo de complemento "pialert-db-query".
|
||||
|
||||
> 🔎Ejemplo
|
||||
>
|
||||
> Observe el prefijo "EXTERNO".
|
||||
>
|
||||
>```json
|
||||
>{
|
||||
> "function": "CMD",
|
||||
> "type": "text",
|
||||
> "default_value":"SELECT hwaddr as Object_PrimaryID, cast('http://' || (SELECT ip FROM EXTERNAL.network_addresses WHERE network_id = id ORDER BY lastseen DESC, ip LIMIT 1) as VARCHAR(100)) || ':' || cast( SUBSTR((SELECT name FROM EXTERNAL.network_addresses WHERE network_id = id ORDER BY lastseen DESC, ip LIMIT 1), 0, INSTR((SELECT name FROM EXTERNAL.network_addresses WHERE network_id = id ORDER BY lastseen DESC, ip LIMIT 1), '/')) as VARCHAR(100)) as Object_SecondaryID, datetime() as DateTime, macVendor as Watched_Value1, lastQuery as Watched_Value2, (SELECT name FROM EXTERNAL.network_addresses WHERE network_id = id ORDER BY lastseen DESC, ip LIMIT 1) as Watched_Value3, 'null' as Watched_Value4, '' as Extra, hwaddr as ForeignKey FROM EXTERNAL.network WHERE hwaddr NOT LIKE 'ip-%' AND hwaddr <> '00:00:00:00:00:00'; ",
|
||||
> "options": [],
|
||||
> "localized": ["name", "description"],
|
||||
> "name" : [{
|
||||
> "language_code":"en_us",
|
||||
> "string" : "SQL to run"
|
||||
> }],
|
||||
> "description": [{
|
||||
> "language_code":"en_us",
|
||||
> "string" : "This SQL query is used to populate the coresponding UI tables under the Plugins section. This particular one selects data from a mapped PiHole SQLite database and maps it to the corresponding Plugin columns."
|
||||
> }]
|
||||
> }
|
||||
> ```
|
||||
|
||||
## 🕳 Filtros
|
||||
|
||||
Las entradas de complementos se pueden filtrar según los valores ingresados en los campos de filtro. El cuadro de texto/campo `txtMacFilter` contiene la dirección Mac del dispositivo actualmente visto o simplemente una dirección Mac que está disponible en la cadena de consulta `mac`.
|
||||
|
||||
| Propiedad | Requerido | Descripción |
|
||||
|----------------------|----------------------|----------------------|
|
||||
| `compare_column` | Sí | El nombre de la columna del complemento cuyo valor se utiliza para comparar (**Lado izquierdo** de la ecuación) |
|
||||
| `compare_operator` | Sí | Operador de comparación de JavaScript |
|
||||
| `compare_field_id` | Sí | El `id` de un campo de texto de entrada que contiene un valor se utiliza para comparar (**Lado derecho** de la ecuación)|
|
||||
| `compare_js_template` | Sí | Código JavaScript utilizado para convertir el lado izquierdo y derecho de la ecuación. `{valor}` se reemplaza con valores de entrada. |
|
||||
| `compare_use_quotes` | Sí | Si es "verdadero", entonces el resultado final de "compare_js_template" lo envolví entre comillas `"`. Úselo para comparar cadenas. |
|
||||
|
||||
|
||||
> 🔎Ejemplo:
|
||||
>
|
||||
> ```json
|
||||
> "data_filters": [
|
||||
> {
|
||||
> "compare_column" : "Object_PrimaryID",
|
||||
> "compare_operator" : "==",
|
||||
> "compare_field_id": "txtMacFilter",
|
||||
> "compare_js_template": "'{value}'.toString()",
|
||||
> "compare_use_quotes": true
|
||||
> }
|
||||
> ],
|
||||
> ```
|
||||
|
||||
1. En la página `pluginsCore.php` hay un campo de entrada con el ID `txtMacFilter`:
|
||||
|
||||
```html
|
||||
<input class="form-control" id="txtMacFilter" type="text" value="--">
|
||||
```
|
||||
|
||||
2. Este campo de entrada se inicializa mediante la cadena de consulta `&mac=`.
|
||||
|
||||
3. Luego, la aplicación procede a utilizar este valor de Mac de este campo y lo compara con el valor del campo de la base de datos `Object_PrimaryID`. El `compare_operator` es `==`.
|
||||
|
||||
4. Ambos valores, del campo de la base de datos `Object_PrimaryID` y del `txtMacFilter` se empaquetan y evalúan con `compare_js_template`, es decir, `'{value}.toString()'`.
|
||||
|
||||
5. `compare_use_quotes` está establecido en `true`, por lo que `'{value}'.toString()` está entre comillas `"`.
|
||||
|
||||
6. Esto da como resultado, por ejemplo, este código:
|
||||
|
||||
```javascript
|
||||
// left part of teh expression coming from compare_column and right from the input field
|
||||
// notice the added quotes ()") around the left and right part of teh expression
|
||||
"eval('ac:82:ac:82:ac:82".toString()')" == "eval('ac:82:ac:82:ac:82".toString()')"
|
||||
```
|
||||
|
||||
7. Los filtros solo se aplican si se especifica un filtro y `txtMacFilter` no está `indefinido` ni está vacío (`--`).
|
||||
|
||||
### 🗺 Mapear los resultados del complemento en una tabla de base de datos
|
||||
|
||||
PiAlert tomará los resultados de la ejecución del complemento e insertará estos resultados en una tabla de base de datos, si un complemento contiene la propiedad `"mapped_to_table"` en la raíz `config.json`. El mapeo de las columnas se define en la matriz `database_column_definitions`.
|
||||
|
||||
Este enfoque se utiliza para implementar el complemento "DHCPLSS". El script analiza todos los archivos "dhcp.leases" proporcionados, obtiene los resultados en el formato de tabla genérica descrito en la sección "Orden y valores de las columnas" anterior y toma valores individuales y los inserta en la tabla de base de datos `"CurrentScan"` en PiAlert. base de datos. Todo esto se logra mediante:
|
||||
|
||||
> [!NOTE]
|
||||
> Si los resultados se asignan a la tabla "CurrentScan", los datos se incluyen en el ciclo de escaneo normal, por lo que, por ejemplo, se envían notificaciones para los dispositivos.
|
||||
|
||||
1) Especificar la tabla de la base de datos en la que se insertan los resultados definiendo `"mapped_to_table": "CurrentScan"` en la raíz del archivo `config.json` como se muestra a continuación:
|
||||
|
||||
```json
|
||||
{
|
||||
"code_name": "dhcp_leases",
|
||||
"unique_prefix": "DHCPLSS",
|
||||
...
|
||||
"data_source": "script",
|
||||
"localized": ["display_name", "description", "icon"],
|
||||
"mapped_to_table": "CurrentScan",
|
||||
...
|
||||
}
|
||||
```
|
||||
|
||||
2) Definir la columna de destino con la propiedad `mapped_to_column` para columnas individuales en la matriz `database_column_definitions` del archivo `config.json`. Por ejemplo, en el complemento `DHCPLSS`, necesitaba asignar el valor de la columna `Object_PrimaryID` devuelta por el complemento a la columna `cur_MAC` en la tabla `CurrentScan` de la base de datos PiAlert. Observe el par clave-valor `"mapped_to_column": "cur_MAC"` en el siguiente ejemplo.
|
||||
|
||||
```json
|
||||
{
|
||||
"column": "Object_PrimaryID",
|
||||
"mapped_to_column": "cur_MAC",
|
||||
"css_classes": "col-sm-2",
|
||||
"show": true,
|
||||
"type": "device_mac",
|
||||
"default_value":"",
|
||||
"options": [],
|
||||
"localized": ["name"],
|
||||
"name":[{
|
||||
"language_code":"en_us",
|
||||
"string" : "MAC address"
|
||||
}]
|
||||
}
|
||||
```
|
||||
|
||||
3) Eso es todo. PiAlert se encarga del resto. Recorre los objetos descubiertos por el complemento, toma los resultados línea por línea y los inserta en la tabla de la base de datos especificada en `"mapped_to_table"`. Las columnas se traducen de las columnas del complemento genérico a la tabla de destino a través de la propiedad `"mapped_to_column"` en las definiciones de las columnas.
|
||||
|
||||
#### Parámetros
|
||||
|
||||
La matriz `params` en `config.json` se utiliza para permitir al usuario cambiar los parámetros del script ejecutado. Por ejemplo, el usuario quiere monitorear una URL específica.
|
||||
|
||||
> 🔎 Ejemplo:
|
||||
> Pasar configuraciones definidas por el usuario a un comando. Digamos que desea tener un script que se llame con un parámetro definido por el usuario llamado "urls":
|
||||
>
|
||||
> ```bash
|
||||
> root@server# python3 /home/pi/pialert/front/plugins/website_monitor/script.py urls=https://google.com,https://duck.com
|
||||
> ```
|
||||
|
||||
* Puede permitir que el usuario agregue URL a una configuración con la propiedad `función` establecida en un nombre personalizado, como `urls_to_check` (este no es un nombre reservado de la sección "Configuraciones admitidas valores de `función`" a continuación).
|
||||
* Usted especifica el parámetro `urls` en la sección `params` de `config.json` de la siguiente manera (`WEBMON_` es el prefijo del complemento que se agrega automáticamente a todas las configuraciones):
|
||||
```json
|
||||
{
|
||||
"params" : [
|
||||
{
|
||||
"name" : "urls",
|
||||
"type" : "setting",
|
||||
"value" : "WEBMON_urls_to_check"
|
||||
}]
|
||||
}
|
||||
```
|
||||
* Luego usa esta configuración como parámetro de entrada para su comando en la configuración `CMD`. Observe `urls={urls}` en el siguiente json:
|
||||
|
||||
```json
|
||||
{
|
||||
"function": "CMD",
|
||||
"type": "text",
|
||||
"default_value":"python3 /home/pi/pialert/front/plugins/website_monitor/script.py urls={urls}",
|
||||
"options": [],
|
||||
"localized": ["name", "description"],
|
||||
"name" : [{
|
||||
"language_code":"en_us",
|
||||
"string" : "Command"
|
||||
}],
|
||||
"description": [{
|
||||
"language_code":"en_us",
|
||||
"string" : "Command to run"
|
||||
}]
|
||||
}
|
||||
```
|
||||
|
||||
Durante la ejecución del script, la aplicación tomará el comando `"python3 /home/pi/pialert/front/plugins/website_monitor/script.py urls={urls}"`, tomará el comodín `{urls}` y lo reemplazará con el valor de la configuración `WEBMON_urls_to_check`. Esto es porque:
|
||||
1) La aplicación verifica las entradas de "parámetros".
|
||||
2) Encuentra `"nombre": "urls"`
|
||||
3) Comprueba el tipo de parámetros de `urls` y encuentra`"type" : "setting"`
|
||||
4) Obtiene el nombre de la configuración de `"value" : "WEBMON_urls_to_check"`
|
||||
- IMPORTANTE: en `config.json` esta configuración se identifica con `"function":"urls_to_check"`, not `"function":"WEBMON_urls_to_check"`
|
||||
- También puedes usar una configuración global o una configuración de un complemento diferente
|
||||
5) The app gets the user defined value from the setting with the code name `WEBMON_urls_to_check`
|
||||
- digamos la configuración con el nombre en clave `WEBMON_urls_to_check` contiene 2 valores ingresados por el usuario:
|
||||
- `WEBMON_urls_to_check=['https://google.com','https://duck.com']`
|
||||
6) La aplicación toma el valor de `WEBMON_urls_to_check` y reemplaza el comodín `{urls}` en la configuración donde `"function":"CMD"`, por lo que pasas de:
|
||||
- `python3 /home/pi/pialert/front/plugins/website_monitor/script.py urls={urls}`
|
||||
- to
|
||||
- `python3 /home/pi/pialert/front/plugins/website_monitor/script.py urls=https://google.com,https://duck.com`
|
||||
|
||||
A continuación se muestran algunas notas adicionales generales al definir "parámetros":
|
||||
|
||||
- `"name":"name_value"` - se utiliza como reemplazo de comodín en el valor de configuración `CMD` mediante el uso de llaves `{name_value}`. El comodín se reemplaza por el resultado de la configuración combinada `"valor": "param_value"` y `"type":"type_value"` a continuación.
|
||||
- `"type":"<sql|setting>"` - se utiliza para especificar el tipo de parámetros, actualmente solo se admiten 2 (`sql`,`setting`).
|
||||
- `"type":"sql"` - ejecutará la consulta SQL especificada en la propiedad `valor`. La consulta SQL debe devolver solo una columna. La columna está aplanada y separada por comas (`,`), por ejemplo: `SELECT dev_MAC from DEVICES` -> `Internet,74:ac:74:ac:74:ac,44:44:74:ac:74:ac `. Luego se usa para reemplazar los comodines en la configuración "CMD".
|
||||
- `"type":"setting"` - El nombre del código de configuración. Una combinación del valor de `unique_prefix` + `_` + valor de `function`, o de lo contrario, el nombre del código que puede encontrar en la página Configuración bajo el nombre para mostrar de configuración, p. `PIHOLE_RUN`.
|
||||
- `"value" : "param_value"` - Debe contener un nombre de código de configuración o una consulta SQL sin comodines.
|
||||
|
||||
|
||||
> 🔎Ejemplo:
|
||||
>
|
||||
> ```json
|
||||
> {
|
||||
> "params" : [{
|
||||
> "name" : "macs",
|
||||
> "type" : "sql",
|
||||
> "value" : "SELECT dev_MAC from DEVICES"
|
||||
> },
|
||||
> {
|
||||
> "name" : "urls",
|
||||
> "type" : "setting",
|
||||
> "value" : "WEBMON_urls_to_check"
|
||||
> },
|
||||
> {
|
||||
> "name" : "internet_ip",
|
||||
> "type" : "setting",
|
||||
> "value" : "WEBMON_SQL_internet_ip"
|
||||
> }]
|
||||
> }
|
||||
> ```
|
||||
|
||||
|
||||
#### ⚙ Configuración de la estructura del objeto
|
||||
|
||||
> [!NOTE]
|
||||
> El flujo de configuración y cuándo se aplican las configuraciones específicas del complemento se describen en la sección [Settings system](/docs/SETTINGS_SYSTEM.md).
|
||||
|
||||
Los atributos requeridos son:
|
||||
|
||||
- `"function": "<see Supported settings function values>"` - ¿Qué función maneja la configuración o un nombre de código único y simple?
|
||||
- `"type": "<text|integer|boolean|password|readonly|integer.select|text.select|text.multiselect|list|integer.checkbox|text.template>"` - El control de formulario utilizado para la configuración que se muestra en la página Configuración y qué valores se aceptan.
|
||||
- `"localized"` - una lista de propiedades en el nivel JSON actual que deben localizarse
|
||||
- `"name"` y `"description"` - Se muestra en la página de Configuración. Una serie de cadenas localizadas. (consulte Cadenas localizadas a continuación).
|
||||
- (optional) `"events"` - `<test|run>` - para generar un botón de ejecución al lado del campo de entrada de la configuración (no probado completamente)
|
||||
- (optional) `"override_value"` - se utiliza para determinar una anulación definida por el usuario para la configuración. Útil para complementos basados en plantillas, donde puede optar por dejar el valor actual o anularlo con el valor definido en la configuración. (trabajo en progreso)
|
||||
- (optional) `"events": ["run", "test"]` - utilizado para activar el complemento. Generalmente se usa en la configuración "EJECUTAR". No probado completamente en todos los escenarios. Mostrará un botón de reproducción al lado de la configuración y luego, después de hacer clic, se generará un evento para el backend en la tabla de la base de datos "Parámetros" para procesar el evento del front-end en la siguiente ejecución.
|
||||
|
||||
##### Valores de `función` de configuraciones admitidas
|
||||
|
||||
Puede tener cualquier nombre personalizado `"function": "my_custom_name"`; sin embargo, los que se enumeran a continuación tienen una funcionalidad específica adjunta. Si usa un nombre personalizado, la configuración se usa principalmente como parámetro de entrada para la sección `params`.
|
||||
|
||||
- `RUN` - (requerido) Especifica cuándo se ejecuta el servicio.
|
||||
- Opciones soportadas:
|
||||
- "disabled" - no ejecutar
|
||||
- "once" - ejecutar al iniciar la aplicación o en la configuración guardada
|
||||
- "schedule" - Si se incluye, se debe especificar una configuración `RUN_SCHD` para determinar cuál es el cronograma,
|
||||
- "always_after_scan" - Se ejecuta siempre después de finalizar un escaneo
|
||||
- "on_new_device" - Se ejecuta cuando se detecta un nuevo dispositivo
|
||||
- "before_config_save" - Se ejecuta antes de que la configuración se marque como guardada. Útil si su complemento necesita modificar el archivo `pialert.conf`.
|
||||
- `RUN_SCHD` - (requerido si incluye la función `RUN` anterior) La programación tipo cron se utiliza si la configuración `RUN` está establecida en `schedule`
|
||||
- `CMD` - (requerido) Qué comando se debe ejecutar.
|
||||
- `API_SQL` - (opcional) Genera una `table_` + code_name + `.json` archivo según [API docs](https://github.com/jokob-sk/NetAlertX/blob/main/docs/API.md).
|
||||
- `RUN_TIMEOUT` - (opcional) Tiempo máximo de ejecución del script. Si no se especifica, se utiliza un valor predeterminado de 10 segundos para evitar que se cuelgue.
|
||||
- `WATCH` - (opcional) Qué columnas de la base de datos se vigilan en busca de cambios para este complemento en particular. Si no se especifica no se envían notificaciones.
|
||||
- `REPORT_ON` - (opcional) Envíe una notificación solo sobre estos estados. Las opciones admitidas son:
|
||||
- `new` significa que se descubrió un nuevo objeto único (combinación única de PrimaryId y SecondaryId).
|
||||
- `watched-changed` - significa que las columnas seleccionadas `Watched_ValueN` cambiaron
|
||||
- `watched-not-changed` - informes incluso en eventos donde el `Watched_ValueN` seleccionado no cambió
|
||||
- `missing-in-last-scan` - si falta el objeto en comparación con escaneos anteriores
|
||||
|
||||
|
||||
> 🔎 Ejemplo:
|
||||
>
|
||||
> ```json
|
||||
> {
|
||||
> "function": "RUN",
|
||||
> "type": "text.select",
|
||||
> "default_value":"disabled",
|
||||
> "options": ["disabled", "once", "schedule", "always_after_scan", "on_new_device"],
|
||||
> "localized": ["name", "description"],
|
||||
> "name" :[{
|
||||
> "language_code":"en_us",
|
||||
> "string" : "When to run"
|
||||
> }],
|
||||
> "description": [{
|
||||
> "language_code":"en_us",
|
||||
> "string" : "Enable a regular scan of your services. If you select <code>schedule</code> the scheduling settings from below are applied. If you select <code>once</code> the scan is run only once on start of the application (container) for the time specified in <a href=\"#WEBMON_RUN_TIMEOUT\"><code>WEBMON_RUN_TIMEOUT</code> setting</a>."
|
||||
> }]
|
||||
> }
|
||||
> ```
|
||||
|
||||
##### 🌍Cadenas localizadas
|
||||
|
||||
- `"language_code":"<en_us|es_es|de_de>"` - nombre de código de la cadena de idioma. Actualmente sólo se admiten estos tres. Al menos se debe definir la variante `"language_code":"en_us"`.
|
||||
- `"string"` - La cadena que se mostrará en el idioma especificado.
|
||||
|
||||
> 🔎 Ejemplo:
|
||||
>
|
||||
> ```json
|
||||
>
|
||||
> {
|
||||
> "language_code":"en_us",
|
||||
> "string" : "When to run"
|
||||
> }
|
||||
>
|
||||
> ```
|
||||
|
||||
##### Configuración de la UI en Database_column_definitions
|
||||
|
||||
La interfaz de usuario ajustará cómo se muestran las columnas en función de la definición del objeto `database_column_definitions`. Estos son los controles de formulario admitidos y la funcionalidad relacionada:
|
||||
|
||||
- Solo las columnas con `"show": true` y también con al menos una traducción al inglés se mostrarán en la interfaz de usuario.
|
||||
- Tipos soportados: `label`, `text`, `threshold`, `replace`, `device_ip`, `device_mac`, `url`. Consulte los detalles a continuación sobre cómo se comportan las columnas según el tipo.
|
||||
- `label` hace que solo se muestre una columna
|
||||
- `text` hace que una columna sea editable y se muestra un icono de guardar junto a ella.
|
||||
- Consulte a continuación para obtener información sobre "umbral", "reemplazar"
|
||||
- La propiedad `opciones` se utiliza junto con estos tipos:
|
||||
- `threshold` - La matriz `opciones` contiene objetos desde el `máximo` más bajo hasta el más alto con el `hexColor` correspondiente usado para el color de fondo del valor si es menor que el `máximo` especificado, pero mayor que el anterior en la matriz `opciones`
|
||||
- `replace` - La matriz `opciones` contiene objetos con una propiedad `equals`, que se compara con el "valor" y si los valores son los mismos, la cadena en "reemplazo" se muestra en la interfaz de usuario en lugar del "valor" real
|
||||
- `device_mac` - El valor se considera una dirección Mac y se genera un enlace que apunta al dispositivo con la dirección Mac proporcionada.
|
||||
- `device_ip` - El valor se considera una dirección IP y se genera un enlace que apunta al dispositivo con la IP dada. La IP se compara con las últimas direcciones IP detectadas y se traduce a una dirección Mac que luego se usa para el enlace en sí.
|
||||
- `url` - El valor se considera una URL por lo que se genera un enlace.
|
||||
- `textbox_save` - Se genera un cuadro de texto editable y guardable que guarda los valores en la base de datos. Diseñado principalmente para la columna de base de datos "UserData" en la tabla "Plugins_Objects".
|
||||
|
||||
|
||||
```json
|
||||
{
|
||||
"column": "Watched_Value1",
|
||||
"css_classes": "col-sm-2",
|
||||
"show": true,
|
||||
"type": "threshold",
|
||||
"default_value":"",
|
||||
"options": [
|
||||
{
|
||||
"maximum": 199,
|
||||
"hexColor": "#792D86"
|
||||
},
|
||||
{
|
||||
"maximum": 299,
|
||||
"hexColor": "#5B862D"
|
||||
},
|
||||
{
|
||||
"maximum": 399,
|
||||
"hexColor": "#7D862D"
|
||||
},
|
||||
{
|
||||
"maximum": 499,
|
||||
"hexColor": "#BF6440"
|
||||
},
|
||||
{
|
||||
"maximum": 599,
|
||||
"hexColor": "#D33115"
|
||||
}
|
||||
],
|
||||
"localized": ["name"],
|
||||
"name":[{
|
||||
"language_code":"en_us",
|
||||
"string" : "Status code"
|
||||
}]
|
||||
},
|
||||
{
|
||||
"column": "Status",
|
||||
"show": true,
|
||||
"type": "replace",
|
||||
"default_value":"",
|
||||
"options": [
|
||||
{
|
||||
"equals": "watched-not-changed",
|
||||
"replacement": "<i class='fa-solid fa-square-check'></i>"
|
||||
},
|
||||
{
|
||||
"equals": "watched-changed",
|
||||
"replacement": "<i class='fa-solid fa-triangle-exclamation'></i>"
|
||||
},
|
||||
{
|
||||
"equals": "new",
|
||||
"replacement": "<i class='fa-solid fa-circle-plus'></i>"
|
||||
}
|
||||
],
|
||||
"localized": ["name"],
|
||||
"name":[{
|
||||
"language_code":"en_us",
|
||||
"string" : "Status"
|
||||
}]
|
||||
}
|
||||
```
|
||||
|
||||
|
||||
|
||||
[screen1]: https://raw.githubusercontent.com/jokob-sk/NetAlertX/main/docs/img/plugins.png "Screen 1"
|
||||
[screen2]: https://raw.githubusercontent.com/jokob-sk/NetAlertX/main/docs/img/plugins_settings.png "Screen 2"
|
||||
[screen3]: https://raw.githubusercontent.com/jokob-sk/NetAlertX/main/docs/img/plugins_json_settings.png "Screen 3"
|
||||
[screen4]: https://raw.githubusercontent.com/jokob-sk/NetAlertX/main/docs/img/plugins_json_ui.png "Screen 4"
|
||||
[screen5]: https://raw.githubusercontent.com/jokob-sk/NetAlertX/main/docs/img/plugins_device_details.png "Screen 5"
|
||||
@@ -8,10 +8,11 @@ import pathlib
|
||||
import sys
|
||||
from datetime import datetime
|
||||
|
||||
# Replace these paths with the actual paths to your NetAlertX directories
|
||||
sys.path.extend(["/home/pi/pialert/front/plugins", "/home/pi/pialert/pialert"])
|
||||
# Register NetAlertX directories
|
||||
sys.path.extend(["/home/pi/pialert/front/plugins", "/home/pi/pialert/netalertx"])
|
||||
|
||||
import conf
|
||||
from const import confFileName
|
||||
from plugin_helper import Plugin_Objects
|
||||
from logger import mylog, append_line_to_file
|
||||
from helper import timeNowTZ, get_setting_value
|
||||
@@ -19,6 +20,7 @@ from notification import Notification_obj
|
||||
from database import DB
|
||||
|
||||
|
||||
|
||||
CUR_PATH = str(pathlib.Path(__file__).parent.resolve())
|
||||
RESULT_FILE = os.path.join(CUR_PATH, 'last_result.log')
|
||||
|
||||
@@ -30,7 +32,7 @@ def main():
|
||||
|
||||
# Check if basic config settings supplied
|
||||
if check_config() == False:
|
||||
mylog('none', [f'[{pluginName}] ⚠ ERROR: Publisher notification gateway not set up correctly. Check your pialert.conf {pluginName}_* variables.'])
|
||||
mylog('none', [f'[{pluginName}] ⚠ ERROR: Publisher notification gateway not set up correctly. Check your {confFileName} {pluginName}_* variables.'])
|
||||
return
|
||||
|
||||
# Create a database connection
|
||||
|
||||
@@ -15,10 +15,11 @@ import smtplib
|
||||
import socket
|
||||
import ssl
|
||||
|
||||
sys.path.extend(["/home/pi/pialert/front/plugins", "/home/pi/pialert/pialert"])
|
||||
sys.path.extend(["/home/pi/pialert/front/plugins", "/home/pi/pialert/netalertx"])
|
||||
|
||||
# PiAlert modules
|
||||
# NetAlertX modules
|
||||
import conf
|
||||
from const import confFileName
|
||||
from plugin_helper import Plugin_Objects
|
||||
from logger import mylog, append_line_to_file, print_log
|
||||
from helper import timeNowTZ, get_setting_value, hide_email
|
||||
@@ -37,7 +38,7 @@ def main():
|
||||
|
||||
# Check if basic config settings supplied
|
||||
if check_config() == False:
|
||||
mylog('none', [f'[{pluginName}] ⚠ ERROR: Publisher notification gateway not set up correctly. Check your pialert.conf {pluginName}_* variables.'])
|
||||
mylog('none', [f'[{pluginName}] ⚠ ERROR: Publisher notification gateway not set up correctly. Check your {confFileName} {pluginName}_* variables.'])
|
||||
return
|
||||
|
||||
# Create a database connection
|
||||
@@ -81,7 +82,7 @@ def check_config ():
|
||||
report_from = get_setting_value("SMTP_REPORT_FROM")
|
||||
|
||||
if server == '' or report_from == '' or report_to == '':
|
||||
mylog('none', ['[Email Check Config] ⚠ ERROR: Email service not set up correctly. Check your pialert.conf SMTP_*, SMTP_REPORT_FROM and SMTP_REPORT_TO variables.'])
|
||||
mylog('none', [f'[Email Check Config] ⚠ ERROR: Email service not set up correctly. Check your {confFileName} SMTP_*, SMTP_REPORT_FROM and SMTP_REPORT_TO variables.'])
|
||||
return False
|
||||
else:
|
||||
return True
|
||||
|
||||
@@ -15,12 +15,12 @@ import paho.mqtt.client as mqtt
|
||||
import hashlib
|
||||
|
||||
|
||||
# Replace these paths with the actual paths to your NetAlertX directories
|
||||
sys.path.extend(["/home/pi/pialert/front/plugins", "/home/pi/pialert/pialert"])
|
||||
# Register NetAlertX directories
|
||||
sys.path.extend(["/home/pi/pialert/front/plugins", "/home/pi/pialert/netalertx"])
|
||||
|
||||
# PiAlert modules
|
||||
# NetAlertX modules
|
||||
import conf
|
||||
from const import apiPath
|
||||
from const import apiPath, confFileName
|
||||
from plugin_utils import getPluginObject
|
||||
from plugin_helper import Plugin_Objects
|
||||
from logger import mylog, append_line_to_file
|
||||
@@ -52,7 +52,7 @@ def main():
|
||||
|
||||
# Check if basic config settings supplied
|
||||
if check_config() == False:
|
||||
mylog('verbose', [f'[{pluginName}] ⚠ ERROR: Publisher notification gateway not set up correctly. Check your pialert.conf {pluginName}_* variables.'])
|
||||
mylog('verbose', [f'[{pluginName}] ⚠ ERROR: Publisher notification gateway not set up correctly. Check your {confFileName} {pluginName}_* variables.'])
|
||||
return
|
||||
|
||||
# Create a database connection
|
||||
@@ -71,7 +71,7 @@ def main():
|
||||
#-------------------------------------------------------------------------------
|
||||
def check_config():
|
||||
if get_setting_value('MQTT_BROKER') == '' or get_setting_value('MQTT_PORT') == '' or get_setting_value('MQTT_USER') == '' or get_setting_value('MQTT_PASSWORD') == '':
|
||||
mylog('verbose', ['[Check Config] ⚠ ERROR: MQTT service not set up correctly. Check your pialert.conf MQTT_* variables.'])
|
||||
mylog('verbose', [f'[Check Config] ⚠ ERROR: MQTT service not set up correctly. Check your {confFileName} MQTT_* variables.'])
|
||||
return False
|
||||
else:
|
||||
return True
|
||||
@@ -281,7 +281,7 @@ def mqtt_start(db):
|
||||
|
||||
# Create a generic device for overal stats
|
||||
if get_setting_value('MQTT_SEND_STATS') == True:
|
||||
# Create a new device representing overall PiAlert stats
|
||||
# Create a new device representing overall stats
|
||||
create_generic_device(mqtt_client)
|
||||
|
||||
# Get the data
|
||||
|
||||
@@ -11,10 +11,11 @@ import requests
|
||||
from datetime import datetime
|
||||
from base64 import b64encode
|
||||
|
||||
# Replace these paths with the actual paths to your NetAlertX directories
|
||||
sys.path.extend(["/home/pi/pialert/front/plugins", "/home/pi/pialert/pialert"])
|
||||
# Register NetAlertX directories
|
||||
sys.path.extend(["/home/pi/pialert/front/plugins", "/home/pi/pialert/netalertx"])
|
||||
|
||||
import conf
|
||||
from const import confFileName
|
||||
from plugin_helper import Plugin_Objects, handleEmpty
|
||||
from logger import mylog, append_line_to_file
|
||||
from helper import timeNowTZ, get_setting_value
|
||||
@@ -33,7 +34,7 @@ def main():
|
||||
|
||||
# Check if basic config settings supplied
|
||||
if check_config() == False:
|
||||
mylog('none', [f'[{pluginName}] ⚠ ERROR: Publisher notification gateway not set up correctly. Check your pialert.conf {pluginName}_* variables.'])
|
||||
mylog('none', [f'[{pluginName}] ⚠ ERROR: Publisher notification gateway not set up correctly. Check your {confFileName} {pluginName}_* variables.'])
|
||||
return
|
||||
|
||||
# Create a database connection
|
||||
|
||||
@@ -5,14 +5,16 @@ import sys
|
||||
import json
|
||||
import requests
|
||||
|
||||
# Replace these paths with the actual paths to your NetAlertX directories
|
||||
sys.path.extend(["/home/pi/pialert/front/plugins", "/home/pi/pialert/pialert"])
|
||||
# Register NetAlertX directories
|
||||
sys.path.extend(["/home/pi/pialert/front/plugins", "/home/pi/pialert/netalertx"])
|
||||
|
||||
from plugin_helper import Plugin_Objects, handleEmpty # noqa: E402
|
||||
from logger import mylog # noqa: E402
|
||||
from helper import timeNowTZ, get_setting_value, hide_string # noqa: E402
|
||||
from notification import Notification_obj # noqa: E402
|
||||
from database import DB # noqa: E402
|
||||
import conf
|
||||
from const import confFileName
|
||||
|
||||
CUR_PATH = str(pathlib.Path(__file__).parent.resolve())
|
||||
RESULT_FILE = os.path.join(CUR_PATH, "last_result.log")
|
||||
@@ -28,7 +30,7 @@ def main():
|
||||
mylog(
|
||||
"none",
|
||||
f"[{pluginName}] ⚠ ERROR: Publisher notification gateway not set up correctly. "
|
||||
f"Check your pialert.conf {pluginName}_* variables.",
|
||||
f"Check your {confFileName} {pluginName}_* variables.",
|
||||
)
|
||||
return
|
||||
|
||||
|
||||
@@ -11,10 +11,11 @@ import requests
|
||||
from datetime import datetime
|
||||
from base64 import b64encode
|
||||
|
||||
# Replace these paths with the actual paths to your NetAlertX directories
|
||||
sys.path.extend(["/home/pi/pialert/front/plugins", "/home/pi/pialert/pialert"])
|
||||
# Register NetAlertX directories
|
||||
sys.path.extend(["/home/pi/pialert/front/plugins", "/home/pi/pialert/netalertx"])
|
||||
|
||||
import conf
|
||||
from const import confFileName
|
||||
from plugin_helper import Plugin_Objects, handleEmpty
|
||||
from logger import mylog, append_line_to_file
|
||||
from helper import timeNowTZ, get_setting_value, hide_string
|
||||
@@ -32,7 +33,7 @@ def main():
|
||||
|
||||
# Check if basic config settings supplied
|
||||
if check_config() == False:
|
||||
mylog('none', [f'[{pluginName}] ⚠ ERROR: Publisher notification gateway not set up correctly. Check your pialert.conf {pluginName}_* variables.'])
|
||||
mylog('none', [f'[{pluginName}] ⚠ ERROR: Publisher notification gateway not set up correctly. Check your {confFileName} {pluginName}_* variables.'])
|
||||
return
|
||||
|
||||
# Create a database connection
|
||||
|
||||
@@ -13,12 +13,12 @@ from base64 import b64encode
|
||||
import hashlib
|
||||
import hmac
|
||||
|
||||
# Replace these paths with the actual paths to your NetAlertX directories
|
||||
sys.path.extend(["/home/pi/pialert/front/plugins", "/home/pi/pialert/pialert"])
|
||||
# Register NetAlertX directories
|
||||
sys.path.extend(["/home/pi/pialert/front/plugins", "/home/pi/pialert/netalertx"])
|
||||
|
||||
|
||||
# pialert modules
|
||||
import conf
|
||||
from const import logPath
|
||||
from const import logPath, confFileName
|
||||
from plugin_helper import Plugin_Objects, handleEmpty
|
||||
from logger import mylog, append_line_to_file
|
||||
from helper import timeNowTZ, get_setting_value, hide_string, write_file
|
||||
@@ -36,7 +36,7 @@ def main():
|
||||
|
||||
# Check if basic config settings supplied
|
||||
if check_config() == False:
|
||||
mylog('none', [f'[{pluginName}] ⚠ ERROR: Publisher notification gateway not set up correctly. Check your pialert.conf {pluginName}_* variables.'])
|
||||
mylog('none', [f'[{pluginName}] ⚠ ERROR: Publisher notification gateway not set up correctly. Check your {confFileName} {pluginName}_* variables.'])
|
||||
return
|
||||
|
||||
# Create a database connection
|
||||
|
||||
@@ -1,12 +0,0 @@
|
||||
## Übersicht
|
||||
|
||||
ARP-Scan ist ein Kommandozeilen-Werkzeug, welches das ARP-Protokoll nutzt, um IP-Hosts im lokalen Netzwerk zu erkennen und identifizieren. Eine Alternative zum ARP-Scan ist die Aktivierung der PiHole-Integration (`PIHOLE_RUN`) in den Einstellungen. Die Dauer des ARP-Scan (und andere Netzwerkscan-Plugins, welche die `SCAN_SUBNETS`-Einstellung nutzen) ist abhängig von der Anzahl der zu prüfenden IP-Adressen. Daher ist es wichtig, dies mit größter Vorsicht und den korrekten Netzwerkmasken und -interfaces zu konfigurieren. Die [Subnetz-Dokumentation](https://github.com/jokob-sk/NetAlertX/blob/main/docs/SUBNETS.md) ansehen für mehr Hilfe zum Aufsetzen von VLANs, welche VLANs unterstützt werden und zum Herausfinden der Netzwerkmaske und -interfaces.
|
||||
|
||||
### Verwendung
|
||||
|
||||
- Zur Einstellungen-Seite gehen und die `SCAN_SUBNETS`-Einstellung anhand der [Subnetz-Dokumentation](https://github.com/jokob-sk/NetAlertX/blob/main/docs/SUBNETS.md) konfigurieren
|
||||
- Das Plugin aktivieren, indem der `RUN`-Parameter von `disabled` auf den gewünschten Ausführzeitpunkt gesetzt wird (normalerweise: `schedule`)
|
||||
- Zeitplan in der `ARPSCAN_RUN_SCHD`-Einstellung setzen
|
||||
- Zeitlimit nach Bedarf in der `ARPSCAN_RUN_TIMEOUT`-Einstellung setzen
|
||||
- SPEICHERN
|
||||
- Auf Ausführung des nächsten Scans warten
|
||||
@@ -1,13 +0,0 @@
|
||||
## Descripción general
|
||||
|
||||
Arp-scan es una herramienta de línea de comandos que utiliza el protocolo ARP para descubrir y tomar huellas digitales de hosts IP en la red local. Una alternativa al escaneo ARP es habilitar la configuración de integración de PiHole `PIHOLE_RUN`. El tiempo de arp-scan (y otros tiempos del complemento de escaneo de red que utilizan la configuración `SCAN_SUBNETS`) depende de la cantidad de direcciones IP a verificar, así que configúrelo cuidadosamente con la interfaz y la máscara de red adecuadas. Consulte la [documentación de subredes](https://github.com/jokob-sk/NetAlertX/blob/main/docs/SUBNETS.md) para obtener ayuda sobre cómo configurar VLAN, qué VLAN son compatibles o cómo averiguarlo. la máscara de red y su interfaz.
|
||||
|
||||
### Uso
|
||||
|
||||
- Vaya a la configuración y establezca la configuración `SCAN_SUBNETS` según la [documentación de subredes](https://github.com/jokob-sk/NetAlertX/blob/main/docs/SUBNETS.md).
|
||||
- Habilite el complemento cambiando el parámetro RUN de deshabilitado a su tiempo de ejecución preferido (generalmente: `schedule`).
|
||||
- Especifique el horario en la configuración `ARPSCAN_RUN_SCHD`
|
||||
- Ajuste el tiempo de espera si es necesario en la configuración `ARPSCAN_RUN_TIMEOUT`
|
||||
- Revisar las configuraciones restantes
|
||||
- Guardar
|
||||
- Espere a que finalice el siguiente escaneo.
|
||||
@@ -10,14 +10,14 @@ import subprocess
|
||||
from time import strftime
|
||||
|
||||
sys.path.append("/home/pi/pialert/front/plugins")
|
||||
sys.path.append('/home/pi/pialert/pialert')
|
||||
sys.path.append('/home/pi/pialert/netalertx')
|
||||
|
||||
# pialert modules
|
||||
# Register NetAlertX modules NetAlertX directories
|
||||
from database import DB
|
||||
from plugin_helper import Plugin_Object, Plugin_Objects, handleEmpty
|
||||
from logger import mylog, append_line_to_file
|
||||
from helper import timeNowTZ, get_setting_value
|
||||
from const import logPath, pialertPath
|
||||
from const import logPath, applicationPath
|
||||
|
||||
CUR_PATH = str(pathlib.Path(__file__).parent.resolve())
|
||||
LOG_FILE = os.path.join(CUR_PATH, 'script.log')
|
||||
@@ -25,9 +25,7 @@ RESULT_FILE = os.path.join(CUR_PATH, 'last_result.log')
|
||||
|
||||
|
||||
def main():
|
||||
# sample
|
||||
# /home/pi/pialert/front/plugins/arp_scan/script.py userSubnets=b'MTkyLjE2OC4xLjAvMjQgLS1pbnRlcmZhY2U9ZXRoMQ=='
|
||||
# the script expects a parameter in the format of userSubnets=subnet1,subnet2,...
|
||||
|
||||
parser = argparse.ArgumentParser(description='Import devices from settings')
|
||||
parser.add_argument('userSubnets', nargs='+', help="list of subnets with options")
|
||||
values = parser.parse_args()
|
||||
|
||||
@@ -1,19 +0,0 @@
|
||||
### Community-Übersetzungen dieser Datei
|
||||
|
||||
<a href="https://github.com/jokob-sk/NetAlertX/blob/main/front/plugins/csv_backup/README.md">
|
||||
<img src="https://github.com/lipis/flag-icons/blob/main/flags/4x3/us.svg" alt="README.md" style="height: 20px !important;width: 20px !important;">
|
||||
Englisch (Amerikanisch)
|
||||
</a>
|
||||
<br>
|
||||
<a href="https://github.com/jokob-sk/NetAlertX/blob/main/front/plugins/csv_backup/README_ES.md">
|
||||
<img src="https://github.com/lipis/flag-icons/blob/main/flags/4x3/es.svg" alt="README_ES.md" style="height: 20px !important;width: 20px !important;">
|
||||
Spanisch (Spanien)
|
||||
</a>
|
||||
|
||||
## Überblick
|
||||
|
||||
Plugin zur Erstellung von CSV-Backups Ihrer Gerätedatenbanktabelle, einschließlich der Netzwerkzuordnungen. Kann zum Importieren Ihres Setups über die Funktion Wartung > Sichern / Wiederherstellen > CSV-Import verwendet werden.
|
||||
|
||||
### Verwendung
|
||||
|
||||
- Wenn die Datei devices.csv überschrieben oder dem Namen ein Zeitstempel für Datum und Uhrzeit hinzugefügt werden kann. Dies wird mit der Einstellung "CSVBCKP_overwrite" umgeschaltet.
|
||||
@@ -1,19 +0,0 @@
|
||||
### Traducciones comunitarias de este archivo
|
||||
|
||||
<a href="https://github.com/jokob-sk/NetAlertX/blob/main/front/plugins/csv_backup/README.md">
|
||||
<img src="https://github.com/lipis/flag-icons/blob/main/flags/4x3/us.svg" alt="README.md" style="height: 20px !important;width: 20px !important;">
|
||||
Ingles (Americano)
|
||||
</a>
|
||||
<br>
|
||||
<a href="https://github.com/jokob-sk/NetAlertX/blob/main/front/plugins/csv_backup/README_DE.md">
|
||||
<img src="https://github.com/lipis/flag-icons/blob/main/flags/4x3/de.svg" alt="README_DE.md" style="height: 20px !important;width: 20px !important;">
|
||||
Aleman (Alemania)
|
||||
</a>
|
||||
|
||||
## Descripción general
|
||||
|
||||
Plugin que genera copias de seguridad CSV de la tabla de base de datos de sus dispositivos, incluidas las asignaciones de red. Se puede utilizar para importar su configuración a través de la función Mantenimiento > Copia de seguridad / Restauración > Importación CSV.
|
||||
|
||||
### Uso
|
||||
|
||||
- Si el archivo devices.csv se puede sobrescribir o se puede agregar la marca de tiempo y fecha al nombre. Esto se alterna con la configuración `CSVBCKP_overwrite`.
|
||||
@@ -1,6 +1,4 @@
|
||||
#!/usr/bin/env python
|
||||
# test script by running:
|
||||
# /home/pi/pialert/front/plugins/csv_backup/script.py overwrite=False location=/home/pi/pialert/config
|
||||
|
||||
import os
|
||||
import pathlib
|
||||
@@ -13,12 +11,12 @@ from io import StringIO
|
||||
from datetime import datetime
|
||||
|
||||
sys.path.append("/home/pi/pialert/front/plugins")
|
||||
sys.path.append('/home/pi/pialert/pialert')
|
||||
sys.path.append('/home/pi/pialert/netalertx')
|
||||
|
||||
from plugin_helper import Plugin_Object, Plugin_Objects, decodeBase64
|
||||
from logger import mylog, append_line_to_file
|
||||
from helper import timeNowTZ
|
||||
from const import logPath, pialertPath, fullDbPath
|
||||
from const import logPath, applicationPath, fullDbPath
|
||||
|
||||
|
||||
CUR_PATH = str(pathlib.Path(__file__).parent.resolve())
|
||||
@@ -42,7 +40,7 @@ def main():
|
||||
|
||||
mylog('verbose', ['[CSVBCKP] In script'])
|
||||
|
||||
# Connect to the PiAlert SQLite database
|
||||
# Connect to the App database
|
||||
conn = sqlite3.connect(fullDbPath)
|
||||
cursor = conn.cursor()
|
||||
|
||||
|
||||
@@ -1,6 +1,4 @@
|
||||
#!/usr/bin/env python
|
||||
# test script by running:
|
||||
# /home/pi/pialert/front/plugins/db_cleanup/script.py pluginskeephistory=250 hourstokeepnewdevice=48 daystokeepevents=90 pholuskeepdays=30
|
||||
|
||||
import os
|
||||
import pathlib
|
||||
@@ -13,12 +11,12 @@ from io import StringIO
|
||||
from datetime import datetime
|
||||
|
||||
sys.path.append("/home/pi/pialert/front/plugins")
|
||||
sys.path.append('/home/pi/pialert/pialert')
|
||||
sys.path.append('/home/pi/pialert/netalertx')
|
||||
|
||||
from plugin_helper import Plugin_Object, Plugin_Objects, decodeBase64
|
||||
from logger import mylog, append_line_to_file
|
||||
from helper import timeNowTZ, get_setting_value
|
||||
from const import logPath, pialertPath, fullDbPath
|
||||
from const import logPath, applicationPath, fullDbPath
|
||||
|
||||
|
||||
CUR_PATH = str(pathlib.Path(__file__).parent.resolve())
|
||||
@@ -62,7 +60,7 @@ def cleanup_database (dbPath, DAYS_TO_KEEP_EVENTS, PHOLUS_DAYS_DATA, HRS_TO_KEEP
|
||||
|
||||
mylog('verbose', [f'[{pluginName}] Upkeep Database:' ])
|
||||
|
||||
# Connect to the PiAlert SQLite database
|
||||
# Connect to the App database
|
||||
conn = sqlite3.connect(dbPath)
|
||||
cursor = conn.cursor()
|
||||
|
||||
|
||||
@@ -1,6 +1,4 @@
|
||||
#!/usr/bin/env python
|
||||
# test script by running:
|
||||
# /home/pi/pialert/front/plugins/internet_ip/script.py TBD
|
||||
|
||||
import os
|
||||
import pathlib
|
||||
@@ -16,12 +14,12 @@ from io import StringIO
|
||||
from datetime import datetime
|
||||
|
||||
sys.path.append("/home/pi/pialert/front/plugins")
|
||||
sys.path.append('/home/pi/pialert/pialert')
|
||||
sys.path.append('/home/pi/pialert/netalertx')
|
||||
|
||||
from plugin_helper import Plugin_Object, Plugin_Objects, decodeBase64
|
||||
from logger import mylog, append_line_to_file
|
||||
from helper import timeNowTZ, check_IP_format
|
||||
from const import logPath, pialertPath, fullDbPath
|
||||
from const import logPath, applicationPath, fullDbPath
|
||||
|
||||
|
||||
CUR_PATH = str(pathlib.Path(__file__).parent.resolve())
|
||||
|
||||
@@ -1,51 +0,0 @@
|
||||
## Übersicht
|
||||
|
||||
Ein Plugin zum Importieren von Geräten aus dhcp.leases-Dateien.
|
||||
|
||||
### Verwendung
|
||||
|
||||
- Absolute Pfade der `dhcp.leases`-Dateien, welche importiert werden sollen, in der `DHCPLSS_paths_to_check`-Einstellung angeben.
|
||||
- Angegebene Pfade in der `DHCPLSS_paths_to_check`-Einstellung in der `docker-compose.yml`-Datei mapppen.
|
||||
|
||||
#### Beispiel
|
||||
|
||||
Auszug aus `docker-compose.yml`:
|
||||
|
||||
```yaml
|
||||
volumes:
|
||||
...
|
||||
# mapping different dhcp.leases files
|
||||
- /first/location/dhcp.leases:/mnt/dhcp1.leases
|
||||
- /second/location/dhcp.leases:/mnt/dhcp2.leases
|
||||
...
|
||||
```
|
||||
|
||||
`DHCPLSS_paths_to_check`-Einstellung:
|
||||
|
||||
```python
|
||||
DHCPLSS_paths_to_check = ['/mnt/dhcp1.leases','/mnt/dhcp2.leases']
|
||||
```
|
||||
|
||||
### Notizen
|
||||
|
||||
- Keine spezifische Konfiguration benötigt.
|
||||
|
||||
- Dieses Plugin erwartet dhcp.leases-Dateien im **dhcp.leases**-Format, welches sich vom von PiHole genutzten Format unterscheidet. [dhcpd.leases(5) - Linux man page]( https://linux.die.net/man/5/dhcpd.leases#:~:text=This%20database%20is%20a%20free,file%20is%20the%20current%20one.)
|
||||
|
||||
Beispiel Dateiformat: _(nicht alle Zeilen werden benötigt)_
|
||||
|
||||
```text
|
||||
lease 192.168.79.15 {
|
||||
starts 0 2016/08/21 13:25:45;
|
||||
ends 0 2016/08/21 19:25:45;
|
||||
cltt 0 2016/08/21 13:25:45;
|
||||
binding state active;
|
||||
next binding state free;
|
||||
rewind binding state free;
|
||||
hardware ethernet 8c:1a:bf:11:00:ea;
|
||||
uid "\001\214\032\277\021\000\352";
|
||||
option agent.circuit-id 0:17;
|
||||
option agent.remote-id c0:a8:9:5;
|
||||
client-hostname "android-8182e21c852776e7";
|
||||
}
|
||||
```
|
||||
@@ -1,53 +0,0 @@
|
||||
## Descripción general
|
||||
|
||||
Un plugin que permite importar dispositivos desde archivos DHCP.leases.
|
||||
|
||||
### Uso
|
||||
|
||||
- Especifique las rutas completas de todos los archivos `dhcp.leases` que desea importar y observar en la configuración `DHCPLSS_paths_to_check`.
|
||||
- Asigne las rutas especificadas en la configuración `DHCPLSS_paths_to_check` en su archivo `docker-compose.yml`.
|
||||
|
||||
#### Ejemplo:
|
||||
|
||||
|
||||
Extracto `docker-compose.yml`:
|
||||
|
||||
```yaml
|
||||
volumes:
|
||||
...
|
||||
# Mapeo de diferentes archivos dhcp.leases
|
||||
- /first/location/dhcp.leases:/mnt/dhcp1.leases
|
||||
- /second/location/dhcp.leases:/mnt/dhcp2.leases
|
||||
...
|
||||
```
|
||||
|
||||
Configuración `DHCPLSS_paths_to_check`:
|
||||
|
||||
```python
|
||||
DHCPLSS_paths_to_check = ['/mnt/dhcp1.leases','/mnt/dhcp2.leases']
|
||||
```
|
||||
|
||||
### Notas
|
||||
|
||||
- No se necesita ninguna configuración específica.
|
||||
|
||||
- Este complemento espera que los archivos dhcp.leases tengan el formato **dhcpd.leases**, que es diferente al formato que utiliza PiHole.
|
||||
[dhcpd.leases(5) - Linux man page]( https://linux.die.net/man/5/dhcpd.leases#:~:text=This%20database%20is%20a%20free,file%20is%20the%20current%20one.)
|
||||
|
||||
Formato de archivo de ejemplo: _(no todas las líneas son obligatorias)_
|
||||
|
||||
```
|
||||
lease 192.168.79.15 {
|
||||
starts 0 2016/08/21 13:25:45;
|
||||
ends 0 2016/08/21 19:25:45;
|
||||
cltt 0 2016/08/21 13:25:45;
|
||||
binding state active;
|
||||
next binding state free;
|
||||
rewind binding state free;
|
||||
hardware ethernet 8c:1a:bf:11:00:ea;
|
||||
uid "\001\214\032\277\021\000\352";
|
||||
option agent.circuit-id 0:17;
|
||||
option agent.remote-id c0:a8:9:5;
|
||||
client-hostname "android-8182e21c852776e7";
|
||||
}
|
||||
```
|
||||
@@ -9,7 +9,7 @@ import sys
|
||||
import chardet
|
||||
|
||||
sys.path.append("/home/pi/pialert/front/plugins")
|
||||
sys.path.append('/home/pi/pialert/pialert')
|
||||
sys.path.append('/home/pi/pialert/netalertx')
|
||||
|
||||
from plugin_helper import Plugin_Object, Plugin_Objects, handleEmpty, is_mac
|
||||
from logger import mylog
|
||||
|
||||
@@ -1,11 +0,0 @@
|
||||
## Descripción general
|
||||
|
||||
Un plugin de muestra simple que permite detectar servidores DHCP no autorizados en la red.
|
||||
|
||||
### Uso
|
||||
|
||||
- No se necesita ninguna configuración específica.
|
||||
|
||||
### Notas
|
||||
|
||||
- No se necesita ninguna configuración específica.
|
||||
@@ -7,7 +7,7 @@ from datetime import datetime
|
||||
import sys
|
||||
|
||||
sys.path.append("/home/pi/pialert/front/plugins")
|
||||
sys.path.append('/home/pi/pialert/pialert')
|
||||
sys.path.append('/home/pi/pialert/netalertx')
|
||||
|
||||
from plugin_helper import Plugin_Objects, Plugin_Object
|
||||
from logger import mylog
|
||||
|
||||
@@ -1,7 +0,0 @@
|
||||
## Übersicht
|
||||
|
||||
Ein Plugin zur regelmäßigen Prüfung der Internetverbindung und externen IP.
|
||||
|
||||
### Verwendung
|
||||
|
||||
- Einstellungen-Seite für Details ansehen.
|
||||
@@ -1,6 +1,4 @@
|
||||
#!/usr/bin/env python
|
||||
# test script by running:
|
||||
# /home/pi/pialert/front/plugins/internet_ip/script.py TBD
|
||||
|
||||
import os
|
||||
import pathlib
|
||||
@@ -16,12 +14,12 @@ from io import StringIO
|
||||
from datetime import datetime
|
||||
|
||||
sys.path.append("/home/pi/pialert/front/plugins")
|
||||
sys.path.append('/home/pi/pialert/pialert')
|
||||
sys.path.append('/home/pi/pialert/netalertx')
|
||||
|
||||
from plugin_helper import Plugin_Object, Plugin_Objects, decodeBase64
|
||||
from logger import mylog, append_line_to_file
|
||||
from helper import timeNowTZ, check_IP_format, get_setting_value
|
||||
from const import logPath, pialertPath, fullDbPath
|
||||
from const import logPath, applicationPath, fullDbPath
|
||||
|
||||
|
||||
CUR_PATH = str(pathlib.Path(__file__).parent.resolve())
|
||||
|
||||
@@ -1,3 +0,0 @@
|
||||
## Übersicht
|
||||
|
||||
Ein Plugin zur periodischen Durchführung von Internetgeschwindigkeitstests.
|
||||
@@ -7,8 +7,8 @@ import sys
|
||||
from datetime import datetime
|
||||
import speedtest
|
||||
|
||||
# Replace these paths with the actual paths to your NetAlertX directories
|
||||
sys.path.extend(["/home/pi/pialert/front/plugins", "/home/pi/pialert/pialert"])
|
||||
# Register NetAlertX directories
|
||||
sys.path.extend(["/home/pi/pialert/front/plugins", "/home/pi/pialert/netalertx"])
|
||||
|
||||
from plugin_helper import Plugin_Objects
|
||||
from logger import mylog, append_line_to_file
|
||||
|
||||
@@ -1,11 +0,0 @@
|
||||
## Descripción general
|
||||
|
||||
Un plugin sencillo basado en plantillas para dispositivos conocidos. Puede cambiar para sobrescribir los valores de los dispositivos conocidos.
|
||||
|
||||
### Uso
|
||||
|
||||
- Dirígete a **Configuración** > **Dispositivos conocidos** para ajustar los valores predeterminados.
|
||||
|
||||
### Notas
|
||||
|
||||
- Este plugin genera configuraciones editables que luego se usan en el script `device.py` para inicializar nuevos valores. ARREGLAR
|
||||
@@ -1,6 +1,4 @@
|
||||
#!/usr/bin/env python
|
||||
# test script by running:
|
||||
# /home/pi/pialert/front/plugins/maintenance/maintenance.py
|
||||
|
||||
import os
|
||||
import pathlib
|
||||
@@ -13,13 +11,13 @@ from io import StringIO
|
||||
from datetime import datetime
|
||||
from collections import deque
|
||||
|
||||
sys.path.extend(["/home/pi/pialert/front/plugins", "/home/pi/pialert/pialert"])
|
||||
sys.path.extend(["/home/pi/pialert/front/plugins", "/home/pi/pialert/netalertx"])
|
||||
|
||||
# pialert modules
|
||||
# Register NetAlertX modules NetAlertX directories
|
||||
from plugin_helper import Plugin_Object, Plugin_Objects, decodeBase64
|
||||
from logger import mylog, append_line_to_file
|
||||
from helper import timeNowTZ, get_setting_value
|
||||
from const import logPath, pialertPath
|
||||
from const import logPath, applicationPath
|
||||
|
||||
|
||||
CUR_PATH = str(pathlib.Path(__file__).parent.resolve())
|
||||
|
||||
@@ -1,11 +0,0 @@
|
||||
## Descripción general
|
||||
|
||||
Un plugin simple basado en plantillas para dispositivos nuevos. Puede cambiar los valores predeterminados para los dispositivos recién detectados.
|
||||
|
||||
### Uso
|
||||
|
||||
- Dirígete a **Configuración** > **Nuevos dispositivos** para ajustar los valores predeterminados.
|
||||
|
||||
### Notas
|
||||
|
||||
- Este plugin genera configuraciones editables que luego se usan en el script `device.py` para inicializar nuevos valores.
|
||||
@@ -1,11 +0,0 @@
|
||||
## Descripción general
|
||||
|
||||
Este plugin muestra todos los servicios descubiertos mediante análisis NMAP regulares. También es un complemento de muestra que muestra cómo usar una consulta SQL para mostrar datos existentes de la base de datos PiAlert.
|
||||
|
||||
### Uso
|
||||
|
||||
- La consulta SQL de la configuración `NMAPSRV_CMD` se utiliza para crear datos de origen para este complemento. El orden de las columnas y los valores deben cumplir con los especificados en la [documentación](https://github.com/jokob-sk/NetAlertX/tree/main/front/plugins).
|
||||
|
||||
### Notas
|
||||
|
||||
- N / A
|
||||
@@ -10,12 +10,12 @@ import subprocess
|
||||
from time import strftime
|
||||
|
||||
sys.path.append("/home/pi/pialert/front/plugins")
|
||||
sys.path.append('/home/pi/pialert/pialert')
|
||||
sys.path.append('/home/pi/pialert/netalertx')
|
||||
|
||||
from plugin_helper import Plugin_Object, Plugin_Objects, decodeBase64
|
||||
from logger import mylog, append_line_to_file
|
||||
from helper import timeNowTZ
|
||||
from const import logPath, pialertPath
|
||||
from const import logPath, applicationPath
|
||||
|
||||
CUR_PATH = str(pathlib.Path(__file__).parent.resolve())
|
||||
LOG_FILE = os.path.join(CUR_PATH, 'script.log')
|
||||
@@ -23,8 +23,6 @@ RESULT_FILE = os.path.join(CUR_PATH, 'last_result.log')
|
||||
|
||||
#-------------------------------------------------------------------------------
|
||||
def main():
|
||||
# sample
|
||||
# /home/pi/pialert/front/plugins/nmap_scan/script.py ips=192.168.1.66,192.168.1.9'
|
||||
parser = argparse.ArgumentParser(description='Scan ports of devices specified by IP addresses')
|
||||
parser.add_argument('ips', nargs='+', help="list of IPs to scan")
|
||||
parser.add_argument('macs', nargs='+', help="list of MACs related to the supplied IPs in the same order")
|
||||
|
||||
@@ -15,12 +15,12 @@ from io import StringIO
|
||||
from datetime import datetime
|
||||
|
||||
sys.path.append("/home/pi/pialert/front/plugins")
|
||||
sys.path.append('/home/pi/pialert/pialert')
|
||||
sys.path.append('/home/pi/pialert/netalertx')
|
||||
|
||||
from plugin_helper import Plugin_Object, Plugin_Objects, decodeBase64
|
||||
from logger import mylog, append_line_to_file
|
||||
from helper import timeNowTZ, get_setting_value
|
||||
from const import logPath, pialertPath, fullDbPath
|
||||
from const import logPath, applicationPath, fullDbPath
|
||||
from database import DB
|
||||
from device import Device_obj
|
||||
|
||||
|
||||
@@ -1,11 +0,0 @@
|
||||
## Descripción general
|
||||
|
||||
Un plugin para resolver nombres de dispositivos "(desconocidos)". Utiliza la herramienta de rastreo [Pholus](https://github.com/jokob-sk/NetAlertX/tree/main/front/plugins/pholus_scan/pholus).
|
||||
|
||||
### Uso
|
||||
|
||||
- Vaya a configuración y busque Pholus-Scan (descubrimiento de nombre) en la lista de configuraciones.
|
||||
- Habilite el complemento cambiando el parámetro `RUN` de deshabilitado a uno que prefiera (`schedule`, `always_after_scan`, `on_new_device`).
|
||||
- Especifique `PHOLUS_RUN_TIMEOUT` (se dividirá por el número de subredes especificadas en la configuración del complemento Arp-Scan (escaneo de red) `SCAN_SUBNETS`)
|
||||
- GUARDAR
|
||||
- Espere a que finalice el siguiente escaneo.
|
||||
@@ -11,12 +11,12 @@ from time import strftime
|
||||
|
||||
|
||||
sys.path.append("/home/pi/pialert/front/plugins")
|
||||
sys.path.append('/home/pi/pialert/pialert')
|
||||
sys.path.append('/home/pi/pialert/netalertx')
|
||||
|
||||
from logger import mylog
|
||||
from plugin_helper import Plugin_Object, Plugin_Objects
|
||||
from helper import timeNowTZ
|
||||
from const import logPath, pialertPath
|
||||
from const import logPath, applicationPath
|
||||
|
||||
CUR_PATH = str(pathlib.Path(__file__).parent.resolve())
|
||||
LOG_FILE = os.path.join(CUR_PATH, 'script.log')
|
||||
@@ -26,9 +26,6 @@ fullPholusPath = os.path.join(CUR_PATH, 'pholus/pholus3.py')
|
||||
pluginName = 'PHOLUS'
|
||||
|
||||
def main():
|
||||
# sample
|
||||
# /home/pi/pialert/front/plugins/pholus_scan/script.py userSubnets=b'MTkyLjE2OC4xLjAvMjQgLS1pbnRlcmZhY2U9ZXRoMQ==' timeoutSec=10
|
||||
# sudo docker exec pialert /home/pi/pialert/front/plugins/pholus_scan/script.py userSubnets=b'MTkyLjE2OC4xLjAvMjQgLS1pbnRlcmZhY2U9ZXRoMQ==' timeoutSec=10
|
||||
|
||||
# the script expects a parameter in the format of userSubnets=subnet1,subnet2,...
|
||||
parser = argparse.ArgumentParser(description='Import devices from settings')
|
||||
|
||||
@@ -1,8 +0,0 @@
|
||||
## Descripción general
|
||||
|
||||
Un plugin que permite importar dispositivos desde la base de datos PiHole. Este es un complemento de importación que utiliza una base de datos SQLite como fuente.
|
||||
|
||||
|
||||
### Uso
|
||||
|
||||
- Debe especificar la configuración `PIHOLE_RUN_SCHD` y asignar el archivo PiHole DB a la ruta especificada en la configuración `PIHOLE_DB_PATH`.
|
||||
@@ -6,9 +6,10 @@ import base64
|
||||
from datetime import datetime
|
||||
|
||||
sys.path.append("/home/pi/pialert/front/plugins")
|
||||
sys.path.append('/home/pi/pialert/pialert')
|
||||
sys.path.append('/home/pi/pialert/netalertx')
|
||||
|
||||
from logger import mylog
|
||||
from const import confFileName
|
||||
|
||||
#-------------------------------------------------------------------------------
|
||||
def read_config_file():
|
||||
@@ -17,11 +18,11 @@ def read_config_file():
|
||||
config_dir[key]
|
||||
"""
|
||||
|
||||
filename = '/home/pi/pialert/config/pialert.conf'
|
||||
filename = '/home/pi/pialert/config/' + confFileName
|
||||
|
||||
|
||||
print('[plugin_helper] reading config file')
|
||||
# load the variables from pialert.conf
|
||||
# load the variables from .conf
|
||||
with open(filename, "r") as file:
|
||||
code = compile(file.read(), filename, "exec")
|
||||
|
||||
|
||||
@@ -1,48 +0,0 @@
|
||||
## Descripción general
|
||||
|
||||
Un plugin simple basado en script para configurar la contraseña.
|
||||
|
||||
### Uso
|
||||
|
||||
- Dirígete a **Configuración** > **Contraseña de UI** para ajustar los valores predeterminados.
|
||||
|
||||
### Notas
|
||||
|
||||
- El complemento se ejecuta `RUN` con en el tipo `before_config_save`, por lo que es posible actualizar el archivo `pialert.conf` antes de que los datos se carguen en la aplicación.
|
||||
- El comando ejecutado se almacena en la configuración `CMD`: `/home/pi/pialert/back/pialert-cli set_password {contraseña}`
|
||||
- El parámetro `{contraseña}` se reemplaza mediante el parámetro y la configuración a continuación:
|
||||
|
||||
```json
|
||||
...
|
||||
"params" : [
|
||||
{
|
||||
"name" : "password",
|
||||
"type" : "setting",
|
||||
"value" : "SETPWD_password"
|
||||
}
|
||||
],
|
||||
|
||||
...
|
||||
{
|
||||
"function": "password",
|
||||
"type": "password",
|
||||
"maxLength": 50,
|
||||
"default_value": "123456",
|
||||
"options": [],
|
||||
"localized": ["name", "description"],
|
||||
"name": [
|
||||
{
|
||||
"language_code": "en_us",
|
||||
"string": "Password"
|
||||
}
|
||||
],
|
||||
"description": [
|
||||
{
|
||||
"language_code": "en_us",
|
||||
"string": "The default password is <code>123456</code>. To change the password run <code>/home/pi/pialert/back/pialert-cli set_password {password}</code> in the container"
|
||||
}
|
||||
]
|
||||
}
|
||||
|
||||
|
||||
```
|
||||
@@ -1,39 +0,0 @@
|
||||
## Descripción general
|
||||
|
||||
Un plugin para importar dispositivos desde un enrutador o conmutador habilitado para SNMP. El uso de SNMP ofrece una manera eficiente de descubrir dispositivos IPv4 en una o más redes/subredes/vlan.
|
||||
|
||||
### Uso
|
||||
|
||||
Especifique las siguientes configuraciones en la sección Configuración de PiAlert:
|
||||
|
||||
- `SNMPDSC_routers`: una lista de comandos `snmpwalk` para ejecutar en direcciones IP de computadoras/conmutadores con SNMP activado. Por ejemplo:
|
||||
|
||||
- `snmpwalk -v 2c -c public -OXsq 192.168.1.1 .1.3.6.1.2.1.3.1.1.2`
|
||||
- `snmpwalk -v 2c -c public -Oxsq 192.168.1.1 .1.3.6.1.2.1.3.1.1.2` (nota: `x` minúscula)
|
||||
|
||||
|
||||
### Configurar Cisco IOS
|
||||
|
||||
Habilite el servicio SNMP de IOS y restrinja a la IP/subred seleccionada (interna).
|
||||
|
||||
````
|
||||
! Add standard ip access-list 10
|
||||
ip access-list standard 10
|
||||
permit 192.168.1.0 0.0.0.255
|
||||
permit host 192.168.2.10
|
||||
!
|
||||
! Enable IOS snmp server with Read Only community 'mysnmpcommunitysecret' name.
|
||||
! Restrict connections to access-list 10
|
||||
snmp-server community mysnmpcommunitysecret RO 10
|
||||
````
|
||||
|
||||
Confirmar SNMP habilitado
|
||||
````
|
||||
show snmp
|
||||
````
|
||||
|
||||
### Notas
|
||||
|
||||
- Sólo se admite IPv4.
|
||||
- El OID SNMP `.1.1.1.3.6.1.2.1.3.1.1.2` es específico para la tabla ARP IPv4 de dispositivos. Este OID se ha probado en Cisco ISR y otros dispositivos L3. El soporte puede variar entre otros proveedores/dispositivos.
|
||||
- Salida esperada (ingesta) en formato `iso.3.6.1.2.1.3.1.1.2.3.1.192.168.1.2 "6C 6C 6C 6C 6C 6C "`.
|
||||
@@ -11,12 +11,12 @@ import os
|
||||
import sys
|
||||
|
||||
sys.path.append("/home/pi/pialert/front/plugins")
|
||||
sys.path.append('/home/pi/pialert/pialert')
|
||||
sys.path.append('/home/pi/pialert/netalertx')
|
||||
|
||||
from plugin_helper import Plugin_Object, Plugin_Objects, decodeBase64, handleEmpty
|
||||
from logger import mylog
|
||||
from helper import timeNowTZ
|
||||
from const import logPath, pialertPath
|
||||
from const import logPath, applicationPath
|
||||
|
||||
CUR_PATH = str(pathlib.Path(__file__).parent.resolve())
|
||||
RESULT_FILE = os.path.join(CUR_PATH, 'last_result.log')
|
||||
|
||||
@@ -1,27 +0,0 @@
|
||||
## Übersicht
|
||||
|
||||
Ein Plugin zum Importieren von nicht erkennbaren Geräten aus einer Datei. Das Plugin findet Verwendung, wenn "dumme" Netzwerkkomponenten (z.B. Unmanaged Hubs/Switches) zur Netzwerkansicht hinzugefügt werden sollen. Möglicherweise gibt es weitere Anwendungsfälle, bitte informiert uns darüber.
|
||||
|
||||
### Verwendung
|
||||
|
||||
- Einstellungen aufrufen und Nicht erkennbare Geräte in der Liste der Plugins finden
|
||||
- Plugin aktivieren, indem der `RUN`-Parameter von `disabled` zu `once` oder `always_after_scan` geändert wird
|
||||
- Gerätenamen der Liste hinzufügen (Beispieleintrag zuerst entfernen)
|
||||
- SPEICHERN
|
||||
- Auf Abschluss des nächsten Scans warten
|
||||
|
||||
#### Beispiele
|
||||
|
||||
Einstellungen:
|
||||

|
||||
|
||||
Resultat:
|
||||

|
||||
|
||||
Erlaubt nicht erkennbare Geräte wie Hubs, Switches oder APs in der Netzwerkansicht:
|
||||

|
||||
|
||||
### Bekannte Einschränkungen
|
||||
|
||||
- Nicht erkennbare Geräte erscheinen immer als Offline. NetAlertX kann diese Geräte nicht erkennen (wie erwartet).
|
||||
- Alle IPs werden auf 0.0.0.0 gesetzt, daher kann es sein, dass das "Zufällige MAC"-Icon erscheint
|
||||
@@ -1,27 +0,0 @@
|
||||
## Descripción general
|
||||
|
||||
Un plugin que permite importar dispositivos no detectables desde la página de configuración.
|
||||
El caso de uso principal es agregar equipos de red tontos, como concentradores y conmutadores no administrados, a la vista de red.
|
||||
Puede haber otros casos de uso, hágamelo saber.
|
||||
|
||||
### Uso
|
||||
|
||||
- Vaya a configuración y busque Dispositivos no descubiertos en la lista de complementos.
|
||||
- Habilite el complemento cambiando el parámetro RUN de deshabilitado a "once" o "always_after_scan".
|
||||
- Añade el nombre de tu dispositivo a la lista. (elimine primero la entrada de muestra)
|
||||
- GUARDAR
|
||||
- Espere a que finalice el siguiente escaneo
|
||||
|
||||
#### Ejemplos:
|
||||
Ajustes:
|
||||

|
||||
|
||||
Resultado en dispositivos:
|
||||

|
||||
|
||||
Permitir que dispositivos no detectables como concentradores, conmutadores o AP se agreguen a la vista de red.
|
||||

|
||||
|
||||
### Limitaciones conocidas
|
||||
- Los dispositivos no detectables siempre se muestran sin conexión. Esto es de esperar, ya que NetAlertX no puede descubrirlos.
|
||||
- Todas las IP están configuradas en 0.0.0.0, por lo que es posible que aparezca el icono "MAC aleatoria".
|
||||
@@ -8,12 +8,12 @@ import sys
|
||||
import hashlib
|
||||
|
||||
sys.path.append("/home/pi/pialert/front/plugins")
|
||||
sys.path.append('/home/pi/pialert/pialert')
|
||||
sys.path.append('/home/pi/pialert/netalertx')
|
||||
|
||||
from plugin_helper import Plugin_Object, Plugin_Objects, decodeBase64
|
||||
from logger import mylog, append_line_to_file
|
||||
from helper import timeNowTZ
|
||||
from const import logPath, pialertPath
|
||||
from const import logPath, applicationPath
|
||||
|
||||
CUR_PATH = str(pathlib.Path(__file__).parent.resolve())
|
||||
LOG_FILE = os.path.join(CUR_PATH, 'script.log')
|
||||
|
||||
@@ -1,19 +0,0 @@
|
||||
## Descripción general
|
||||
|
||||
Un plugin que permite importar dispositivos desde un controlador UniFi.
|
||||
|
||||
### Uso
|
||||
|
||||
Especifique las siguientes configuraciones en la sección Configuración de PiAlert:
|
||||
|
||||
- `UNFIMP_username`: nombre de usuario utilizado para iniciar sesión en el controlador UNIFI.
|
||||
- `UNFIMP_password`: contraseña utilizada para iniciar sesión en el controlador UNIFI.
|
||||
- `UNFIMP_host`: URL del host o dirección IP donde está alojado el controlador UNIFI (excluyendo http://)
|
||||
- `UNFIMP_sites`: nombre de los sitios (generalmente 'predeterminado', verifique la URL en la interfaz de usuario de su controlador UniFi si no está seguro. La identificación del sitio se encuentra en la siguiente parte de la URL: `https://192.168.1.1:8443/manage /sitio/este-es-el-id-del-sitio/configuración/`).
|
||||
- `Protocolo_UNFIMP` - https:// o http://
|
||||
- `UNFIMP_port` - Generalmente 8443
|
||||
|
||||
### Notas
|
||||
|
||||
- Actualmente sólo se utiliza para importar dispositivos, no su estado, tipo o mapa de red.
|
||||
- Se recomienda crear un usuario de solo lectura en su controlador UniFi
|
||||
@@ -20,7 +20,7 @@ from pyunifi.controller import Controller
|
||||
|
||||
# Add your paths here
|
||||
sys.path.append("/home/pi/pialert/front/plugins")
|
||||
sys.path.append('/home/pi/pialert/pialert')
|
||||
sys.path.append('/home/pi/pialert/netalertx')
|
||||
|
||||
from plugin_helper import Plugin_Object, Plugin_Objects
|
||||
from logger import mylog
|
||||
|
||||
@@ -1,7 +0,0 @@
|
||||
## Übersicht
|
||||
|
||||
Ein Plugin zum Herunterladen einer MAC- und Hersteller-Datenbank für die Erkennung vom Hersteller eines Gerätes. Das Resultat des Plugins ist eine Liste von Herstellern, verknüpft zu Geräten, deren Hersteller bisher unbekannt war.
|
||||
|
||||
### Verwendung
|
||||
|
||||
- Einstellungen-Seite für Details ansehen.
|
||||
@@ -1,6 +1,4 @@
|
||||
#!/usr/bin/env python
|
||||
# test script by running:
|
||||
# /home/pi/pialert/front/plugins/db_cleanup/script.py pluginskeephistory=250 hourstokeepnewdevice=48 daystokeepevents=90
|
||||
|
||||
import os
|
||||
import pathlib
|
||||
@@ -14,12 +12,12 @@ from io import StringIO
|
||||
from datetime import datetime
|
||||
|
||||
sys.path.append("/home/pi/pialert/front/plugins")
|
||||
sys.path.append('/home/pi/pialert/pialert')
|
||||
sys.path.append('/home/pi/pialert/netalertx')
|
||||
|
||||
from plugin_helper import Plugin_Object, Plugin_Objects, decodeBase64, handleEmpty
|
||||
from logger import mylog, append_line_to_file
|
||||
from helper import timeNowTZ
|
||||
from const import logPath, pialertPath, fullDbPath
|
||||
from const import logPath, applicationPath, fullDbPath
|
||||
from device import query_MAC_vendor
|
||||
|
||||
|
||||
@@ -52,7 +50,7 @@ def update_vendor_database():
|
||||
|
||||
# Update vendors DB (iab oui)
|
||||
mylog('verbose', [' Updating vendors DB (iab & oui)'])
|
||||
update_args = ['sh', pialertPath + '/back/update_vendors.sh']
|
||||
update_args = ['sh', applicationPath + '/back/update_vendors.sh']
|
||||
|
||||
# Execute command
|
||||
try:
|
||||
@@ -67,7 +65,7 @@ def update_vendor_database():
|
||||
# resolve missing vendors
|
||||
def update_vendors (dbPath, plugin_objects):
|
||||
|
||||
# Connect to the PiAlert SQLite database
|
||||
# Connect to the App SQLite database
|
||||
conn = sqlite3.connect(dbPath)
|
||||
sql = conn.cursor()
|
||||
|
||||
|
||||
@@ -1,12 +0,0 @@
|
||||
## Descripción general
|
||||
|
||||
Un plugin de muestra simple que permite monitorear servicios web o URL. El código de estado corresponde a los [códigos de estado de respuesta HTTP](https://developer.mozilla.org/en-US/docs/Web/HTTP/Status).
|
||||
|
||||
### Uso
|
||||
|
||||
- El usuario puede especificar qué servicios (sitios web) monitorear a través de la configuración `WEBMON_urls_to_check`.
|
||||
|
||||
### Notas
|
||||
|
||||
- La configuración `(WEBMON_)SQL_internet_ip` no se utiliza ni se especifica únicamente con fines de demostración.
|
||||
- Los parámetros `macs` e `internet_ip` en el archivo `config.json` no se utilizan ni se especifican únicamente con fines de demostración.
|
||||
@@ -10,7 +10,7 @@ import sys
|
||||
import os
|
||||
from requests.packages.urllib3.exceptions import InsecureRequestWarning
|
||||
|
||||
sys.path.extend(["/home/pi/pialert/front/plugins", "/home/pi/pialert/pialert"])
|
||||
sys.path.extend(["/home/pi/pialert/front/plugins", "/home/pi/pialert/netalertx"])
|
||||
|
||||
from plugin_helper import Plugin_Objects
|
||||
from datetime import datetime
|
||||
|
||||
Reference in New Issue
Block a user