| Server IP : 3.111.61.48 / Your IP : 216.73.216.67 Web Server : Apache System : Linux ip-10-0-5-176 6.8.0-1057-aws #60~22.04.1-Ubuntu SMP Wed May 27 08:16:59 UTC 2026 x86_64 User : ubuntu ( 1000) PHP Version : 8.2.31 Disable Function : exec,passthru,shell_exec,system MySQL : OFF | cURL : ON | WGET : ON | Perl : ON | Python : OFF | Sudo : ON | Pkexec : ON Directory : /opt/server-monitor/ |
Upload File : |
#!/usr/bin/env python3
import psutil
import requests
import time
import json
import logging
from datetime import datetime, timezone
import os
import sys
# ===============================
# Paths
# ===============================
CONFIG_FILE = "/opt/server-monitor/config.json"
LOG_FILE = "/opt/server-monitor/agent.log"
# Ensure log directory exists
os.makedirs(os.path.dirname(LOG_FILE), exist_ok=True)
# ===============================
# Setup Logging
# ===============================
logging.basicConfig(
filename=LOG_FILE,
level=logging.INFO,
format="%(asctime)s - %(levelname)s - %(message)s"
)
# ===============================
# Load Configuration
# ===============================
def load_config():
try:
with open(CONFIG_FILE, "r") as f:
return json.load(f)
except FileNotFoundError:
logging.error(f"Configuration file {CONFIG_FILE} not found.")
sys.exit(1)
except json.JSONDecodeError:
logging.error(f"Configuration file {CONFIG_FILE} is not valid JSON.")
sys.exit(1)
config = load_config()
API_URL = config.get("api_url")
API_KEY = config.get("api_key")
SERVER_NAME = config.get("server_name", "Unknown-Server")
INTERVAL = config.get("interval", 30)
if not API_URL or not API_KEY:
logging.error("API URL or API KEY not set in configuration.")
sys.exit(1)
# ===============================
# Collect Metrics
# ===============================
def get_metrics():
cpu_usage = psutil.cpu_percent(interval=1)
memory = psutil.virtual_memory()
ram_total = round(memory.total / (1024 ** 2))
ram_used = round(memory.used / (1024 ** 2))
ram_free = round(memory.available / (1024 ** 2))
ram_percent = memory.percent
disk_data = {}
for partition in psutil.disk_partitions():
try:
usage = psutil.disk_usage(partition.mountpoint)
disk_data[partition.mountpoint] = {
"total_gb": round(usage.total / (1024 ** 3), 2),
"used_gb": round(usage.used / (1024 ** 3), 2),
"free_gb": round(usage.free / (1024 ** 3), 2),
"percent": usage.percent
}
except PermissionError:
continue
uptime_seconds = int(time.time() - psutil.boot_time())
return {
"server_name": SERVER_NAME,
"cpu_usage": cpu_usage,
"ram": {
"total_mb": ram_total,
"used_mb": ram_used,
"free_mb": ram_free,
"percent": ram_percent
},
"disk": disk_data,
"uptime_seconds": uptime_seconds,
"timestamp": datetime.now(timezone.utc).isoformat()
}
# ===============================
# Send Metrics
# ===============================
def send_metrics(data):
headers = {
"Authorization": f"Bearer {API_KEY}",
"Content-Type": "application/json"
}
try:
response = requests.post(API_URL, headers=headers, json=data, timeout=10)
if response.status_code == 200:
logging.info("Metrics sent successfully.")
else:
logging.error(f"Server responded with {response.status_code}: {response.text}")
except requests.RequestException as e:
logging.error(f"Error sending metrics: {e}")
# ===============================
# Main Loop
# ===============================
def main():
logging.info("Server Monitor Agent Started")
try:
while True:
metrics = get_metrics()
send_metrics(metrics)
time.sleep(INTERVAL)
except KeyboardInterrupt:
logging.info("Server Monitor Agent stopped manually.")
except Exception as e:
logging.exception(f"Unexpected error: {e}")
if __name__ == "__main__":
main()