import routeros_api
import sys
import pprint
HOST = '192.168.1.1'
USERNAME = 'user'
PASSWORD = '********'
API_PORT = 8728
USE_SSL = False
MANGLE_RULE_COMMENT = 'VPN4AlexS23U'
connection = None
try:
print(f"Connecting to MikroTik device at {HOST}:{API_PORT}...")
connection = routeros_api.RouterOsApiPool(
host=HOST,
username=USERNAME,
password=PASSWORD,
port=API_PORT,
plaintext_login=True,
use_ssl=USE_SSL
)
api = connection.get_api()
print("Connection successful.")
mangle = api.get_resource('/ip/firewall/mangle')
print(f"Searching for mangle rule with comment: '{MANGLE_RULE_COMMENT}'...")
rules = mangle.get(comment=MANGLE_RULE_COMMENT)
if rules:
rule_data = rules[0]
if 'id' in rule_data:
rule_id = rule_data['id']
rule_dis = rule_data['disabled']
print(f"Found rule with ID: {rule_id}")
# ON/OFF the found rule
if rule_dis == "true":
print("Enabling the rule...")
mangle.set(id=rule_id, disabled='no')
print("Mangle rule enabled successfully.")
else:
print("Disabling the rule...")
mangle.set(id=rule_id, disabled='yes')
print("Mangle rule disabled successfully.")
else:
print("Error: The found rule does not have a valid '.id' key.", file=sys.stderr)
print("Full rule data for debugging:", file=sys.stderr)
pprint.pprint(rule_data, stream=sys.stderr)
sys.exit(1)
else:
print(f"Error: Rule with comment '{MANGLE_RULE_COMMENT}' not found on the device.", file=sys.stderr)
sys.exit(1)
except routeros_api.exceptions.RouterOsApiError as e:
print(f"An API error occurred: {e}", file=sys.stderr)
sys.exit(1)
except Exception as e:
print(f"An unexpected error occurred: {e}", file=sys.stderr)
sys.exit(1)
finally:
if connection:
print("Disconnecting from MikroTik.")
connection.disconnect()