115 lines
3.4 KiB
Python
115 lines
3.4 KiB
Python
#!/usr/bin/env python3
|
|
"""
|
|
Script untuk update data MikroTik dari REST API
|
|
"""
|
|
|
|
import requests
|
|
import json
|
|
import os
|
|
from datetime import datetime
|
|
from dotenv import load_dotenv
|
|
|
|
# Load environment
|
|
load_dotenv()
|
|
|
|
# MikroTik credentials
|
|
MIKROTIK_HOST = os.getenv("MIKROTIK_HOST", "192.168.1.1")
|
|
MIKROTIK_PORT = os.getenv("MIKROTIK_PORT", "8728")
|
|
MIKROTIK_USER = os.getenv("MIKROTIK_USER", "admin")
|
|
MIKROTIK_PASSWORD = os.getenv("MIKROTIK_PASSWORD", "password")
|
|
|
|
# API endpoints
|
|
BASE_URL = f"http://{MIKROTIK_HOST}:{MIKROTIK_PORT}/rest"
|
|
AUTH = (MIKROTIK_USER, MIKROTIK_PASSWORD)
|
|
|
|
def fetch_data(endpoint):
|
|
"""Fetch data from MikroTik REST API"""
|
|
url = f"{BASE_URL}/{endpoint}"
|
|
try:
|
|
response = requests.get(url, auth=AUTH, timeout=10)
|
|
response.raise_for_status()
|
|
return response.json()
|
|
except Exception as e:
|
|
print(f"Error fetching {endpoint}: {e}")
|
|
return []
|
|
|
|
def gather_all_info():
|
|
"""Gather all MikroTik information"""
|
|
print("🔍 Gathering MikroTik data...")
|
|
|
|
data = {
|
|
"metadata": {
|
|
"timestamp": datetime.now().isoformat(),
|
|
"source": "MikroTik REST API",
|
|
"host": MIKROTIK_HOST
|
|
},
|
|
"system": {
|
|
"resource": fetch_data("system/resource"),
|
|
"identity": fetch_data("system/identity"),
|
|
"license": fetch_data("system/license"),
|
|
"users": fetch_data("user")
|
|
},
|
|
"interfaces": {
|
|
"interfaces": fetch_data("interface")
|
|
},
|
|
"network": {
|
|
"ip_addresses": fetch_data("ip/address"),
|
|
"routes": fetch_data("ip/route")
|
|
},
|
|
"ppp": {
|
|
"secrets": fetch_data("ppp/secret")
|
|
},
|
|
"logs": fetch_data("log"),
|
|
"hotspot": {
|
|
"active": fetch_data("ip/hotspot/active"),
|
|
"users": fetch_data("ip/hotspot/user")
|
|
}
|
|
}
|
|
|
|
# Calculate statistics
|
|
if data["interfaces"]["interfaces"]:
|
|
total = len(data["interfaces"]["interfaces"])
|
|
running = sum(1 for i in data["interfaces"]["interfaces"] if i.get("running") == True)
|
|
data["interfaces"]["statistics"] = {
|
|
"total": total,
|
|
"running": running,
|
|
"not_running": total - running
|
|
}
|
|
|
|
if data["ppp"]["secrets"]:
|
|
total = len(data["ppp"]["secrets"])
|
|
enabled = sum(1 for s in data["ppp"]["secrets"] if s.get("disabled") == False)
|
|
data["ppp"]["statistics"] = {
|
|
"total_secrets": total,
|
|
"enabled_secrets": enabled
|
|
}
|
|
|
|
print(f"✅ Data gathered: {len(str(data))} bytes")
|
|
return data
|
|
|
|
def save_data(data, filename="data/mikrotik_mcp_data.json"):
|
|
"""Save data to JSON file"""
|
|
try:
|
|
with open(filename, 'w', encoding='utf-8') as f:
|
|
json.dump(data, f, indent=2, ensure_ascii=False)
|
|
print(f"💾 Data saved to {filename}")
|
|
return True
|
|
except Exception as e:
|
|
print(f"Error saving data: {e}")
|
|
return False
|
|
|
|
if __name__ == "__main__":
|
|
print("🔄 Updating MikroTik MCP data...")
|
|
|
|
# Check credentials
|
|
if not all([MIKROTIK_HOST, MIKROTIK_USER, MIKROTIK_PASSWORD]):
|
|
print("⚠️ MikroTik credentials not set in .env file")
|
|
print(" Using existing data file only")
|
|
else:
|
|
data = gather_all_info()
|
|
if data:
|
|
save_data(data)
|
|
print("✅ Update completed successfully")
|
|
else:
|
|
print("❌ Failed to gather data")
|