Systems and Operations

Using the Management API: Start with Read-Only Queries

Compiled by the VPSMap Editorial Team · Updated 2026-09-26 · 20-minute read · Plain-Text Version

When managing VPS instances across multiple nodes and regions, inspecting them individually through a web panel is inefficient and difficult to integrate with Prometheus, Zabbix, or custom operations dashboards. Providers with infrastructure management APIs let administrators retrieve instance status in batches, monitor bandwidth usage, and perform emergency lifecycle operations programmatically.

The underlying management API connects directly to the host's Hypervisor. Management credentials generally have privileges equal to or greater than the operating system's root privileges, including forced power-off, restoring disk snapshots, and reinstalling the entire system. The first rule for integrating a management API into an automation pipeline isAlways Start with a Read-Only Query,在数据采集、鉴权传输与凭据 Storage 的全流程中建立最小权限与防御性编码规范。


1. The Role of Management APIs and Differences in Control-Plane Security#

Before integrating automation, clearly distinguish betweenApplication-Layer Interface、Operating System ManagementandHost-Level Infrastructure Management API the boundaries of authority and responsibility:

  • Operating System-Level Management: interact with the instance's Linux system through SSH or configuration management tools such as Ansible.
  • Underlying Management API: communicates directly with the control plane of the provider's virtualization platform. Even if the instance's operating system deadlocks, its kernel crashes, or its network interface is accidentally disabled, the underlying API can forcibly control the instance's hardware state.

Providers differ significantly in their design philosophies for the operations control plane:

  • BandwagonHost( BandwagonHost ) uses an instance-level REST API architecture built on its proprietary KiwiVM system. Each VPS has its own Virtual Environment ID (VEID) and API Key. Lightweight HTTPS requests allow direct instance lifecycle operations and metric queries. This design is well suited to small automation scripts and independent monitoring, but a leaked instance API Key also lets an attacker perform destructive actions on that instance at the host level.
  • DMIT places greater emphasis on a centralized platform console and infrastructure security isolation. DMIT disables remote root password login, using a centralized SSH key repository and instance Access authorization. Console operations rely on the platform account's multi-factor authentication (MFA), while emergency troubleshooting uses the browser-based VNC/Console.

BandwagonHost's operations system uses several mutually independent password systems:

  1. Provider Client Area Password(for checkout, invoice payments, and support tickets);
  2. KiwiVM Panel Administration Password(用于 Web 端虚拟化管理);
  3. Operating System root Password(for interaction within the operating system);
  4. KiwiVM API Key(for programmatic communication).

API Keys Are Not Subject to Web Login CAPTCHAs or Two-Factor Authentication (2FA); Requests Work When a Valid Key Reaches the Endpoint. Treat Them as Highly Sensitive Credentials and Protect Them Carefully in Scripts.


2. KiwiVM API Read-Only Interface Specifications and Field Descriptions#

In BandwagonHost's KiwiVM control panel, open the target instance and find in the sidebar API menu. This page displays the current instance's two core credentials:

  • VEID: The instance's unique numeric identifier within the virtualization system.
  • API Key: a long hexadecimal key string generated by the system.

The hostname for API communication is api.64clouds.com, and all communication must be encrypted with TLS (HTTPS).

Comparison of Core Read-Only Endpoints#

Interface Name请求 Type Resource ConsumptionTypical Response Fields and Their Uses
/v1/getServiceInfo轻量只读Extremely Low (Reads Cached Metadata)主机名、IP 列表、 Operating system 模板、 Plan Specification 、 Memory /磁盘配额、计费周期与流量 Reset 日、month度总流量配额
/v1/getLiveServiceInfoReal-Time ProbingMedium (real-time direct retrieval)Physical Host Node, Real-Time Memory Usage (Used/Free/Cache), SWAP Status, Load Average, and Cumulative Network Packets Sent/Received
/v1/getUsageGraphs数据图表LowHistorical Monitoring Chart URLs or Underlying Time Series for CPU, Memory, and Network I/O

High-Risk Write API List (Do Not Use for Routine Checks)#

When designing automated inspection programs, strictly filter out the following destructive endpoints:

  • restart / start / stop / kill: Power control.
  • reinstallOS: OS reinstallation (erases all disk data).
  • resetRootPassword: Reset the operating system administrator password.
  • snapshot/*: Create or roll back snapshots.

Engineering Guidelines: never hard-code method names that grant write access or change state into routine monitoring agents or status display pages. This prevents configuration errors or unintended control flow from causing accidental shutdowns.


3. 鉴权参数传输的安全加固#

KiwiVM 文档中常常以简易的 HTTP GET example 展示接口用法(如 https://api.64clouds.com/v1/getServiceInfo?veid=...&api_key=...)。Never Transmit Sensitive Credentials with GET in Any Production or Automation Script。

Why POST Is Required#

  1. 规避日志留痕: the URL of a GET request appears in client-side proxy logs and the operating system's process tree (such as curl Command-Line Arguments Are ps aux intercepted), recorded in plaintext in browser history and on intermediate network devices.
  2. Prevent Accidental Referrer Leakage: If invoked through a web frontend or internal debugging tool, the URL can easily be exposed through HTTP Referer header to leak to external third-party static resources.
  3. Parameter Payload Encapsulation: use a POST request to send veid and api_key place it in the request Body and use HTTPS end-to-end encryption to ensure credentials are transmitted only after a TLS session has been established at the network layer.

4. Production-Grade Read-Only Queries with Python#

The following script demonstrates how to build a robust, secure, read-only query client using the Python standard library. The code follows these security and engineering guidelines:

  • No external third-party libraries are required, reducing software supply-chain security risks;
  • Retrieve credentials securely from operating system environment variables or interactive input; never hardcode them in source;
  • Strictly validate the endpoint URL, domain legitimacy, and path in advance;
  • Only call getLiveServiceInfo retrieve runtime status and traffic data, parse the raw byte values, and convert units precisely;
  • Includes Timeout Handling and API Error-Code Validation.
python
#!/usr/bin/env python3
"""
KiwiVM API 只读健康与流量巡检工具
遵循最小权限原则:仅调用 getLiveServiceInfo 端点。
"""

import getpass
import json
import os
import sys
import urllib.error
import urllib.parse
import urllib.request
from typing import Any, Dict


EXPECTED_HOST = "api.64clouds.com"
ALLOWED_PATH = "/v1/getLiveServiceInfo"


def get_credentials() -> tuple[str, str]:
    """
    优先从环境变量读取凭据,若不存在则提示安全交互输入。
    避免密钥在命令行历史中留痕。
    """
    veid = os.environ.get("KIWIVM_VEID", "").strip()
    api_key = os.environ.get("KIWIVM_API_KEY", "").strip()

    if not veid:
        veid = input("请输入 VEID: ").strip()
    if not api_key:
        api_key = getpass.getpass("请输入 API Key (输入隐藏): ").strip()

    if not veid.isdigit():
        sys.exit("错误: VEID 必须是纯数字编号。")
    if not api_key:
        sys.exit("错误: API Key 不能为空。")

    return veid, api_key


def format_bytes(num_bytes: int) -> str:
    """将原始字节数转换为易读的 GiB/MiB 格式"""
    gib = num_bytes / (1024**3)
    if gib >= 1.0:
        return f"{gib:.2f} GiB"
    mib = num_bytes / (1024**2)
    return f"{mib:.2f} MiB"


def query_kiwivm_live_info(veid: str, api_key: str) -> Dict[str, Any]:
    """构建安全的 POST 请求并解析返回数据"""
    endpoint = f"https://{EXPECTED_HOST}{ALLOWED_PATH}"
    
    # 严格校验 URL 架构
    parsed_url = urllib.parse.urlsplit(endpoint)
    if parsed_url.scheme != "https" or parsed_url.netloc != EXPECTED_HOST:
        sys.exit(f"安全阻断: 非法的请求目标 {endpoint}")
    if parsed_url.path != ALLOWED_PATH or parsed_url.query:
        sys.exit("安全阻断: 只允许访问指定的只读端点,严禁附带 Query 参数。")

    # 载荷编码(POST 表单)
    payload = urllib.parse.urlencode({"veid": veid, "api_key": api_key}).encode("utf-8")
    
    headers = {
        "User-Agent": "VPSMap-Ops-Monitor/1.0",
        "Content-Type": "application/x-www-form-urlencoded",
    }

    req = urllib.request.Request(endpoint, data=payload, headers=headers, method="POST")

    try:
        with urllib.request.urlopen(req, timeout=15) as response:
            if response.status != 200:
                sys.exit(f"HTTP 响应异常: 状态码 {response.status}")
            raw_body = response.read().decode("utf-8")
            data = json.loads(raw_body)
    except urllib.error.HTTPError as err:
        sys.exit(f"HTTP 请求失败: {err.code} {err.reason}")
    except urllib.error.URLError as err:
        sys.exit(f"网络连接错误: {err.reason}")
    except json.JSONDecodeError:
        sys.exit("响应内容不是有效的 JSON 格式。")

    if data.get("error") != 0:
        err_msg = data.get("message", "未知错误")
        sys.exit(f"KiwiVM 接口调用失败 (Error Code {data.get('error')}): {err_msg}")

    return data


def display_metrics(data: Dict[str, Any]) -> None:
    """过滤敏感网络拓扑,仅输出运维关键指标"""
    print("\n" + "=" * 48)
    print("      VPS 运行与资源健康度报告 (只读)")
    print("=" * 48)
    
    vm_type = data.get("vm_type", "N/A")
    load_avg = data.get("load_average", "N/A")
    print(f"虚拟化平台架构 : {vm_type}")
    print(f"系统当前平均负载: {load_avg}")

    # 内存计算 (KiwiVM 报告通常以字节为单位)
    mem_total = data.get("plan_ram", 0)
    mem_used = data.get("mem_available_bytes", 0)  # 注意各版本字段差异
    if mem_total:
        print(f"配额分配内存   : {format_bytes(mem_total)}")

    # 流量与带宽核算
    data_counter = data.get("data_counter", 0)
    plan_monthly_data = data.get("plan_monthly_data", 0)
    data_reset_day = data.get("data_next_reset", "N/A")

    if plan_monthly_data > 0:
        usage_ratio = (data_counter / plan_monthly_data) * 100
        print(f"本月累计流量   : {format_bytes(data_counter)} / {format_bytes(plan_monthly_data)} ({usage_ratio:.1f}%)")
    else:
        print(f"本月累计流量   : {format_bytes(data_counter)}")

    print(f"下次流量重置时间: {data_reset_day}")
    print("=" * 48 + "\n")


if __name__ == "__main__":
    v_id, a_key = get_credentials()
    result = query_kiwivm_live_info(v_id, a_key)
    display_metrics(result)

5. Engineering Guidelines for Automated Checks and Monitoring Integration#

When integrating the read-only queries above into Cron jobs or microservice collectors, follow these operational engineering constraints:

Control Polling Frequency and Failure Backoff#

  1. Do Not Poll the Infrastructure API at High Frequency: the KiwiVM API runs on the host cluster's management frontend. Frequent requests (such as polling every 5 seconds) can trigger anti-bot protection and Rate Limits, and may also temporarily block API access from your current IP address.
  2. Set Sensible Monitoring Intervals: Polling traffic allowances and monthly usage every 15 to 30 minutes is generally sufficient; instance health checks should run every 3 to 5 minutes. For second-level monitoring of detailed internal load, install Node Exporter or Telegraf inside the system instead of relying on the host API.
  3. Implement Retries with Exponential Backoff:当接口返回 Networking 超时或 HTTP 5xx 错误时,程序应等待 $2^n$ 秒后再做有限次(如最多 3 次) Retry ,避免因 Networking 抖动造成 cluster 雪崩式重连。

State Caching and Metric Persistence#

When writing to a monitoring time-series database, such as InfluxDB or Prometheus Pushgateway, the program should maintain two separate sets of timestamps:

  • probe_timestamp: the actual time this API probe was initiated.
  • data_timestamp: the timestamp of the actual business-data update in the API response.

If a request encounters a network error or interface timeout, the alert should explicitly say “Management API communication interrupted,”Strictly Prohibitedset the traffic value directly to zero or mark the previous successful cached value as the latest sample, to prevent false outage or capacity alerts on the monitoring dashboard.

Traffic Reset Cycles and Unit Conversion Pitfalls#

  • 计费 Reset 日差异:KiwiVM 的流量 Reset 周期与账单日严格对齐,而非自然month的第一天。例如某 instance 于 15 日开通,其流量计数器通常在每month 15 日自动 Reset 归零。 compute month度消耗率时切勿直接套用自然日天数。
  • Decimal versus Binary Conversion: Providers usually express plan specifications using $1\text{ GB} = 1000^3\text{ Bytes}$ or $1\text{ GiB} = 1024^3\text{ Bytes}$. When calculating data_counter and plan_monthly_data as a percentage, always divide the raw byte values to avoid false alerts caused by rounding errors.

6. 凭据全生命周期管理:轮转、废除与权限隔离#

In long-term instance operations, secure API Key management directly determines the infrastructure's security baseline:

Beware of “Export All Services and Private API Keys”#

The KiwiVM panel provides one-click export of the VEIDs and corresponding API Keys for all instances in the current account, usually in CSV format.

  • Risk Level: Highest (catastrophic). This file is effectively a master infrastructure key to every VPS under the BandwagonHost account.
  • Operating Guidelines: Never casually download this file unless performing centralized enterprise asset archiving. If downloading is necessary, store it on a GPG-encrypted partition. Never send it through instant messaging or place it in cloud storage or a public project directory.

凭据轮转与废除流程#

若发生以下情况,必须立即执行 API Key 轮换:

  1. The Key Was Accidentally Committed to a Git Repository, Even If the Commit Was Later Reverted;
  2. The operations staff who maintained the script leave or hand over their responsibilities;
  3. The Instance Has Triggered an External Security Alert or Is Suspected of Being Compromised.

Standard Rotation Procedure:

  1. Log into the target instance's KiwiVM web panel and open the API menu;
  2. Click Regenerate API Key(regenerate the key), and the panel immediately invalidates the old key;
  3. 将新生成的密钥 Updated 至本地受保护的环境变量或密钥管理服务(如 HashiCorp Vault);
  4. Run the Read-Only Test Script in Section 4 to Verify That the New Key Works and Returns a Normal Response;
  5. 确认自动化流水线与监控代理恢复采集。

建立只读代理隔离层#

In more complex team environments or public-facing display scenarios, it is not advisable to give every monitoring frontend or administrator direct access to the underlying veid and api_key。

The recommended architecture deploys a lightweight layer on the internal network:中间代理程序:

  • The intermediary proxy stores the core API Key and requests only read-only KiwiVM endpoints;
  • The proxy exposes a custom, allowlist-filtered REST interface externally, returning only sanitized traffic percentages and system status;
  • Completely sever the physical path through which the presentation layer can send write commands, such as rebooting or reinstalling, to the host machine.

Starting with read-only queries and applying strict credential storage and transmission requirements to every request lets teams enjoy the efficiency of automated operations while minimizing the risk of infrastructure takeover.