Files
vps-manager/agent/reporter.py
T

48 lines
1.3 KiB
Python

"""VPS Agent 主入口:采集本机信息并上报到中心服务器
环境变量(建议写入 /etc/vps-agent.env):
VPS_MANAGER_URL 中心地址,如 http://100.89.0.11:8000
VPS_ASSET_ID 本机对应的资产 ID
VPS_AGENT_KEY Agent Key(中心配置了 AGENT_KEY 时必填)
"""
import os
import sys
import httpx
from collector import collect_metrics, collect_security, collect_server_info
def main() -> int:
url = os.environ.get("VPS_MANAGER_URL", "").rstrip("/")
asset_id = os.environ.get("VPS_ASSET_ID", "")
key = os.environ.get("VPS_AGENT_KEY", "")
if not url or not asset_id:
print("错误:需设置 VPS_MANAGER_URL 和 VPS_ASSET_ID")
return 1
payload = {
"asset_id": int(asset_id),
"metrics": collect_metrics(),
"server_info": collect_server_info(),
"security": collect_security(),
}
headers = {"X-Agent-Key": key} if key else {}
try:
resp = httpx.post(
f"{url}/api/agent/report", json=payload, headers=headers, timeout=30
)
print(f"上报完成 HTTP {resp.status_code}: {resp.text}")
resp.raise_for_status()
return 0
except Exception as e: # noqa: BLE001
print(f"上报失败: {e}")
return 1
if __name__ == "__main__":
sys.exit(main())