Monitoring – Api

This Flask program creates a small web service that exposes system command outputs through HTTP endpoints, primarily for users who need a secure way to remotely retrieve system information (like CPU usage, memory status, and disk usage) from a server. Here’s a breakdown of what the program does and how users can interact with it.

Program Description

  1. Authentication Setup:
    • The service requires a token for authorization. AUTH_TOKEN is defined as "your_secret_token", and each incoming request must include this token in the header to be processed.
  2. Command Definition:
    • The COMMANDS list specifies the system commands available for execution through this API. Each item is a tuple:
      • The first item is the endpoint name (e.g., "top", "free", "df").
      • The second item is the command to execute (e.g., ["top", "-b", "-n", "1"] for a snapshot of active processes).
  3. Authorization Check:
    • The check_token function verifies if the request has the correct Authorization header in the format Bearer your_secret_token.
    • If the token is incorrect or missing, it returns a 401 Unauthorized response.
  4. Command Execution:
    • handle_command is a route handler function that executes the specified system command using subprocess.check_output, returning the command’s output in plain text.
    • Errors during command execution are caught, and a 500 Internal Server Error response is returned with the error message.
  5. Dynamic Endpoint Creation:
    • The program iterates over COMMANDS and creates a route for each command using Flask’s add_url_rule function. Each command in COMMANDS gets its own endpoint (e.g., /top, /free, /df).
    • Each endpoint is mapped to a POST request, allowing clients to retrieve system data securely.
  6. Running the App:
    • When executed, the app runs on host 0.0.0.0 and listens on port 5000.

Usage Instructions

To use this service, a user would:

  1. Set Up the Token:
    • Replace "your_secret_token" in AUTH_TOKEN with a secure, complex token.
  2. Make a Request:
    • Send a POST request to any of the defined endpoints (e.g., /top, /free, /df).Include an Authorization header with the value Bearer your_secret_token (replace your_secret_token with the actual token used in the app).
    For example, to get a snapshot of CPU processes:

    curl -X POST http://<server_ip>:5000/top -H "Authorization: Bearer your_secret_token"

    Each endpoint provides information about the server:
    • /top: Retrieves a snapshot of active processes.
    • /free: Shows memory usage.
    • /df: Displays disk usage.

Security Note

This service should only be exposed in a secure, trusted network since it allows remote command execution, even though it uses basic token-based authentication. For better security, consider using HTTPS and more complex authentication mechanisms.