aboutsummaryrefslogtreecommitdiffstats
path: root/mod
diff options
context:
space:
mode:
Diffstat (limited to 'mod')
-rw-r--r--mod/bridge-port-to.rsc33
-rw-r--r--mod/bridge-port-vlan.rsc36
-rw-r--r--mod/inspectvar.rsc19
-rw-r--r--mod/ipcalc.rsc19
-rw-r--r--mod/notification-email.rsc130
-rw-r--r--mod/notification-gotify.rsc139
-rw-r--r--mod/notification-matrix.rsc208
-rw-r--r--mod/notification-ntfy.rsc161
-rw-r--r--mod/notification-telegram.rsc168
-rw-r--r--mod/scriptrunonce.rsc53
-rw-r--r--mod/ssh-keys-import.rsc91
11 files changed, 802 insertions, 255 deletions
diff --git a/mod/bridge-port-to.rsc b/mod/bridge-port-to.rsc
index 86689c9..39a036e 100644
--- a/mod/bridge-port-to.rsc
+++ b/mod/bridge-port-to.rsc
@@ -1,18 +1,20 @@
#!rsc by RouterOS
# RouterOS script: mod/bridge-port-to
-# Copyright (c) 2013-2023 Christian Hesse <mail@eworm.de>
-# https://git.eworm.de/cgit/routeros-scripts/about/COPYING.md
+# Copyright (c) 2013-2025 Christian Hesse <mail@eworm.de>
+# https://rsc.eworm.de/COPYING.md
+#
+# requires RouterOS, version=7.15
#
# reset bridge ports to default bridge
-# https://git.eworm.de/cgit/routeros-scripts/about/doc/mod/bridge-port-to.md
+# https://rsc.eworm.de/doc/mod/bridge-port-to.md
:global BridgePortTo;
-:set BridgePortTo do={
+:set BridgePortTo do={ :do {
:local BridgePortTo [ :tostr $1 ];
:global IfThenElse;
- :global LogPrintExit2;
+ :global LogPrint;
:global ParseKeyValueStore;
:local InterfaceReEnable ({});
@@ -24,21 +26,22 @@
:if ($BridgeDefault = "dhcp-client") do={
:if ([ :len $DHCPClient ] != 1) do={
- $LogPrintExit2 warning $0 ([ $IfThenElse ([ :len $DHCPClient ] = 0) "Missing" "Duplicate" ] . \
- " dhcp client configuration for interface " . $BridgePortVal->"interface" . "!") true;
+ $LogPrint warning $0 ([ $IfThenElse ([ :len $DHCPClient ] = 0) "Missing" "Duplicate" ] . \
+ " dhcp client configuration for interface " . $BridgePortVal->"interface" . "!");
+ :return false;
}
:local DHCPClientDisabled [ /ip/dhcp-client/get $DHCPClient disabled ];
:if ($BridgePortVal->"disabled" = false || $DHCPClientDisabled = true) do={
- $LogPrintExit2 info $0 ("Disabling bridge port for interface " . $BridgePortVal->"interface" . ", enabling dhcp client.") false;
+ $LogPrint info $0 ("Disabling bridge port for interface " . $BridgePortVal->"interface" . ", enabling dhcp client.");
/interface/bridge/port/disable $BridgePort;
:delay 200ms;
/ip/dhcp-client/enable $DHCPClient;
}
} else={
:if ($BridgePortVal->"disabled" = true || $BridgeDefault != $BridgePortVal->"bridge") do={
- $LogPrintExit2 info $0 ("Enabling bridge port for interface " . $BridgePortVal->"interface" . ", changing to " . $BridgePortTo . \
- " bridge " . $BridgeDefault . ", disabling dhcp client.") false;
+ $LogPrint info $0 ("Enabling bridge port for interface " . $BridgePortVal->"interface" . ", changing to " . $BridgePortTo . \
+ " bridge " . $BridgeDefault . ", disabling dhcp client.");
:if ([ :len $DHCPClient ] = 1) do={
/ip/dhcp-client/disable $DHCPClient;
:delay 200ms;
@@ -50,8 +53,8 @@
}
/interface/bridge/port/set disabled=no bridge=$BridgeDefault $BridgePort;
} else={
- $LogPrintExit2 debug $0 ("Interface " . $BridgePortVal->"interface" . " already connected to " . $BridgePortTo . \
- " bridge " . $BridgeDefault . ".") false;
+ $LogPrint debug $0 ("Interface " . $BridgePortVal->"interface" . " already connected to " . $BridgePortTo . \
+ " bridge " . $BridgeDefault . ".");
}
}
}
@@ -59,7 +62,9 @@
}
:if ([ :len $InterfaceReEnable ] > 0) do={
:delay 5s;
- $LogPrintExit2 info $0 ("Re-enabling interfaces...") false;
+ $LogPrint info $0 ("Re-enabling interfaces...");
/interface/ethernet/enable $InterfaceReEnable;
}
-}
+} on-error={
+ :global ExitError; $ExitError false $0;
+} }
diff --git a/mod/bridge-port-vlan.rsc b/mod/bridge-port-vlan.rsc
index 792a6c4..0eeb9b5 100644
--- a/mod/bridge-port-vlan.rsc
+++ b/mod/bridge-port-vlan.rsc
@@ -1,18 +1,20 @@
#!rsc by RouterOS
# RouterOS script: mod/bridge-port-vlan
-# Copyright (c) 2013-2023 Christian Hesse <mail@eworm.de>
-# https://git.eworm.de/cgit/routeros-scripts/about/COPYING.md
+# Copyright (c) 2013-2025 Christian Hesse <mail@eworm.de>
+# https://rsc.eworm.de/COPYING.md
+#
+# requires RouterOS, version=7.15
#
# manage VLANs on bridge ports
-# https://git.eworm.de/cgit/routeros-scripts/about/doc/mod/bridge-port-vlan.md
+# https://rsc.eworm.de/doc/mod/bridge-port-vlan.md
:global BridgePortVlan;
-:global BridgePortVlan do={
+:global BridgePortVlan do={ :do {
:local ConfigTo [ :tostr $1 ];
:global IfThenElse;
- :global LogPrintExit2;
+ :global LogPrint;
:global ParseKeyValueStore;
:local InterfaceReEnable ({});
@@ -24,13 +26,14 @@
:if ($Vlan = "dhcp-client") do={
:if ([ :len $DHCPClient ] != 1) do={
- $LogPrintExit2 warning $0 ([ $IfThenElse ([ :len $DHCPClient ] = 0) "Missing" "Duplicate" ] . \
- " dhcp client configuration for interface " . $BridgePortVal->"interface" . "!") true;
+ $LogPrint warning $0 ([ $IfThenElse ([ :len $DHCPClient ] = 0) "Missing" "Duplicate" ] . \
+ " dhcp client configuration for interface " . $BridgePortVal->"interface" . "!");
+ :return false;
}
:local DHCPClientDisabled [ /ip/dhcp-client/get $DHCPClient disabled ];
:if ($BridgePortVal->"disabled" = false || $DHCPClientDisabled = true) do={
- $LogPrintExit2 info $0 ("Disabling bridge port for interface " . $BridgePortVal->"interface" . ", enabling dhcp client.") false;
+ $LogPrint info $0 ("Disabling bridge port for interface " . $BridgePortVal->"interface" . ", enabling dhcp client.");
/interface/bridge/port/disable $BridgePort;
:delay 200ms;
/ip/dhcp-client/enable $DHCPClient;
@@ -41,12 +44,13 @@
:do {
:set $Vlan ([ /interface/bridge/vlan/get [ find where comment=$Vlan ] vlan-ids ]->0);
} on-error={
- $LogPrintExit2 warning $0 ("Could not find VLAN '" . $Vlan . "' for interface " . $BridgePortVal->"interface" . "!") true;
+ $LogPrint warning $0 ("Could not find VLAN '" . $Vlan . "' for interface " . $BridgePortVal->"interface" . "!");
+ :return false;
}
}
:if ($BridgePortVal->"disabled" = true || $Vlan != $BridgePortVal->"pvid") do={
- $LogPrintExit2 info $0 ("Enabling bridge port for interface " . $BridgePortVal->"interface" . ", changing to " . $ConfigTo . \
- " vlan " . $Vlan . [ $IfThenElse ($Vlan != $VlanName) (" (" . $VlanName . ")") ] . ", disabling dhcp client.") false;
+ $LogPrint info $0 ("Enabling bridge port for interface " . $BridgePortVal->"interface" . ", changing to " . $ConfigTo . \
+ " vlan " . $Vlan . [ $IfThenElse ($Vlan != $VlanName) (" (" . $VlanName . ")") ] . ", disabling dhcp client.");
:if ([ :len $DHCPClient ] = 1) do={
/ip/dhcp-client/disable $DHCPClient;
:delay 200ms;
@@ -58,8 +62,8 @@
}
/interface/bridge/port/set disabled=no pvid=$Vlan $BridgePort;
} else={
- $LogPrintExit2 debug $0 ("Interface " . $BridgePortVal->"interface" . " already connected to " . $ConfigTo . \
- " vlan " . $Vlan . ".") false;
+ $LogPrint debug $0 ("Interface " . $BridgePortVal->"interface" . " already connected to " . $ConfigTo . \
+ " vlan " . $Vlan . ".");
}
}
}
@@ -67,7 +71,9 @@
}
:if ([ :len $InterfaceReEnable ] > 0) do={
:delay 5s;
- $LogPrintExit2 info $0 ("Re-enabling interfaces...") false;
+ $LogPrint info $0 ("Re-enabling interfaces...");
/interface/ethernet/enable $InterfaceReEnable;
}
-}
+} on-error={
+ :global ExitError; $ExitError false $0;
+} }
diff --git a/mod/inspectvar.rsc b/mod/inspectvar.rsc
index e06d799..c861557 100644
--- a/mod/inspectvar.rsc
+++ b/mod/inspectvar.rsc
@@ -1,21 +1,24 @@
#!rsc by RouterOS
# RouterOS script: mod/inspectvar
-# Copyright (c) 2020-2023 Christian Hesse <mail@eworm.de>
-# https://git.eworm.de/cgit/routeros-scripts/about/COPYING.md
+# Copyright (c) 2020-2025 Christian Hesse <mail@eworm.de>
+# https://rsc.eworm.de/COPYING.md
+#
+# requires RouterOS, version=7.15
#
# inspect variables
-# https://git.eworm.de/cgit/routeros-scripts/about/doc/mod/inspectvar.md
+# https://rsc.eworm.de/doc/mod/inspectvar.md
:global InspectVar;
:global InspectVarReturn;
# inspect variable and print on terminal
-:set InspectVar do={
+:set InspectVar do={ :do {
:global InspectVarReturn;
- :global PrettyPrint;
- $PrettyPrint [ $InspectVarReturn $1 ];
-}
+ :put [ :tocrlf [ $InspectVarReturn $1 ] ];
+} on-error={
+ :global ExitError; $ExitError false $0;
+} }
# inspect variable and return formatted string
:set InspectVarReturn do={
@@ -39,7 +42,7 @@
:local TypeOf [ :typeof $Input ];
:local Return [ $IndentReturn "type" $TypeOf $Level ];
-
+
:if ($TypeOf = "array") do={
:foreach Key,Value in=$Input do={
:set $Return ($Return . "\n" . \
diff --git a/mod/ipcalc.rsc b/mod/ipcalc.rsc
index eaa5c97..477cf4a 100644
--- a/mod/ipcalc.rsc
+++ b/mod/ipcalc.rsc
@@ -1,32 +1,35 @@
#!rsc by RouterOS
# RouterOS script: mod/ipcalc
-# Copyright (c) 2020-2023 Christian Hesse <mail@eworm.de>
-# https://git.eworm.de/cgit/routeros-scripts/about/COPYING.md
+# Copyright (c) 2020-2025 Christian Hesse <mail@eworm.de>
+# https://rsc.eworm.de/COPYING.md
+#
+# requires RouterOS, version=7.15
#
# ip address calculation
-# https://git.eworm.de/cgit/routeros-scripts/about/doc/mod/ipcalc.md
+# https://rsc.eworm.de/doc/mod/ipcalc.md
:global IPCalc;
:global IPCalcReturn;
# print netmask, network, min host, max host and broadcast
-:set IPCalc do={
+:set IPCalc do={ :do {
:local Input [ :tostr $1 ];
:global FormatLine;
:global IPCalcReturn;
- :global PrettyPrint;
:local Values [ $IPCalcReturn $1 ];
- $PrettyPrint ( \
+ :put [ :tocrlf ( \
[ $FormatLine "Address" ($Values->"address") ] . "\n" . \
[ $FormatLine "Netmask" ($Values->"netmask") ] . "\n" . \
[ $FormatLine "Network" ($Values->"network") ] . "\n" . \
[ $FormatLine "HostMin" ($Values->"hostmin") ] . "\n" . \
[ $FormatLine "HostMax" ($Values->"hostmax") ] . "\n" . \
- [ $FormatLine "Broadcast" ($Values->"broadcast") ]);
-}
+ [ $FormatLine "Broadcast" ($Values->"broadcast") ]) ];
+} on-error={
+ :global ExitError; $ExitError false $0;
+} }
# calculate and return netmask, network, min host, max host and broadcast
:set IPCalcReturn do={
diff --git a/mod/notification-email.rsc b/mod/notification-email.rsc
index e266201..7b89d98 100644
--- a/mod/notification-email.rsc
+++ b/mod/notification-email.rsc
@@ -1,11 +1,15 @@
#!rsc by RouterOS
# RouterOS script: mod/notification-email
-# Copyright (c) 2013-2023 Christian Hesse <mail@eworm.de>
-# https://git.eworm.de/cgit/routeros-scripts/about/COPYING.md
+# Copyright (c) 2013-2025 Christian Hesse <mail@eworm.de>
+# https://rsc.eworm.de/COPYING.md
+#
+# requires RouterOS, version=7.15
+# requires device-mode, email, scheduler
#
# send notifications via e-mail
-# https://git.eworm.de/cgit/routeros-scripts/about/doc/mod/notification-email.md
+# https://rsc.eworm.de/doc/mod/notification-email.md
+:global EMailGenerateFrom;
:global FlushEmailQueue;
:global LogForwardFilterLogForwarding;
:global NotificationEMailSubject;
@@ -15,43 +19,73 @@
:global SendEMail;
:global SendEMail2;
+# generate from-property with display name
+:set EMailGenerateFrom do={
+ :global Identity;
+
+ :global CleanName;
+
+ :local From [ /tool/e-mail/get from ];
+
+ :if ($From ~ "<.*>\$") do={
+ :return $From;
+ }
+
+ :return ([ $CleanName $Identity ] . " via routeros-scripts <" . $From . ">");
+}
+
# flush e-mail queue
-:set FlushEmailQueue do={
+:set FlushEmailQueue do={ :do {
:global EmailQueue;
:global EitherOr;
+ :global EMailGenerateFrom;
:global IsDNSResolving;
:global IsTimeSync;
- :global LogPrintExit2;
+ :global LogPrint;
:local AllDone true;
:local QueueLen [ :len $EmailQueue ];
- :local Scheduler [ /system/scheduler/find where name=$0 ];
-
- :if ([ :len $Scheduler ] > 0 && [ /system/scheduler/get $Scheduler interval ] < 1m) do={
+ :local Scheduler [ /system/scheduler/find where name="_FlushEmailQueue" ];
+
+ :if ([ :len $Scheduler ] > 0 && $QueueLen = 0) do={
+ $LogPrint warning $0 ("Flushing E-Mail messages from scheduler, but queue is empty.");
+ /system/scheduler/remove $Scheduler;
+ :return false;
+ }
+
+ :if ($QueueLen = 0) do={
+ :return true;
+ }
+
+ :if ([ :len $Scheduler ] < 0) do={
+ /system/scheduler/add name="_FlushEmailQueue" interval=1m start-time=startup \
+ comment="Doing initial checks..." on-event=(":global FlushEmailQueue; \$FlushEmailQueue;");
+ :set Scheduler [ /system/scheduler/find where name="_FlushEmailQueue" ];
+ }
+
+ :local SchedVal [ /system/scheduler/get $Scheduler ];
+ :if (($SchedVal->"interval") < 1m) do={
/system/scheduler/set interval=1m comment="Doing initial checks..." $Scheduler;
}
:if ([ /tool/e-mail/get last-status ] = "in-progress") do={
- $LogPrintExit2 debug $0 ("Sending mail is currently in progress, not flushing.") false;
+ $LogPrint debug $0 ("Sending mail is currently in progress, not flushing.");
:return false;
}
:if ([ $IsTimeSync ] = false) do={
- $LogPrintExit2 debug $0 ("Time is not synced, not flushing.") false;
+ $LogPrint debug $0 ("Time is not synced, not flushing.");
:return false;
}
- :if ([ :typeof [ :toip [ /tool/e-mail/get address ] ] ] != "ip" && [ $IsDNSResolving ] = false) do={
- $LogPrintExit2 debug $0 ("Server address is a DNS name and resolving fails, not flushing.") false;
+ :local EMailSettings [ /tool/e-mail/get ];
+ :if ([ :typeof [ :toip ($EMailSettings->"server") ] ] != "ip" && [ $IsDNSResolving ] = false) do={
+ $LogPrint debug $0 ("Server address is a DNS name and resolving fails, not flushing.");
:return false;
}
- :if ([ :len $Scheduler ] > 0 && $QueueLen = 0) do={
- $LogPrintExit2 warning $0 ("Flushing E-Mail messages from scheduler, but queue is empty.") false;
- }
-
- /system/scheduler/set interval=([ $EitherOr $QueueLen 1 ] . "m") comment="Sending..." $Scheduler;
+ /system/scheduler/set interval=($QueueLen . "m") comment="Sending..." $Scheduler;
:foreach Id,Message in=$EmailQueue do={
:if ([ :typeof $Message ] = "array" ) do={
@@ -61,11 +95,11 @@
:if ([ :len [ /file/find where name=$File ] ] = 1) do={
:set Attach ($Attach, $File);
} else={
- $LogPrintExit2 warning $0 ("File '" . $File . "' does not exist, can not attach.") false;
+ $LogPrint warning $0 ("File '" . $File . "' does not exist, can not attach.");
}
}
- /tool/e-mail/send to=($Message->"to") cc=($Message->"cc") subject=($Message->"subject") \
- body=($Message->"body") file=$Attach;
+ /tool/e-mail/send from=[ $EMailGenerateFrom ] to=($Message->"to") cc=($Message->"cc") \
+ subject=($Message->"subject") body=($Message->"body") file=$Attach;
:local Wait true;
:do {
:delay 1s;
@@ -90,10 +124,20 @@
:if ($AllDone = true && $QueueLen = [ :len $EmailQueue ]) do={
/system/scheduler/remove $Scheduler;
:set EmailQueue;
- } else={
- /system/scheduler/set interval=1m comment="Waiting for retry..." $Scheduler;
+ :return true;
}
-}
+
+ :if ([ :len [ /system/scheduler/find where name="_FlushEmailQueue" ] ] = 0 && \
+ [ :typeof $EmailQueue ] = "nothing") do={
+ $LogPrint info $0 ("Queue was purged? Exiting.");
+ :return false;
+ }
+
+ /system/scheduler/set interval=(($SchedVal->"run-count") . "m") \
+ comment="Waiting for retry..." $Scheduler;
+} on-error={
+ :global ExitError; $ExitError false $0;
+} }
# generate filter for log-forward
:set LogForwardFilterLogForwarding do={
@@ -130,20 +174,21 @@
:global EitherOr;
:global IfThenElse;
+ :global NotificationEMailSignature;
:global NotificationEMailSubject;
:local To [ $EitherOr ($EmailGeneralToOverride->($Notification->"origin")) $EmailGeneralTo ];
:local Cc [ $EitherOr ($EmailGeneralCcOverride->($Notification->"origin")) $EmailGeneralCc ];
:local EMailSettings [ /tool/e-mail/get ];
- :if ([ :len $To ] = 0 || ($EMailSettings->"address") = "0.0.0.0" || ($EMailSettings->"from") = "<>") do={
+ :if ([ :len $To ] = 0 || ($EMailSettings->"server") = "0.0.0.0" || ($EMailSettings->"from") = "<>") do={
:return false;
}
:if ([ :typeof $EmailQueue ] = "nothing") do={
:set EmailQueue ({});
}
- :local Signature [ /system/note/get note ];
+ :local Signature [ $EitherOr [ $NotificationEMailSignature ] [ /system/note/get note ] ];
:set ($EmailQueue->[ :len $EmailQueue ]) {
to=$To; cc=$Cc;
subject=[ $NotificationEMailSubject ($Notification->"subject") ];
@@ -151,8 +196,8 @@
[ $IfThenElse ([ :len ($Notification->"link") ] > 0) ("\n\n" . ($Notification->"link")) "" ] . \
[ $IfThenElse ([ :len $Signature ] > 0) ("\n-- \n" . $Signature) "" ]); \
attach=($Notification->"attach"); remove-attach=($Notification->"remove-attach") };
- :if ([ :len [ /system/scheduler/find where name="\$FlushEmailQueue" ] ] = 0) do={
- /system/scheduler/add name="\$FlushEmailQueue" interval=1s start-time=startup \
+ :if ([ :len [ /system/scheduler/find where name="_FlushEmailQueue" ] ] = 0) do={
+ /system/scheduler/add name="_FlushEmailQueue" interval=1s start-time=startup \
comment="Queuing new mail..." on-event=(":global FlushEmailQueue; \$FlushEmailQueue;");
}
}
@@ -161,7 +206,7 @@
:set PurgeEMailQueue do={
:global EmailQueue;
- /system/scheduler/remove [ find where name="\$FlushEmailQueue" ];
+ /system/scheduler/remove [ find where name="_FlushEmailQueue" ];
:set EmailQueue;
}
@@ -169,27 +214,28 @@
:global QuotedPrintable do={
:local Input [ :tostr $1 ];
+ :global CharacterMultiply;
+
:if ([ :len $Input ] = 0) do={
:return $Input;
}
:local Return "";
- :local Chars ("\80\81\82\83\84\85\86\87\88\89\8A\8B\8C\8D\8E\8F\90\91\92\93\94\95\96\97" . \
- "\98\99\9A\9B\9C\9D\9E\9F\A0\A1\A2\A3\A4\A5\A6\A7\A8\A9\AA\AB\AC\AD\AE\AF\B0\B1\B2\B3" . \
- "\B4\B5\B6\B7\B8\B9\BA\BB\BC\BD\BE\BF\C0\C1\C2\C3\C4\C5\C6\C7\C8\C9\CA\CB\CC\CD\CE\CF" . \
- "\D0\D1\D2\D3\D4\D5\D6\D7\D8\D9\DA\DB\DC\DD\DE\DF\E0\E1\E2\E3\E4\E5\E6\E7\E8\E9\EA\EB" . \
- "\EC\ED\EE\EF\F0\F1\F2\F3\F4\F5\F6\F7\F8\F9\FA\FB\FC\FD\FE\FF");
- :local Hex { "0"; "1"; "2"; "3"; "4"; "5"; "6"; "7"; "8"; "9"; "A"; "B"; "C"; "D"; "E"; "F" };
+ :local Chars ( \
+ "\00\01\02\03\04\05\06\07\08\09\0A\0B\0C\0D\0E\0F\10\11\12\13\14\15\16\17\18\19\1A\1B\1C\1D\1E\1F" . \
+ [ $CharacterMultiply ("\00") 29 ] . "=\00?" . [ $CharacterMultiply ("\00") 63 ] . "\7F" . \
+ "\80\81\82\83\84\85\86\87\88\89\8A\8B\8C\8D\8E\8F\90\91\92\93\94\95\96\97\98\99\9A\9B\9C\9D\9E\9F" . \
+ "\A0\A1\A2\A3\A4\A5\A6\A7\A8\A9\AA\AB\AC\AD\AE\AF\B0\B1\B2\B3\B4\B5\B6\B7\B8\B9\BA\BB\BC\BD\BE\BF" . \
+ "\C0\C1\C2\C3\C4\C5\C6\C7\C8\C9\CA\CB\CC\CD\CE\CF\D0\D1\D2\D3\D4\D5\D6\D7\D8\D9\DA\DB\DC\DD\DE\DF" . \
+ "\E0\E1\E2\E3\E4\E5\E6\E7\E8\E9\EA\EB\EC\ED\EE\EF\F0\F1\F2\F3\F4\F5\F6\F7\F8\F9\FA\FB\FC\FD\FE\FF");
+ :local Hex "0123456789ABCDEF";
:for I from=0 to=([ :len $Input ] - 1) do={
:local Char [ :pick $Input $I ];
:local Replace [ :find $Chars $Char ];
- :if ($Char = "=") do={
- :set Char "=3D";
- }
:if ([ :typeof $Replace ] = "num") do={
- :set Char ("=" . ($Hex->($Replace / 16 + 8)) . ($Hex->($Replace % 16)));
+ :set Char ("=" . [ :pick $Hex ($Replace / 16)] . [ :pick $Hex ($Replace % 16) ]);
}
:set Return ($Return . $Char);
}
@@ -202,11 +248,13 @@
}
# send notification via e-mail - expects at least two string arguments
-:set SendEMail do={
+:set SendEMail do={ :do {
:global SendEMail2;
- $SendEMail2 ({ subject=$1; message=$2; link=$3 });
-}
+ $SendEMail2 ({ origin=$0; subject=$1; message=$2; link=$3 });
+} on-error={
+ :global ExitError; $ExitError false $0;
+} }
# send notification via e-mail - expects one array argument
:set SendEMail2 do={
diff --git a/mod/notification-gotify.rsc b/mod/notification-gotify.rsc
new file mode 100644
index 0000000..7070918
--- /dev/null
+++ b/mod/notification-gotify.rsc
@@ -0,0 +1,139 @@
+#!rsc by RouterOS
+# RouterOS script: mod/notification-gotify
+# Copyright (c) 2013-2025 Christian Hesse <mail@eworm.de>
+# Leonardo David Monteiro <leo@cub3.xyz>
+# https://rsc.eworm.de/COPYING.md
+#
+# requires RouterOS, version=7.15
+# requires device-mode, fetch, scheduler
+#
+# send notifications via Gotify (gotify.net)
+# https://rsc.eworm.de/doc/mod/notification-gotify.md
+
+:global FlushGotifyQueue;
+:global NotificationFunctions;
+:global PurgeGotifyQueue;
+:global SendGotify;
+:global SendGotify2;
+
+# flush Gotify queue
+:set FlushGotifyQueue do={ :do {
+ :global GotifyQueue;
+
+ :global IsFullyConnected;
+ :global LogPrint;
+
+ :if ([ $IsFullyConnected ] = false) do={
+ $LogPrint debug $0 ("System is not fully connected, not flushing.");
+ :return false;
+ }
+
+ :local AllDone true;
+ :local QueueLen [ :len $GotifyQueue ];
+
+ :if ([ :len [ /system/scheduler/find where name="_FlushGotifyQueue" ] ] > 0 && $QueueLen = 0) do={
+ $LogPrint warning $0 ("Flushing Gotify messages from scheduler, but queue is empty.");
+ }
+
+ :foreach Id,Message in=$GotifyQueue do={
+ :if ([ :typeof $Message ] = "array" ) do={
+ :do {
+ /tool/fetch check-certificate=yes-without-crl output=none http-method=post \
+ http-header-field=($Message->"headers") http-data=[ :serialize to=json ($Message->"message") ] \
+ ($Message->"url") as-value;
+ :set ($GotifyQueue->$Id);
+ } on-error={
+ $LogPrint debug $0 ("Sending queued Gotify message failed.");
+ :set AllDone false;
+ }
+ }
+ }
+
+ :if ($AllDone = true && $QueueLen = [ :len $GotifyQueue ]) do={
+ /system/scheduler/remove [ find where name="_FlushGotifyQueue" ];
+ :set GotifyQueue;
+ }
+} on-error={
+ :global ExitError; $ExitError false $0;
+} }
+
+# send notification via Gotify - expects one array argument
+:set ($NotificationFunctions->"gotify") do={
+ :local Notification $1;
+
+ :global Identity;
+ :global IdentityExtra;
+ :global GotifyQueue;
+ :global GotifyServer;
+ :global GotifyServerOverride;
+ :global GotifyToken;
+ :global GotifyTokenOverride;
+
+ :global EitherOr;
+ :global FetchUserAgentStr;
+ :global IfThenElse;
+ :global LogPrint;
+ :global SymbolForNotification;
+
+ :local Server [ $EitherOr ($GotifyServerOverride->($Notification->"origin")) $GotifyServer ];
+ :local Token [ $EitherOr ($GotifyTokenOverride->($Notification->"origin")) $GotifyToken ];
+
+ :if ([ :len $Token ] = 0) do={
+ :return false;
+ }
+
+ :local Url ("https://" . $Server . "/message");
+ :local Headers ({ [ $FetchUserAgentStr ($Notification->"origin") ]; \
+ ("X-Gotify-Key: " . $Token); "Content-Type: application/json" });
+ :local Message ({
+ "title"=("[" . $IdentityExtra . $Identity . "] " . ($Notification->"subject")); \
+ "message"=(($Notification->"message") . "\n" . [ $IfThenElse ([ :len ($Notification->"link") ] > 0) \
+ ("\n" . [ $SymbolForNotification "link" ] . ($Notification->"link")) ]); \
+ "priority"=[ :tonum [ $IfThenElse ($Notification->"silent") 2 5 ] ] });
+
+ :do {
+ /tool/fetch check-certificate=yes-without-crl output=none http-method=post \
+ http-header-field=$Headers http-data=[ :serialize to=json $Message ] $Url as-value;
+ } on-error={
+ $LogPrint info $0 ("Failed sending Gotify notification! Queuing...");
+
+ :if ([ :typeof $GotifyQueue ] = "nothing") do={
+ :set GotifyQueue ({});
+ }
+ :set ($Message->"message") (($Notification->"message") . "\n" . \
+ [ $SymbolForNotification "alarm-clock" ] . "This message was queued since " . \
+ [ /system/clock/get date ] . " " . [ /system/clock/get time ] . " and may be obsolete.");
+ :set ($GotifyQueue->[ :len $GotifyQueue ]) \
+ { url=$Url; headers=$Headers; message=$Message };
+ :if ([ :len [ /system/scheduler/find where name="_FlushGotifyQueue" ] ] = 0) do={
+ /system/scheduler/add name="_FlushGotifyQueue" interval=1m start-time=startup \
+ on-event=(":global FlushGotifyQueue; \$FlushGotifyQueue;");
+ }
+ }
+}
+
+# purge the Gotify queue
+:set PurgeGotifyQueue do={
+ :global GotifyQueue;
+
+ /system/scheduler/remove [ find where name="_FlushGotifyQueue" ];
+ :set GotifyQueue;
+}
+
+# send notification via Gotify - expects at least two string arguments
+:set SendGotify do={ :do {
+ :global SendGotify2;
+
+ $SendGotify2 ({ origin=$0; subject=$1; message=$2; link=$3; silent=$4 });
+} on-error={
+ :global ExitError; $ExitError false $0;
+} }
+
+# send notification via Gotify - expects one array argument
+:set SendGotify2 do={
+ :local Notification $1;
+
+ :global NotificationFunctions;
+
+ ($NotificationFunctions->"gotify") ("\$NotificationFunctions->\"gotify\"") $Notification;
+}
diff --git a/mod/notification-matrix.rsc b/mod/notification-matrix.rsc
index 03cfb13..e989ee0 100644
--- a/mod/notification-matrix.rsc
+++ b/mod/notification-matrix.rsc
@@ -1,59 +1,66 @@
#!rsc by RouterOS
# RouterOS script: mod/notification-matrix
-# Copyright (c) 2013-2023 Michael Gisbers <michael@gisbers.de>
+# Copyright (c) 2013-2025 Michael Gisbers <michael@gisbers.de>
# Christian Hesse <mail@eworm.de>
-# https://git.eworm.de/cgit/routeros-scripts/about/COPYING.md
+# https://rsc.eworm.de/COPYING.md
+#
+# requires RouterOS, version=7.15
+# requires device-mode, fetch, scheduler
#
# send notifications via Matrix
-# https://git.eworm.de/cgit/routeros-scripts/about/doc/mod/notification-matrix.md
+# https://rsc.eworm.de/doc/mod/notification-matrix.md
:global FlushMatrixQueue;
:global NotificationFunctions;
:global PurgeMatrixQueue;
:global SendMatrix;
:global SendMatrix2;
+:global SetupMatrixAuthenticate;
+:global SetupMatrixJoinRoom;
# flush Matrix queue
-:set FlushMatrixQueue do={
+:set FlushMatrixQueue do={ :do {
:global MatrixQueue;
:global IsFullyConnected;
- :global LogPrintExit2;
+ :global LogPrint;
:if ([ $IsFullyConnected ] = false) do={
- $LogPrintExit2 debug $0 ("System is not fully connected, not flushing.") false;
+ $LogPrint debug $0 ("System is not fully connected, not flushing.");
:return false;
}
:local AllDone true;
:local QueueLen [ :len $MatrixQueue ];
- :if ([ :len [ /system/scheduler/find where name=$0 ] ] > 0 && $QueueLen = 0) do={
- $LogPrintExit2 warning $0 ("Flushing Matrix messages from scheduler, but queue is empty.") false;
+ :if ([ :len [ /system/scheduler/find where name="_FlushMatrixQueue" ] ] > 0 && $QueueLen = 0) do={
+ $LogPrint warning $0 ("Flushing Matrix messages from scheduler, but queue is empty.");
}
:foreach Id,Message in=$MatrixQueue do={
:if ([ :typeof $Message ] = "array" ) do={
:do {
- /tool/fetch check-certificate=yes-without-crl output=none http-method=post \
- ("https://" . $Message->"homeserver" . "/_matrix/client/r0/rooms/" . $Message->"room" . \
- "/send/m.room.message?access_token=" . $Message->"accesstoken") \
- http-data=("{ \"msgtype\": \"m.text\", \"body\": \"" . $Message->"plain" . "\"," . \
- "\"format\": \"org.matrix.custom.html\", \"formatted_body\": \"" . \
- $Message->"formatted" . "\" }") as-value;
+ /tool/fetch check-certificate=yes-without-crl output=none \
+ http-header-field=($Message->"headers") http-method=post \
+ http-data=[ :serialize to=json { "msgtype"="m.text"; "body"=($Message->"plain");
+ "format"="org.matrix.custom.html"; "formatted_body"=($Message->"formatted") } ] \
+ ("https://" . $Message->"homeserver" . "/_matrix/client/r0/rooms/" . $Message->"room" . \
+ "/send/m.room.message?access_token=" . $Message->"accesstoken") as-value;
:set ($MatrixQueue->$Id);
} on-error={
- $LogPrintExit2 debug $0 ("Sending queued Matrix message failed.") false;
+ $LogPrint debug $0 ("Sending queued Matrix message failed.");
:set AllDone false;
}
}
}
:if ($AllDone = true && $QueueLen = [ :len $MatrixQueue ]) do={
- /system/scheduler/remove [ find where name=$0 ];
+ /system/scheduler/remove [ find where name="_FlushMatrixQueue" ];
:set MatrixQueue;
}
-}
+} on-error={
+ :global ExitError; $ExitError false $0;
+} }
# send notification via Matrix - expects one array argument
:set ($NotificationFunctions->"matrix") do={
@@ -70,7 +77,9 @@
:global MatrixRoomOverride;
:global EitherOr;
- :global LogPrintExit2;
+ :global FetchUserAgentStr;
+ :global LogPrint;
+ :global ProtocolStrip;
:global SymbolForNotification;
:local PrepareText do={
@@ -81,21 +90,15 @@
}
:local Return "";
- :local Chars {
- "plain"={ "\\"; "\""; "\n" };
- "format"={ "\\"; "\""; "\n"; "&"; "<"; ">" };
- }
- :local Subs {
- "plain"={ "\\\\"; "\\\""; "\\n" };
- "format"={ "\\\\"; "&quot;"; "<br/>"; "&amp;"; "&lt;"; "&gt;" };
- }
+ :local Chars { "\""; "\n"; "&"; "<"; ">" };
+ :local Subs { "&quot;"; "<br/>"; "&amp;"; "&lt;"; "&gt;" };
:for I from=0 to=([ :len $Input ] - 1) do={
:local Char [ :pick $Input $I ];
- :local Replace [ :find ($Chars->$2) $Char ];
+ :local Replace [ :find $Chars $Char ];
:if ([ :typeof $Replace ] = "num") do={
- :set Char ($Subs->$2->$Replace);
+ :set Char ($Subs->$Replace);
}
:set Return ($Return . $Char);
}
@@ -111,42 +114,45 @@
:return false;
}
- :local Plain [ $PrepareText ("## [" . $IdentityExtra . $Identity . "] " . \
- ($Notification->"subject") . "\n```\n" . ($Notification->"message") . "\n```") "plain" ];
+ :local Headers ({ [ $FetchUserAgentStr ($Notification->"origin") ] });
+ :local Plain ("## [" . $IdentityExtra . $Identity . "] " . \
+ ($Notification->"subject") . "\n```\n" . ($Notification->"message") . "\n```");
:local Formatted ("<h2>" . [ $PrepareText ("[" . $IdentityExtra . $Identity . "] " . \
- ($Notification->"subject")) "format" ] . "</h2>" . "<pre><code>" . \
- [ $PrepareText ($Notification->"message") "format" ] . "</code></pre>");
+ ($Notification->"subject")) ] . "</h2>" . "<pre><code>" . \
+ [ $PrepareText ($Notification->"message") ] . "</code></pre>");
:if ([ :len ($Notification->"link") ] > 0) do={
- :set Plain ($Plain . "\\n" . [ $SymbolForNotification "link" ] . \
- [ $PrepareText ("[" . $Notification->"link" . "](" . $Notification->"link" . ")") "plain" ]);
+ :local Label [ $ProtocolStrip ($Notification->"link") ];
+ :set Plain ($Plain . "\n" . [ $SymbolForNotification "link" ] . \
+ "[" . $Label . "](" . $Notification->"link" . ")");
:set Formatted ($Formatted . "<br/>" . [ $SymbolForNotification "link" ] . \
- "<a href=\\\"" . [ $PrepareText ($Notification->"link") "format" ] . "\\\">" . \
- [ $PrepareText ($Notification->"link") "format" ] . "</a>");
+ "<a href=\"" . [ $PrepareText ($Notification->"link") ] . "\">" . \
+ [ $PrepareText $Label ] . "</a>");
}
:do {
- /tool/fetch check-certificate=yes-without-crl output=none http-method=post \
- ("https://" . $HomeServer . "/_matrix/client/r0/rooms/" . $Room . \
- "/send/m.room.message?access_token=" . $AccessToken) \
- http-data=("{ \"msgtype\": \"m.text\", \"body\": \"" . $Plain . "\"," . \
- "\"format\": \"org.matrix.custom.html\", \"formatted_body\": \"" . \
- $Formatted . "\" }") as-value;
+ /tool/fetch check-certificate=yes-without-crl output=none \
+ http-header-field=$Headers http-method=post \
+ http-data=[ :serialize to=json { "msgtype"="m.text"; "body"=$Plain;
+ "format"="org.matrix.custom.html"; "formatted_body"=$Formatted } ] \
+ ("https://" . $HomeServer . "/_matrix/client/r0/rooms/" . $Room . \
+ "/send/m.room.message?access_token=" . $AccessToken) as-value;
} on-error={
- $LogPrintExit2 info $0 ("Failed sending Matrix notification! Queuing...") false;
+ $LogPrint info $0 ("Failed sending Matrix notification! Queuing...");
:if ([ :typeof $MatrixQueue ] = "nothing") do={
:set MatrixQueue ({});
}
- :local Text ([ $SymbolForNotification "alarm-clock" ] . \
- "This message was queued since " . [ /system/clock/get date ] . \
- " " . [ /system/clock/get time ] . " and may be obsolete.");
- :set Plain ($Plain . "\\n" . $Text);
- :set Formatted ($Formatted . "<br/>" . $Text);
- :set ($MatrixQueue->[ :len $MatrixQueue ]) { room=$Room; \
- accesstoken=$AccessToken; homeserver=$HomeServer; \
- plain=$Plain; formatted=$Formatted };
- :if ([ :len [ /system/scheduler/find where name="\$FlushMatrixQueue" ] ] = 0) do={
- /system/scheduler/add name="\$FlushMatrixQueue" interval=1m start-time=startup \
+ :local Symbol [ $SymbolForNotification "alarm-clock" ];
+ :local DateTime ([ /system/clock/get date ] . " " . [ /system/clock/get time ]);
+ :set Plain ($Plain . "\n" . $Symbol . "This message was queued since *" . \
+ $DateTime . "* and may be obsolete.");
+ :set Formatted ($Formatted . "<br/>" . $Symbol . "This message was queued since <em>" . \
+ $DateTime . "</em> and may be obsolete.");
+ :set ($MatrixQueue->[ :len $MatrixQueue ]) { headers=$Headers; \
+ accesstoken=$AccessToken; homeserver=$HomeServer; room=$Room; \
+ plain=$Plain; formatted=$Formatted };
+ :if ([ :len [ /system/scheduler/find where name="_FlushMatrixQueue" ] ] = 0) do={
+ /system/scheduler/add name="_FlushMatrixQueue" interval=1m start-time=startup \
on-event=(":global FlushMatrixQueue; \$FlushMatrixQueue;");
}
}
@@ -156,16 +162,18 @@
:set PurgeMatrixQueue do={
:global MatrixQueue;
- /system/scheduler/remove [ find where name="\$FlushMatrixQueue" ];
+ /system/scheduler/remove [ find where name="_FlushMatrixQueue" ];
:set MatrixQueue;
}
# send notification via Matrix - expects at least two string arguments
-:set SendMatrix do={
+:set SendMatrix do={ :do {
:global SendMatrix2;
- $SendMatrix2 ({ subject=$1; message=$2; link=$3 });
-}
+ $SendMatrix2 ({ origin=$0; subject=$1; message=$2; link=$3 });
+} on-error={
+ :global ExitError; $ExitError false $0;
+} }
# send notification via Matrix - expects one array argument
:set SendMatrix2 do={
@@ -175,3 +183,89 @@
($NotificationFunctions->"matrix") ("\$NotificationFunctions->\"matrix\"") $Notification;
}
+
+# setup - get home server and access token
+:set SetupMatrixAuthenticate do={
+ :local User [ :tostr $1 ];
+ :local Pass [ :tostr $2 ];
+
+ :global FetchUserAgentStr;
+ :global LogPrint;
+
+ :global MatrixAccessToken;
+ :global MatrixHomeServer;
+
+ :local Domain [ :pick $User ([ :find $User ":" ] + 1) [ :len $User] ];
+ :do {
+ :local Data ([ /tool/fetch check-certificate=yes-without-crl output=user \
+ http-header-field=({ [ $FetchUserAgentStr $0 ] }) \
+ ("https://" . $Domain . "/.well-known/matrix/client") as-value ]->"data");
+ :set MatrixHomeServer ([ :deserialize from=json value=$Data ]->"m.homeserver"->"base_url");
+ $LogPrint debug $0 ("Home server is: " . $MatrixHomeServer);
+ } on-error={
+ $LogPrint error $0 ("Failed getting home server!");
+ :return false;
+ }
+
+ :if ([ :pick $MatrixHomeServer 0 8 ] = "https://") do={
+ :set MatrixHomeServer [ :pick $MatrixHomeServer 8 [ :len $MatrixHomeServer ] ];
+ }
+
+ :do {
+ :local Data ([ /tool/fetch check-certificate=yes-without-crl output=user \
+ http-header-field=({ [ $FetchUserAgentStr $0 ] }) http-method=post \
+ http-data=[ :serialize to=json { "type"="m.login.password"; "user"=$User; "password"=$Pass } ] \
+ ("https://" . $MatrixHomeServer . "/_matrix/client/r0/login") as-value ]->"data");
+ :set MatrixAccessToken ([ :deserialize from=json value=$Data ]->"access_token");
+ $LogPrint debug $0 ("Access token is: " . $MatrixAccessToken);
+ } on-error={
+ $LogPrint error $0 ("Failed logging in (and getting access token)!");
+ :return false;
+ }
+
+ :do {
+ /system/script/remove [ find where name="global-config-overlay.d/mod/notification-matrix" ];
+ /system/script/add name="global-config-overlay.d/mod/notification-matrix" source=( \
+ "# configuration snippet: mod/notification-matrix\n\n" . \
+ ":global MatrixHomeServer \"" . $MatrixHomeServer . "\";\n" . \
+ ":global MatrixAccessToken \"" . $MatrixAccessToken . "\";\n");
+ $LogPrint info $0 ("Added configuration snippet. Now create and join a room, please!");
+ } on-error={
+ $LogPrint error $0 ("Failed adding configuration snippet!");
+ :return false;
+ }
+}
+
+# setup - join a room
+:set SetupMatrixJoinRoom do={
+ :global MatrixRoom [ :tostr $1 ];
+
+ :global FetchUserAgentStr;
+ :global LogPrint;
+ :global UrlEncode;
+
+ :global MatrixAccessToken;
+ :global MatrixHomeServer;
+ :global MatrixRoom;
+
+ :do {
+ /tool/fetch check-certificate=yes-without-crl output=none \
+ http-header-field=({ [ $FetchUserAgentStr $0 ] }) http-method=post http-data="" \
+ ("https://" . $MatrixHomeServer . "/_matrix/client/r0/rooms/" . [ $UrlEncode $MatrixRoom ] . \
+ "/join?access_token=" . [ $UrlEncode $MatrixAccessToken ]) as-value;
+ $LogPrint debug $0 ("Joined the room.");
+ } on-error={
+ $LogPrint error $0 ("Failed joining the room!");
+ :return false;
+ }
+
+ :do {
+ :local Snippet [ /system/script/find where name="global-config-overlay.d/mod/notification-matrix" ];
+ /system/script/set $Snippet source=([ get $Snippet source ] . \
+ ":global MatrixRoom \"" . $MatrixRoom . "\";\n");
+ $LogPrint info $0 ("Appended configuration to configuration snippet. Please review!");
+ } on-error={
+ $LogPrint error $0 ("Failed appending configuration to snippet!");
+ :return false;
+ }
+}
diff --git a/mod/notification-ntfy.rsc b/mod/notification-ntfy.rsc
new file mode 100644
index 0000000..2748c5b
--- /dev/null
+++ b/mod/notification-ntfy.rsc
@@ -0,0 +1,161 @@
+#!rsc by RouterOS
+# RouterOS script: mod/notification-ntfy
+# Copyright (c) 2013-2025 Christian Hesse <mail@eworm.de>
+# https://rsc.eworm.de/COPYING.md
+#
+# requires RouterOS, version=7.15
+# requires device-mode, fetch, scheduler
+#
+# send notifications via Ntfy (ntfy.sh)
+# https://rsc.eworm.de/doc/mod/notification-ntfy.md
+
+:global FlushNtfyQueue;
+:global NotificationFunctions;
+:global PurgeNtfyQueue;
+:global SendNtfy;
+:global SendNtfy2;
+
+# flush ntfy queue
+:set FlushNtfyQueue do={ :do {
+ :global NtfyQueue;
+
+ :global IsFullyConnected;
+ :global LogPrint;
+
+ :if ([ $IsFullyConnected ] = false) do={
+ $LogPrint debug $0 ("System is not fully connected, not flushing.");
+ :return false;
+ }
+
+ :local AllDone true;
+ :local QueueLen [ :len $NtfyQueue ];
+
+ :if ([ :len [ /system/scheduler/find where name="_FlushNtfyQueue" ] ] > 0 && $QueueLen = 0) do={
+ $LogPrint warning $0 ("Flushing Ntfy messages from scheduler, but queue is empty.");
+ }
+
+ :foreach Id,Message in=$NtfyQueue do={
+ :if ([ :typeof $Message ] = "array" ) do={
+ :do {
+ /tool/fetch check-certificate=yes-without-crl output=none http-method=post \
+ http-header-field=($Message->"headers") http-data=($Message->"text") \
+ ($Message->"url") as-value;
+ :set ($NtfyQueue->$Id);
+ } on-error={
+ $LogPrint debug $0 ("Sending queued Ntfy message failed.");
+ :set AllDone false;
+ }
+ }
+ }
+
+ :if ($AllDone = true && $QueueLen = [ :len $NtfyQueue ]) do={
+ /system/scheduler/remove [ find where name="_FlushNtfyQueue" ];
+ :set NtfyQueue;
+ }
+} on-error={
+ :global ExitError; $ExitError false $0;
+} }
+
+# send notification via ntfy - expects one array argument
+:set ($NotificationFunctions->"ntfy") do={
+ :local Notification $1;
+
+ :global Identity;
+ :global IdentityExtra;
+ :global NtfyQueue;
+ :global NtfyServer;
+ :global NtfyServerOverride;
+ :global NtfyServerPass;
+ :global NtfyServerPassOverride;
+ :global NtfyServerToken;
+ :global NtfyServerTokenOverride;
+ :global NtfyServerUser;
+ :global NtfyServerUserOverride;
+ :global NtfyTopic;
+ :global NtfyTopicOverride;
+
+ :global CertificateAvailable;
+ :global EitherOr;
+ :global FetchUserAgentStr;
+ :global IfThenElse;
+ :global LogPrint;
+ :global SymbolForNotification;
+ :global UrlEncode;
+
+ :local Server [ $EitherOr ($NtfyServerOverride->($Notification->"origin")) $NtfyServer ];
+ :local User [ $EitherOr ($NtfyServerUserOverride->($Notification->"origin")) $NtfyServerUser ];
+ :local Pass [ $EitherOr ($NtfyServerPassOverride->($Notification->"origin")) $NtfyServerPass ];
+ :local Token [ $EitherOr ($NtfyServerTokenOverride->($Notification->"origin")) $NtfyServerToken ];
+ :local Topic [ $EitherOr ($NtfyTopicOverride->($Notification->"origin")) $NtfyTopic ];
+
+ :if ([ :len $Topic ] = 0) do={
+ :return false;
+ }
+
+ :local Url ("https://" . $Server . "/" . [ $UrlEncode $Topic ]);
+ :local Headers ({ [ $FetchUserAgentStr ($Notification->"origin") ]; \
+ ("Priority: " . [ $IfThenElse ($Notification->"silent") "low" "default" ]); \
+ ("Title: " . "[" . $IdentityExtra . $Identity . "] " . ($Notification->"subject")) });
+ :if ([ :len $User ] > 0 || [ :len $Pass ] > 0) do={
+ :set Headers ($Headers, ("Authorization: Basic " . [ :convert to=base64 ($User . ":" . $Pass) ]));
+ }
+ :if ([ :len $Token ] > 0) do={
+ :set Headers ($Headers, ("Authorization: Bearer " . $Token));
+ }
+ :local Text (($Notification->"message") . "\n");
+ :if ([ :len ($Notification->"link") ] > 0) do={
+ :set Text ($Text . "\n" . [ $SymbolForNotification "link" ] . ($Notification->"link"));
+ }
+
+ :do {
+ :if ($Server = "ntfy.sh") do={
+ :if ([ $CertificateAvailable "ISRG Root X1" ] = false) do={
+ $LogPrint warning $0 ("Downloading required certificate failed.");
+ :error false;
+ }
+ }
+ /tool/fetch check-certificate=yes-without-crl output=none http-method=post \
+ http-header-field=$Headers http-data=$Text $Url as-value;
+ } on-error={
+ $LogPrint info $0 ("Failed sending ntfy notification! Queuing...");
+
+ :if ([ :typeof $NtfyQueue ] = "nothing") do={
+ :set NtfyQueue ({});
+ }
+ :set Text ($Text . "\n" . [ $SymbolForNotification "alarm-clock" ] . \
+ "This message was queued since " . [ /system/clock/get date ] . " " . \
+ [ /system/clock/get time ] . " and may be obsolete.");
+ :set ($NtfyQueue->[ :len $NtfyQueue ]) \
+ { url=$Url; headers=$Headers; text=$Text };
+ :if ([ :len [ /system/scheduler/find where name="_FlushNtfyQueue" ] ] = 0) do={
+ /system/scheduler/add name="_FlushNtfyQueue" interval=1m start-time=startup \
+ on-event=(":global FlushNtfyQueue; \$FlushNtfyQueue;");
+ }
+ }
+}
+
+# purge the Ntfy queue
+:set PurgeNtfyQueue do={
+ :global NtfyQueue;
+
+ /system/scheduler/remove [ find where name="_FlushNtfyQueue" ];
+ :set NtfyQueue;
+}
+
+# send notification via ntfy - expects at least two string arguments
+:set SendNtfy do={ :do {
+ :global SendNtfy2;
+
+ $SendNtfy2 ({ origin=$0; subject=$1; message=$2; link=$3; silent=$4 });
+} on-error={
+ :global ExitError; $ExitError false $0;
+} }
+
+# send notification via ntfy - expects one array argument
+:set SendNtfy2 do={
+ :local Notification $1;
+
+ :global NotificationFunctions;
+
+ ($NotificationFunctions->"ntfy") ("\$NotificationFunctions->\"ntfy\"") $Notification;
+}
diff --git a/mod/notification-telegram.rsc b/mod/notification-telegram.rsc
index ea47b1a..5ef353b 100644
--- a/mod/notification-telegram.rsc
+++ b/mod/notification-telegram.rsc
@@ -1,59 +1,102 @@
#!rsc by RouterOS
# RouterOS script: mod/notification-telegram
-# Copyright (c) 2013-2023 Christian Hesse <mail@eworm.de>
-# https://git.eworm.de/cgit/routeros-scripts/about/COPYING.md
+# Copyright (c) 2013-2025 Christian Hesse <mail@eworm.de>
+# https://rsc.eworm.de/COPYING.md
+#
+# requires RouterOS, version=7.15
+# requires device-mode, fetch, scheduler
#
# send notifications via Telegram
-# https://git.eworm.de/cgit/routeros-scripts/about/doc/mod/notification-telegram.md
+# https://rsc.eworm.de/doc/mod/notification-telegram.md
:global FlushTelegramQueue;
+:global GetTelegramChatId;
:global NotificationFunctions;
:global PurgeTelegramQueue;
:global SendTelegram;
:global SendTelegram2;
# flush telegram queue
-:set FlushTelegramQueue do={
+:set FlushTelegramQueue do={ :do {
:global TelegramQueue;
+ :global TelegramMessageIDs;
:global IsFullyConnected;
- :global LogPrintExit2;
+ :global LogPrint;
:if ([ $IsFullyConnected ] = false) do={
- $LogPrintExit2 debug $0 ("System is not fully connected, not flushing.") false;
+ $LogPrint debug $0 ("System is not fully connected, not flushing.");
:return false;
}
:local AllDone true;
:local QueueLen [ :len $TelegramQueue ];
- :if ([ :len [ /system/scheduler/find where name=$0 ] ] > 0 && $QueueLen = 0) do={
- $LogPrintExit2 warning $0 ("Flushing Telegram messages from scheduler, but queue is empty.") false;
+ :if ([ :len [ /system/scheduler/find where name="_FlushTelegramQueue" ] ] > 0 && $QueueLen = 0) do={
+ $LogPrint warning $0 ("Flushing Telegram messages from scheduler, but queue is empty.");
}
:foreach Id,Message in=$TelegramQueue do={
:if ([ :typeof $Message ] = "array" ) do={
:do {
- /tool/fetch check-certificate=yes-without-crl output=none http-method=post \
+ :local Data ([ /tool/fetch check-certificate=yes-without-crl output=user http-method=post \
("https://api.telegram.org/bot" . ($Message->"tokenid") . "/sendMessage") \
- http-data=("chat_id=" . ($Message->"chatid") . \
- "&disable_notification=" . ($Message->"silent") . \
- "&reply_to_message_id=" . ($Message->"replyto") . \
- "&disable_web_page_preview=true&parse_mode=" . ($Message->"parsemode") . \
- "&text=" . ($Message->"text")) as-value;
+ http-data=($Message->"http-data") as-value ]->"data");
:set ($TelegramQueue->$Id);
+ :set ($TelegramMessageIDs->[ :tostr ([ :deserialize from=json value=$Data ]->"result"->"message_id") ]) 1;
} on-error={
- $LogPrintExit2 debug $0 ("Sending queued Telegram message failed.") false;
+ $LogPrint debug $0 ("Sending queued Telegram message failed.");
:set AllDone false;
}
}
}
:if ($AllDone = true && $QueueLen = [ :len $TelegramQueue ]) do={
- /system/scheduler/remove [ find where name=$0 ];
+ /system/scheduler/remove [ find where name="_FlushTelegramQueue" ];
:set TelegramQueue;
}
-}
+} on-error={
+ :global ExitError; $ExitError false $0;
+} }
+
+# get the chat id
+:set GetTelegramChatId do={ :do {
+ :global TelegramTokenId;
+
+ :global CertificateAvailable;
+ :global LogPrint;
+
+ :if ([ $CertificateAvailable "Go Daddy Root Certificate Authority - G2" ] = false) do={
+ $LogPrint warning $0 ("Downloading required certificate failed.");
+ :return false;
+ }
+
+ :local Data;
+ :do {
+ :set Data ([ /tool/fetch check-certificate=yes-without-crl output=user \
+ ("https://api.telegram.org/bot" . $TelegramTokenId . "/getUpdates?offset=0" . \
+ "&allowed_updates=%5B%22message%22%5D") as-value ]->"data");
+ } on-error={
+ $LogPrint warning $0 ("Fetching data failed!");
+ :return false;
+ }
+
+ :local JSON [ :deserialize from=json value=$Data ];
+ :local Count [ :len ($JSON->"result") ];
+
+ :if ($Count = 0) do={
+ $LogPrint info $0 ("No message received.");
+ :return false;
+ }
+
+ :local Message ($JSON->"result"->($Count - 1)->"message");
+ $LogPrint info $0 ("The chat id is: " . ($Message->"chat"->"id"));
+ :if (($Message->"is_topic_message") = true) do={
+ $LogPrint info $0 ("The thread id is: " . ($Message->"message_thread_id"));
+ }
+} on-error={
+ :global ExitError; $ExitError false $0;
+} }
# send notification via telegram - expects one array argument
:set ($NotificationFunctions->"telegram") do={
@@ -63,8 +106,10 @@
:global IdentityExtra;
:global TelegramChatId;
:global TelegramChatIdOverride;
- :global TelegramFixedWidthFont;
+ :global TelegramMessageIDs;
:global TelegramQueue;
+ :global TelegramThreadId;
+ :global TelegramThreadIdOverride;
:global TelegramTokenId;
:global TelegramTokenIdOverride;
@@ -72,51 +117,58 @@
:global CharacterReplace;
:global EitherOr;
:global IfThenElse;
- :global LogPrintExit2;
+ :global LogPrint;
+ :global ProtocolStrip;
:global SymbolForNotification;
:global UrlEncode;
:local EscapeMD do={
- :global TelegramFixedWidthFont;
+ :local Text [ :tostr $1 ];
+ :local Mode [ :tostr $2 ];
+ :local Excl [ :tostr $3 ];
:global CharacterReplace;
:global IfThenElse;
- :if ($TelegramFixedWidthFont != true) do={
- :return ($1 . [ $IfThenElse ($2 = "body") ("\n") "" ]);
- }
-
- :local Return $1;
:local Chars {
- "body"={ "\\"; "`" };
+ "body"={ "\\"; "`" };
"plain"={ "_"; "*"; "["; "]"; "("; ")"; "~"; "`"; ">";
"#"; "+"; "-"; "="; "|"; "{"; "}"; "."; "!" };
}
- :foreach Char in=($Chars->$2) do={
- :set Return [ $CharacterReplace $Return $Char ("\\" . $Char) ];
+ :foreach Char in=($Chars->$Mode) do={
+ :if ([ :typeof [ :find $Excl $Char ] ] = "nil") do={
+ :set Text [ $CharacterReplace $Text $Char ("\\" . $Char) ];
+ }
}
- :if ($2 = "body") do={
- :return ("```\n" . $Return . "\n```");
+ :if ($Mode = "body") do={
+ :return ("```\n" . $Text . "\n```");
}
- :return $Return;
+ :return $Text;
}
:local ChatId [ $EitherOr ($Notification->"chatid") \
[ $EitherOr ($TelegramChatIdOverride->($Notification->"origin")) $TelegramChatId ] ];
+ :local ThreadId [ $EitherOr ($Notification->"threadid") \
+ [ $EitherOr ($TelegramThreadIdOverride->($Notification->"origin")) \
+ [ $IfThenElse ([ :len ($TelegramChatIdOverride->($Notification->"origin")) ] = 0) $TelegramThreadId ] ] ];
:local TokenId [ $EitherOr ($TelegramTokenIdOverride->($Notification->"origin")) $TelegramTokenId ];
:if ([ :len $TokenId ] = 0 || [ :len $ChatId ] = 0) do={
:return false;
}
+ :if ([ :typeof $TelegramMessageIDs ] = "nothing") do={
+ :set TelegramMessageIDs ({});
+ }
+
:local Truncated false;
:local Text ("*__" . [ $EscapeMD ("[" . $IdentityExtra . $Identity . "] " . \
($Notification->"subject")) "plain" ] . "__*\n\n");
:local LenSubject [ :len $Text ];
:local LenMessage [ :len ($Notification->"message") ];
- :local LenLink [ :len ($Notification->"link") ];
+ :local LenLink ([ :len ($Notification->"link") ] * 2);
:local LenSum ($LenSubject + $LenMessage + $LenLink);
:if ($LenSum > 3968) do={
:set Text ($Text . [ $EscapeMD ([ :pick ($Notification->"message") 0 (3840 - $LenSubject - $LenLink) ] . "...") "body" ]);
@@ -125,39 +177,41 @@
:set Text ($Text . [ $EscapeMD ($Notification->"message") "body" ]);
}
:if ($LenLink > 0) do={
- :set Text ($Text . "\n" . [ $SymbolForNotification "link" ] . [ $EscapeMD ($Notification->"link") "plain" ]);
+ :set Text ($Text . "\n" . [ $SymbolForNotification "link" ] . \
+ "[" . [ $EscapeMD [ $ProtocolStrip ($Notification->"link") ] "plain" ] . "]" . \
+ "(" . [ $EscapeMD ($Notification->"link") "plain" ] . ")");
}
:if ($Truncated = true) do={
:set Text ($Text . "\n" . [ $SymbolForNotification "scissors" ] . \
- [ $EscapeMD ("The message was too long and has been truncated, cut off " . \
- (($LenSum - [ :len $Text ]) * 100 / $LenSum) . "%!") "plain" ]);
+ [ $EscapeMD ("The message was too long and has been truncated, cut off _" . \
+ (($LenSum - [ :len $Text ]) * 100 / $LenSum) . "%_!") "plain" "_" ]);
}
- :set Text [ $UrlEncode $Text ];
- :local ParseMode [ $IfThenElse ($TelegramFixedWidthFont = true) "MarkdownV2" "" ];
+ :local HTTPData ("chat_id=" . $ChatId . "&disable_notification=" . ($Notification->"silent") . \
+ "&reply_to_message_id=" . ($Notification->"replyto") . "&message_thread_id=" . $ThreadId . \
+ "&disable_web_page_preview=true&parse_mode=MarkdownV2");
:do {
- :if ([ $CertificateAvailable "Go Daddy Secure Certificate Authority - G2" ] = false) do={
- $LogPrintExit2 warning $0 ("Downloading required certificate failed.") true;
+ :if ([ $CertificateAvailable "Go Daddy Root Certificate Authority - G2" ] = false) do={
+ $LogPrint warning $0 ("Downloading required certificate failed.");
+ :error false;
}
- /tool/fetch check-certificate=yes-without-crl output=none http-method=post \
+ :local Data ([ /tool/fetch check-certificate=yes-without-crl output=user http-method=post \
("https://api.telegram.org/bot" . $TokenId . "/sendMessage") \
- http-data=("chat_id=" . $ChatId . "&disable_notification=" . ($Notification->"silent") . \
- "&reply_to_message_id=" . ($Notification->"replyto") . \
- "&disable_web_page_preview=true&parse_mode=" . $ParseMode . "&text=" . $Text) as-value;
+ http-data=($HTTPData . "&text=" . [ $UrlEncode $Text ]) as-value ]->"data");
+ :set ($TelegramMessageIDs->[ :tostr ([ :deserialize from=json value=$Data ]->"result"->"message_id") ]) 1;
} on-error={
- $LogPrintExit2 info $0 ("Failed sending telegram notification! Queuing...") false;
+ $LogPrint info $0 ("Failed sending Telegram notification! Queuing...");
:if ([ :typeof $TelegramQueue ] = "nothing") do={
:set TelegramQueue ({});
}
- :set Text ($Text . [ $UrlEncode ("\n" . [ $SymbolForNotification "alarm-clock" ] . \
- [ $EscapeMD ("This message was queued since " . [ /system/clock/get date ] . \
- " " . [ /system/clock/get time ] . " and may be obsolete.") "plain" ]) ]);
- :set ($TelegramQueue->[ :len $TelegramQueue ]) { chatid=$ChatId; tokenid=$TokenId;
- parsemode=$ParseMode; text=$Text; silent=($Notification->"silent");
- replyto=($Notification->"replyto") };
- :if ([ :len [ /system/scheduler/find where name="\$FlushTelegramQueue" ] ] = 0) do={
- /system/scheduler/add name="\$FlushTelegramQueue" interval=1m start-time=startup \
+ :set Text ($Text . "\n" . [ $SymbolForNotification "alarm-clock" ] . \
+ [ $EscapeMD ("This message was queued since _" . [ /system/clock/get date ] . \
+ " " . [ /system/clock/get time ] . "_ and may be obsolete.") "plain" "_" ]);
+ :set ($TelegramQueue->[ :len $TelegramQueue ]) { tokenid=$TokenId;
+ http-data=($HTTPData . "&text=" . [ $UrlEncode $Text ]) };
+ :if ([ :len [ /system/scheduler/find where name="_FlushTelegramQueue" ] ] = 0) do={
+ /system/scheduler/add name="_FlushTelegramQueue" interval=1m start-time=startup \
on-event=(":global FlushTelegramQueue; \$FlushTelegramQueue;");
}
}
@@ -167,16 +221,18 @@
:set PurgeTelegramQueue do={
:global TelegramQueue;
- /system/scheduler/remove [ find where name="\$FlushTelegramQueue" ];
+ /system/scheduler/remove [ find where name="_FlushTelegramQueue" ];
:set TelegramQueue;
}
# send notification via telegram - expects at least two string arguments
-:set SendTelegram do={
+:set SendTelegram do={ :do {
:global SendTelegram2;
- $SendTelegram2 ({ subject=$1; message=$2; link=$3; silent=$4 });
-}
+ $SendTelegram2 ({ origin=$0; subject=$1; message=$2; link=$3; silent=$4 });
+} on-error={
+ :global ExitError; $ExitError false $0;
+} }
# send notification via telegram - expects one array argument
:set SendTelegram2 do={
diff --git a/mod/scriptrunonce.rsc b/mod/scriptrunonce.rsc
index 199d852..7fcd5b5 100644
--- a/mod/scriptrunonce.rsc
+++ b/mod/scriptrunonce.rsc
@@ -1,49 +1,56 @@
#!rsc by RouterOS
# RouterOS script: mod/scriptrunonece
-# Copyright (c) 2020-2023 Christian Hesse <mail@eworm.de>
-# https://git.eworm.de/cgit/routeros-scripts/about/COPYING.md
+# Copyright (c) 2020-2025 Christian Hesse <mail@eworm.de>
+# https://rsc.eworm.de/COPYING.md
+#
+# requires RouterOS, version=7.15
#
# download script and run it once
-# https://git.eworm.de/cgit/routeros-scripts/about/doc/mod/scriptrunonce.md
+# https://rsc.eworm.de/doc/mod/scriptrunonce.md
:global ScriptRunOnce;
# fetch and run script(s) once
-:set ScriptRunOnce do={
+:set ScriptRunOnce do={ :do {
:local Scripts [ :toarray $1 ];
:global ScriptRunOnceBaseUrl;
:global ScriptRunOnceUrlSuffix;
- :global LogPrintExit2;
+ :global FetchHuge;
+ :global LogPrint;
:global ValidateSyntax;
:foreach Script in=$Scripts do={
:if (!($Script ~ "^(ftp|https?|sftp)://")) do={
:if ([ :len $ScriptRunOnceBaseUrl ] = 0) do={
- $LogPrintExit2 warning $0 ("Script '" . $Script . "' is not an url and base url is not available.") true;
+ $LogPrint warning $0 ("Script '" . $Script . "' is not an url and base url is not available.");
+ :return false;
}
:set Script ($ScriptRunOnceBaseUrl . $Script . ".rsc" . $ScriptRunOnceUrlSuffix);
}
- :local Source;
- :do {
- :set Source ([ /tool/fetch check-certificate=yes-without-crl $Script output=user as-value ]->"data");
- } on-error={
- $LogPrintExit2 warning $0 ("Failed fetching script '" . $Script . "'!") false;
+ :local Source [ $FetchHuge $0 $Script true ];
+ :if ($Source = false) do={
+ $LogPrint warning $0 ("Failed fetching script '" . $Script . "'!");
+ :return false;
}
- :if ([ :len $Source ] > 0) do={
- :if ([ $ValidateSyntax $Source ] = true) do={
- :do {
- $LogPrintExit2 info $0 ("Running script '" . $Script . "' now.") false;
- [ :parse $Source ];
- } on-error={
- $LogPrintExit2 warning $0 ("The script '" . $Script . "' failed to run!") false;
- }
- } else={
- $LogPrintExit2 warning $0 ("The script '" . $Script . "' failed syntax validation!") false;
- }
+ :if ([ $ValidateSyntax $Source ] = false) do={
+ $LogPrint warning $0 ("The script '" . $Script . "' failed syntax validation!");
+ :return false;
}
+
+ :do {
+ $LogPrint info $0 ("Running script '" . $Script . "' now.");
+ [ :parse $Source ];
+ } on-error={
+ $LogPrint warning $0 ("The script '" . $Script . "' failed to run!");
+ :return false;
+ }
+
+ :return true;
}
-}
+} on-error={
+ :global ExitError; $ExitError false $0;
+} }
diff --git a/mod/ssh-keys-import.rsc b/mod/ssh-keys-import.rsc
index 31bb3e6..2fae4b1 100644
--- a/mod/ssh-keys-import.rsc
+++ b/mod/ssh-keys-import.rsc
@@ -1,89 +1,114 @@
#!rsc by RouterOS
# RouterOS script: mod/ssh-keys-import
-# Copyright (c) 2020-2023 Christian Hesse <mail@eworm.de>
-# https://git.eworm.de/cgit/routeros-scripts/about/COPYING.md
+# Copyright (c) 2020-2025 Christian Hesse <mail@eworm.de>
+# https://rsc.eworm.de/COPYING.md
+#
+# requires RouterOS, version=7.16
#
# import ssh keys for public key authentication
-# https://git.eworm.de/cgit/routeros-scripts/about/doc/mod/ssh-keys-import.md
+# https://rsc.eworm.de/doc/mod/ssh-keys-import.md
:global SSHKeysImport;
:global SSHKeysImportFile;
# import single key passed as string
-:set SSHKeysImport do={
+:set SSHKeysImport do={ :do {
:local Key [ :tostr $1 ];
:local User [ :tostr $2 ];
:global GetRandom20CharAlNum;
- :global LogPrintExit2;
+ :global LogPrint;
:global MkDir;
- :global RequiredRouterOS;
+ :global RmDir;
:global WaitForFile;
:if ([ :len $Key ] = 0 || [ :len $User ] = 0) do={
- $LogPrintExit2 warning $0 ("Missing argument(s), please pass key and user!") true;
+ $LogPrint warning $0 ("Missing argument(s), please pass key and user!");
+ :return false;
}
:if ([ :len [ /user/find where name=$User ] ] = 0) do={
- $LogPrintExit2 warning $0 ("User '" . $User . "' does not exist.") true;
+ $LogPrint warning $0 ("User '" . $User . "' does not exist.");
+ :return false;
+ }
+
+ :local KeyVal ([ :deserialize $Key delimiter=" " from=dsv options=dsv.plain ]->0);
+ :if (!($KeyVal->0 = "ssh-ed25519" || $KeyVal->0 = "ssh-rsa")) do={
+ $LogPrint warning $0 ("SSH key of type '" . $KeyVal->0 . "' is not supported.");
+ :return false;
}
- :local Type [ :pick $Key 0 [ :find $Key " " ] ];
- :if (!(([ $RequiredRouterOS $0 "7.12beta1" ] = true && $Type = "ssh-ed25519") || $Type = "ssh-rsa")) do={
- $LogPrintExit2 warning $0 ("SSH key of type '" . $Type . "' is not supported.") true;
+ :local FingerPrintMD5 [ :convert from=base64 transform=md5 to=hex ($KeyVal->1) ];
+
+ :if ([ :len [ /user/ssh-keys/find where user=$User key-owner~("\\bmd5=" . $FingerPrintMD5 . "\\b") ] ] > 0) do={
+ $LogPrint warning $0 ("The ssh public key (MD5:" . $FingerPrintMD5 . \
+ ") is already available for user '" . $User . "'.");
+ :return false;
}
:if ([ $MkDir "tmpfs/ssh-keys-import" ] = false) do={
- $LogPrintExit2 warning $0 ("Creating directory 'tmpfs/ssh-keys-import' failed!") true;
+ $LogPrint warning $0 ("Creating directory 'tmpfs/ssh-keys-import' failed!");
+ :return false;
}
:local FileName ("tmpfs/ssh-keys-import/key-" . [ $GetRandom20CharAlNum 6 ] . ".pub");
- /file/add name=$FileName contents=$Key;
+ /file/add name=$FileName contents=($Key . ", md5=" . $FingerPrintMD5);
$WaitForFile $FileName;
:do {
/user/ssh-keys/import public-key-file=$FileName user=$User;
+ $LogPrint info $0 ("Imported ssh public key (" . $KeyVal->2 . ", " . $KeyVal->0 . ", " . \
+ "MD5:" . $FingerPrintMD5 . ") for user '" . $User . "'.");
+ $RmDir "tmpfs/ssh-keys-import";
} on-error={
- $LogPrintExit2 warning $0 ("Failed importing key.") true;
+ $LogPrint warning $0 ("Failed importing key.");
+ $RmDir "tmpfs/ssh-keys-import";
+ :return false;
}
-}
+} on-error={
+ :global ExitError; $ExitError false $0;
+} }
# import keys from a file
-:set SSHKeysImportFile do={
+:set SSHKeysImportFile do={ :do {
:local FileName [ :tostr $1 ];
:local User [ :tostr $2 ];
:global EitherOr;
- :global LogPrintExit2;
+ :global LogPrint;
:global ParseKeyValueStore;
- :global RequiredRouterOS;
:global SSHKeysImport;
:if ([ :len $FileName ] = 0 || [ :len $User ] = 0) do={
- $LogPrintExit2 warning $0 ("Missing argument(s), please pass file name and user!") true;
+ $LogPrint warning $0 ("Missing argument(s), please pass file name and user!");
+ :return false;
}
:local File [ /file/find where name=$FileName ];
:if ([ :len $File ] = 0) do={
- $LogPrintExit2 warning $0 ("File '" . $FileName . "' does not exist.") true;
+ $LogPrint warning $0 ("File '" . $FileName . "' does not exist.");
+ :return false;
}
- :local Keys ([ /file/get $FileName contents ] . "\n");
+ :local Keys [ :tolf [ /file/get $FileName contents ] ];
- :do {
+ :foreach KeyVal in=[ :deserialize $Keys delimiter=" " from=dsv options=dsv.plain ] do={
:local Continue false;
- :local Line [ :pick $Keys 0 [ :find $Keys "\n" ] ];
- :set Keys [ :pick $Keys ([ :find $Keys "\n" ] + 1) [ :len $Keys ] ];
- :local Type [ :pick $Line 0 [ :find $Line " " ] ];
- :if (([ $RequiredRouterOS $0 "7.12beta1" ] = true && $Type = "ssh-ed25519") || $Type = "ssh-rsa") do={
- $SSHKeysImport $Line $User;
+ :if ($KeyVal->0 = "ssh-ed25519" || $KeyVal->0 = "ssh-rsa") do={
+ :do {
+ $SSHKeysImport ($KeyVal->0 . " " . $KeyVal->1 . " " . $KeyVal->2) $User;
+ } on-error={
+ $LogPrint warning $0 ("Failed importing key for user '" . $User . "'.");
+ }
:set Continue true;
}
- :if ($Continue = false && $Type = "#") do={
- :set User [ $EitherOr ([ $ParseKeyValueStore [ :pick $Line 2 [ :len $Line ] ] ]->"user") $User ];
+ :if ($Continue = false && $KeyVal->0 = "#") do={
+ :set User [ $EitherOr ([ $ParseKeyValueStore ($KeyVal->1) ]->"user") $User ];
:set Continue true;
}
- :if ($Continue = false && [ :len $Type ] > 0) do={
- $LogPrintExit2 warning $0 ("SSH key of type '" . $Type . "' is not supported.") false;
+ :if ($Continue = false && [ :len ($KeyVal->0) ] > 0) do={
+ $LogPrint warning $0 ("SSH key of type '" . $KeyVal->0 . "' is not supported.");
}
- } while=([ :len $Keys ] > 0);
-}
+ }
+} on-error={
+ :global ExitError; $ExitError false $0;
+} }