Skip to content

Instantly share code, notes, and snippets.

@remotephone
Created June 9, 2024 20:19
Show Gist options
  • Save remotephone/b790328716cac90116bdd8d5e69112fe to your computer and use it in GitHub Desktop.
Save remotephone/b790328716cac90116bdd8d5e69112fe to your computer and use it in GitHub Desktop.
Uptime Kuma - Restore a back up via the API
import json
import os
from uptime_kuma_api import UptimeKumaApi, MonitorType
def load_notification_params(data):
"""
Load notification parameters from data and add monitors to Uptime Kuma.
This function iterates over a list of dictionaries, each representing a monitor's configuration,
and adds them to Uptime Kuma using its API. It filters out certain keys from each dictionary
before adding the monitor.
"""
# Initialize the Uptime Kuma API client with the URL from environment variables
api = UptimeKumaApi(os.getenv('UPTIME_KUMA_URL'))
try:
# Login to the API using credentials from environment variables
api.login(os.getenv('UPTIME_KUMA_USER'), os.getenv('UPTIME_KUMA_PASSWORD'))
for entry in data:
# Filter out unwanted keys from the monitor configuration
params = {key: value for key, value in entry.items() if key not in ["id", "description", "active", "forceInactive", "dns_last_result", "tags", "maintenance", "screenshot", "pushToken", "includeSensitiveData"]}
# If the monitor type is specified, set it to HTTP, otherwise ping
if "type" in params:
if params["type"] == "http":
params["type"] = MonitorType.HTTP
else:
params["type"] = MonitorType.PING
# Debugging: Print current notifications to console
print(api.get_notifications())
# Add the monitor with the filtered parameters
api.add_monitor(**params)
except Exception as e:
# Handle any exceptions that occur during the API calls
print(f"Failed to add monitor: {e}")
finally:
# Ensure the API client disconnects from the server even if an error occurs
api.disconnect()
if __name__ == "__main__":
try:
# Load monitor configurations from a JSON file
# You can reate this from exporting a backup.
with open("backup.json", "r") as file:
data = json.load(file)
load_notification_params(data)
except FileNotFoundError:
# Handle the case where the backup.json file does not exist
print("backup.json file not found.")
except json.JSONDecodeError:
# Handle errors in decoding the JSON file
print("Error decoding JSON from backup.json.")
@remotephone
Copy link
Author

Pretty sure this works as is. Banged it up to insert the records from a backup back into Uptime Kuma. I did a backup, didn't notice the note it shouldn't work, and then removed everything only to realize I couldn't restore. This is hacky but works.

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment