Skip to content

Instantly share code, notes, and snippets.

@alsolovyev
Last active June 30, 2024 11:43
Show Gist options
  • Save alsolovyev/30dcf3ed490f313cfcf18839a51dfc97 to your computer and use it in GitHub Desktop.
Save alsolovyev/30dcf3ed490f313cfcf18839a51dfc97 to your computer and use it in GitHub Desktop.
Managing the state of Wi-Fi interfaces via ssh on MikroTik routers running RouterOS
#
# Remark:
# The USERNAME, HOST, PORT, SSH_KEY_PATH variables must be filled in before use
#
# Usage:
# - wifi Guest status
# - wifi Guest on
# - wifi Guest off
# - wifi Guest toggle
# - wifi Guest
#
function wifi --description "Manage the state of Wi-Fi on Mikrotik"
function _exec_mikrotik_command -d "Execute a command on a MikroTik router"
set -l CONNECTION_TIMEOUT 3
set -l HOST
set -l PORT
set -l SSH_KEY_PATH
set -l USERNAME
# Check if SSH key exists
if not test -e $SSH_KEY_PATH
echo "SSH key not found at $SSH_KEY_PATH"
return 1
end
ssh \
-i $SSH_KEY_PATH \
-o PubkeyAcceptedAlgorithms=ssh-rsa \
-o ConnectTimeout=$CONNECTION_TIMEOUT \
-p $PORT \
$USERNAME@$HOST \
$argv
end
function _echo_error -d "Echo error message"
set_color red; echo "Error: $argv"; set_color normal
end
# Variables
set -l INTERFACE_NAME $argv[1]
set -l ACTION (if test (count $argv) -ge 2; echo $argv[2]; else; echo ""; end)
set -l IS_DISABLED (string trim -- (
_exec_mikrotik_command "/interface wireless; :put [get $INTERFACE_NAME disabled]")
)
if test $status -ne 0
_echo_error $IS_DISABLED
return
end
switch $ACTION
case "status"
echo "WiFi is $(if test $IS_DISABLED = "false"; echo "enabled"; else; echo "disabled"; end)"
return
case "on"
if test $IS_DISABLED = "false"
echo "WiFi is already enabled"
return
end
set NEW_STATE "no"
case "off"
if test $IS_DISABLED = "true"
echo "WiFi is already disabled"
return
end
set NEW_STATE "yes"
case "*"
if test $IS_DISABLED = "true"
set NEW_STATE "no"
else
set NEW_STATE "yes"
end
end
set -l OUTPUT (_exec_mikrotik_command "/interface wireless set $INTERFACE_NAME disabled=$NEW_STATE")
if test $status -ne 0
_echo_error $OUTPUT
return $status
end
echo "WiFi has been $(if test $NEW_STATE = "no"; echo "enabled"; else; echo "disabled"; end)"
end
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment