Add Uptime Kuma API management tooling

Implements programmatic monitor management via Socket.IO API:
- manage_monitors.py: CLI script for CRUD operations on monitors
- API.md: Comprehensive API usage documentation
- SETUP.md: Step-by-step setup and verification guide

Key features:
- Supports API key and username/password authentication
- List, add, update, delete monitors via CLI
- SSL verification disabled for self-signed certificates
- Monitor types: HTTP, TCP, ping, DNS, docker
This commit is contained in:
2026-02-08 19:59:43 +00:00
parent f46d493ca2
commit 3a990fc686
3 changed files with 562 additions and 0 deletions
+217
View File
@@ -0,0 +1,217 @@
# Uptime Kuma API Documentation
## Overview
Uptime Kuma provides a Socket.IO-based API for programmatic monitor management. The REST API does **not** support monitor CRUD operations - you must use the Socket.IO API via the `uptime-kuma-api` Python package.
## Setup
### 1. Install Python Package
```bash
pip3 install uptime-kuma-api
```
**Requirements:** Python 3.7+
### 2. Create API Credentials
#### Option A: API Key (Recommended)
1. Access Uptime Kuma web UI: https://uptime.kolpacksoftware.com
2. Navigate to **Settings → API Keys**
3. Click **Generate** to create a new API key
4. Set a descriptive name (e.g., "CLI Management")
5. Set expiry (or "Never expire")
6. **Copy the key immediately** (shown only once)
7. Store securely in environment variable:
```bash
export UPTIME_KUMA_API_KEY="uk1_your_api_key_here"
```
**Important:** Once the first API key is created, basic authentication is permanently disabled for supported endpoints.
#### Option B: Username/Password
Use existing Uptime Kuma login credentials:
```bash
export UPTIME_KUMA_USERNAME="your_username"
export UPTIME_KUMA_PASSWORD="your_password"
```
### 3. Make Script Executable
```bash
chmod +x /home/poprhythm/docker-infrastructure/uptime-kuma/manage_monitors.py
```
## Usage
### List All Monitors
```bash
./manage_monitors.py list
```
Output:
```
ID Name Type URL
------------------------------------------------------------------------------------------------
1 Example Service http https://example.com
2 Database Health tcp 192.168.1.100:5432
3 Gateway Ping ping 192.168.1.1
```
### Add a Monitor
**HTTP/HTTPS Monitor:**
```bash
./manage_monitors.py add --name "My Service" --url "https://myservice.com" --type http
```
**TCP Port Monitor:**
```bash
./manage_monitors.py add --name "PostgreSQL" --url "192.168.1.100:5432" --type tcp
```
**Ping Monitor:**
```bash
./manage_monitors.py add --name "Router" --url "192.168.1.1" --type ping
```
**Custom Interval (default is 60 seconds):**
```bash
./manage_monitors.py add --name "Critical Service" --url "https://critical.com" --interval 30
```
### Update a Monitor
```bash
# Update name
./manage_monitors.py update --id 123 --name "New Name"
# Update URL
./manage_monitors.py update --id 123 --url "https://newurl.com"
# Update interval
./manage_monitors.py update --id 123 --interval 300
# Update multiple fields
./manage_monitors.py update --id 123 --name "Updated" --url "https://updated.com" --interval 120
```
### Delete a Monitor
```bash
./manage_monitors.py delete --id 123
```
## Monitor Types
| Type | Description | URL Format |
|------|-------------|------------|
| `http` | HTTP/HTTPS endpoint | `https://example.com` or `http://example.com` |
| `tcp` | TCP port check | `hostname:port` or `ip:port` |
| `ping` | ICMP ping | `hostname` or `ip` |
| `dns` | DNS resolution | `example.com` |
| `docker` | Docker container | Container name or ID |
## Authentication
The script checks for credentials in the following order:
1. `UPTIME_KUMA_API_KEY` environment variable (preferred)
2. `UPTIME_KUMA_USERNAME` and `UPTIME_KUMA_PASSWORD` environment variables
To persist credentials, add to your shell profile (`~/.bashrc` or `~/.zshrc`):
```bash
export UPTIME_KUMA_API_KEY="uk1_your_api_key_here"
```
## Troubleshooting
### "No credentials provided" Error
**Problem:** Script cannot find API credentials.
**Solution:** Set environment variables before running:
```bash
export UPTIME_KUMA_API_KEY="uk1_your_key"
./manage_monitors.py list
```
### Connection Refused
**Problem:** Cannot connect to Uptime Kuma instance.
**Solution:**
1. Verify service is running: `docker ps | grep uptime-kuma`
2. Check URL in script matches web UI access
3. Ensure SSL certificate is valid (or use `verify=False` in script for self-signed)
### "Monitor not found" Error
**Problem:** Monitor ID doesn't exist.
**Solution:** Run `./manage_monitors.py list` to see all valid monitor IDs.
### Import Error: uptime_kuma_api
**Problem:** Python package not installed.
**Solution:**
```bash
pip3 install uptime-kuma-api
# Or with sudo if needed:
sudo pip3 install uptime-kuma-api
```
## Advanced Usage
### Using as a Python Module
```python
from uptime_kuma_api import UptimeKumaApi, MonitorType
# Connect
api = UptimeKumaApi("https://uptime.kolpacksoftware.com")
api.login_by_token("uk1_your_api_key")
# Get all monitors
monitors = api.get_monitors()
# Add monitor
api.add_monitor(
type=MonitorType.HTTP,
name="My Service",
url="https://example.com",
interval=60
)
# Edit monitor
monitor = api.get_monitor(1)
monitor['name'] = "Updated Name"
api.edit_monitor(1, **monitor)
# Delete monitor
api.delete_monitor(1)
# Always disconnect
api.disconnect()
```
## References
- [Uptime Kuma API Keys Documentation](https://github.com/louislam/uptime-kuma/wiki/API-Keys)
- [Uptime Kuma API Documentation](https://github.com/louislam/uptime-kuma/wiki/API-Documentation)
- [uptime-kuma-api Python Package](https://github.com/lucasheld/uptime-kuma-api)
- [uptime-kuma-api Documentation](https://uptime-kuma-api.readthedocs.io/)
## Web UI Access
- **URL:** https://uptime.kolpacksoftware.com
- **Settings:** Click gear icon → API Keys
- **Monitor Management:** Dashboard → Add/Edit monitors via UI
+189
View File
@@ -0,0 +1,189 @@
# Uptime Kuma API Setup Guide
## Prerequisites Installation
The management script requires Python 3.7+ and the `uptime-kuma-api` package.
### Step 1: Install pip (if not already installed)
```bash
sudo apt update
sudo apt install python3-pip -y
```
### Step 2: Install uptime-kuma-api Package
```bash
pip3 install uptime-kuma-api
# Or if pip3 is not in PATH:
python3 -m pip install uptime-kuma-api
```
**Verify installation:**
```bash
python3 -c "import uptime_kuma_api; print('Package installed successfully')"
```
## Authentication Setup
You must configure API credentials before using the management script.
### Option A: API Key (Recommended)
1. **Access Uptime Kuma web UI:**
- URL: https://uptime.kolpacksoftware.com
- Log in with your credentials
2. **Generate API Key:**
- Click the gear icon (Settings)
- Navigate to **API Keys** section
- Click **Generate**
- Set a descriptive name (e.g., "CLI Management")
- Set expiry (or "Never expire")
- **IMPORTANT:** Copy the key immediately - it's only shown once!
3. **Configure Environment Variable:**
Add to `~/.bashrc` or `~/.zshrc`:
```bash
export UPTIME_KUMA_API_KEY="uk1_your_api_key_here"
```
Or set temporarily:
```bash
export UPTIME_KUMA_API_KEY="uk1_your_api_key_here"
```
Apply changes:
```bash
source ~/.bashrc # or source ~/.zshrc
```
### Option B: Username/Password
```bash
export UPTIME_KUMA_USERNAME="your_username"
export UPTIME_KUMA_PASSWORD="your_password"
```
**Note:** Once you create the first API key, username/password authentication is permanently disabled for API endpoints. API keys are more secure and recommended.
## Verification
### Test 1: Check Script is Executable
```bash
cd /home/poprhythm/docker-infrastructure
ls -l uptime-kuma/manage_monitors.py
# Should show -rwxr-xr-x (executable permissions)
```
### Test 2: List Existing Monitors
```bash
cd /home/poprhythm/docker-infrastructure
./uptime-kuma/manage_monitors.py list
```
**Expected output:**
```
ID Name Type URL
------------------------------------------------------------------------------------------------
1 Example Service http https://example.com
...
```
### Test 3: Add a Test Monitor
```bash
./uptime-kuma/manage_monitors.py add --name "Test Monitor" --url "https://httpbin.org/status/200" --type http --interval 300
```
### Test 4: Delete the Test Monitor
```bash
# Find the ID from the list command
./uptime-kuma/manage_monitors.py list
# Delete it (replace 999 with actual ID)
./uptime-kuma/manage_monitors.py delete --id 999
```
### Test 5: Verify in Web UI
1. Access https://uptime.kolpacksoftware.com
2. Check that the test monitor was created and deleted
3. Verify existing monitors match the CLI list output
## Troubleshooting
### "No credentials provided" Error
**Cause:** Environment variables not set.
**Fix:**
```bash
# Check current environment
echo $UPTIME_KUMA_API_KEY
# If empty, set it:
export UPTIME_KUMA_API_KEY="uk1_your_key"
```
### "ModuleNotFoundError: No module named 'uptime_kuma_api'"
**Cause:** Package not installed or installed for wrong Python version.
**Fix:**
```bash
# Install for your Python 3
python3 -m pip install --user uptime-kuma-api
# Or system-wide (requires sudo)
sudo python3 -m pip install uptime-kuma-api
```
### Connection Errors
**Cause:** Uptime Kuma service not running or URL incorrect.
**Fix:**
```bash
# Check service is running
docker ps | grep uptime-kuma
# Test web UI access
curl -k https://uptime.kolpacksoftware.com
# If needed, start the service
cd /home/poprhythm/docker-infrastructure/uptime-kuma
docker compose up -d
```
### SSL Certificate Errors
**Cause:** Self-signed certificate or certificate validation issues.
**Fix:** If using self-signed certificates, you may need to modify the script to disable SSL verification (not recommended for production).
## Next Steps
1. ✅ Install prerequisites (`python3-pip`, `uptime-kuma-api`)
2. ✅ Create API key in web UI
3. ✅ Set environment variable
4. ✅ Test with `./manage_monitors.py list`
5. 📖 Read [API.md](API.md) for full usage documentation
## Quick Reference
```bash
# Set credentials (add to ~/.bashrc for persistence)
export UPTIME_KUMA_API_KEY="uk1_your_api_key"
# Common commands
cd /home/poprhythm/docker-infrastructure
./uptime-kuma/manage_monitors.py list
./uptime-kuma/manage_monitors.py add --name "Service" --url "https://example.com"
./uptime-kuma/manage_monitors.py update --id 123 --interval 120
./uptime-kuma/manage_monitors.py delete --id 123
```
+156
View File
@@ -0,0 +1,156 @@
#!/usr/bin/env python3
"""
Uptime Kuma Monitor Management Script
Usage examples:
./manage_monitors.py list
./manage_monitors.py add --name "My Service" --url "https://example.com" --type http
./manage_monitors.py delete --id 123
./manage_monitors.py update --id 123 --name "Updated Name"
"""
import argparse
import sys
import os
from uptime_kuma_api import UptimeKumaApi, MonitorType
# Configuration
UPTIME_KUMA_URL = "https://uptime.kolpacksoftware.com"
# Set one of these (or use environment variables):
API_KEY = os.getenv('UPTIME_KUMA_API_KEY') # Set via UPTIME_KUMA_API_KEY env var
USERNAME = os.getenv('UPTIME_KUMA_USERNAME') # Or use UPTIME_KUMA_USERNAME
PASSWORD = os.getenv('UPTIME_KUMA_PASSWORD') # And UPTIME_KUMA_PASSWORD
def connect():
"""Connect to Uptime Kuma API"""
# Disable SSL verification for self-signed certificates
api = UptimeKumaApi(UPTIME_KUMA_URL, ssl_verify=False)
if API_KEY:
# API key authentication (preferred)
api.login_by_token(API_KEY)
elif USERNAME and PASSWORD:
# Username/password authentication
api.login(USERNAME, PASSWORD)
else:
print("Error: No credentials provided. Set UPTIME_KUMA_API_KEY or UPTIME_KUMA_USERNAME/PASSWORD environment variables.")
sys.exit(1)
return api
def list_monitors(api):
"""List all monitors"""
monitors = api.get_monitors()
if not monitors:
print("No monitors found")
return
print(f"{'ID':<6} {'Name':<30} {'Type':<10} {'URL/Hostname':<50}")
print("-" * 96)
for monitor in monitors:
url = monitor.get('url') or monitor.get('hostname', 'N/A')
if url is None:
url = 'N/A'
print(f"{monitor['id']:<6} {monitor['name']:<30} {str(monitor['type']):<10} {url:<50}")
def add_monitor(api, name, url, monitor_type='http', interval=60, ignore_tls=False):
"""Add a new monitor"""
type_map = {
'http': MonitorType.HTTP,
'https': MonitorType.HTTP,
'tcp': MonitorType.PORT,
'ping': MonitorType.PING,
'dns': MonitorType.DNS,
'docker': MonitorType.DOCKER,
}
monitor_type_value = type_map.get(monitor_type.lower(), MonitorType.HTTP)
# Different monitor types use different parameters
if monitor_type.lower() == 'ping':
result = api.add_monitor(
type=monitor_type_value,
name=name,
hostname=url,
interval=interval
)
else:
kwargs = {
'type': monitor_type_value,
'name': name,
'url': url,
'interval': interval
}
# Add SSL ignore for HTTPS URLs
if ignore_tls or (url.startswith('https://') and monitor_type.lower() in ['http', 'https']):
kwargs['ignoreTls'] = True
result = api.add_monitor(**kwargs)
print(f"Monitor added successfully: ID {result['monitorID']}")
def delete_monitor(api, monitor_id):
"""Delete a monitor"""
api.delete_monitor(monitor_id)
print(f"Monitor {monitor_id} deleted successfully")
def update_monitor(api, monitor_id, **kwargs):
"""Update a monitor"""
# Get existing monitor
monitor = api.get_monitor(monitor_id)
# Update fields
for key, value in kwargs.items():
if value is not None:
monitor[key] = value
api.edit_monitor(monitor_id, **monitor)
print(f"Monitor {monitor_id} updated successfully")
def main():
parser = argparse.ArgumentParser(description='Manage Uptime Kuma monitors')
subparsers = parser.add_subparsers(dest='command', help='Commands')
# List command
subparsers.add_parser('list', help='List all monitors')
# Add command
add_parser = subparsers.add_parser('add', help='Add a monitor')
add_parser.add_argument('--name', required=True, help='Monitor name')
add_parser.add_argument('--url', required=True, help='URL to monitor')
add_parser.add_argument('--type', default='http', help='Monitor type (http, tcp, ping, dns, docker)')
add_parser.add_argument('--interval', type=int, default=60, help='Check interval in seconds')
add_parser.add_argument('--ignore-tls', action='store_true', help='Ignore TLS/SSL certificate errors')
# Delete command
delete_parser = subparsers.add_parser('delete', help='Delete a monitor')
delete_parser.add_argument('--id', type=int, required=True, help='Monitor ID')
# Update command
update_parser = subparsers.add_parser('update', help='Update a monitor')
update_parser.add_argument('--id', type=int, required=True, help='Monitor ID')
update_parser.add_argument('--name', help='New name')
update_parser.add_argument('--url', help='New URL')
update_parser.add_argument('--interval', type=int, help='New interval')
args = parser.parse_args()
if not args.command:
parser.print_help()
sys.exit(1)
# Connect to API
api = connect()
try:
if args.command == 'list':
list_monitors(api)
elif args.command == 'add':
ignore_tls = getattr(args, 'ignore_tls', False)
add_monitor(api, args.name, args.url, args.type, args.interval, ignore_tls)
elif args.command == 'delete':
delete_monitor(api, args.id)
elif args.command == 'update':
update_monitor(api, args.id, name=args.name, url=args.url, interval=args.interval)
finally:
api.disconnect()
if __name__ == '__main__':
main()