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
- Authentication Setup:
- The service requires a token for authorization.
AUTH_TOKENis defined as"your_secret_token", and each incoming request must include this token in the header to be processed.
- The service requires a token for authorization.
- Command Definition:
- The
COMMANDSlist 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).
- The first item is the endpoint name (e.g.,
- The
- Authorization Check:
- The
check_tokenfunction verifies if the request has the correctAuthorizationheader in the formatBearer your_secret_token. - If the token is incorrect or missing, it returns a
401 Unauthorizedresponse.
- The
- Command Execution:
handle_commandis a route handler function that executes the specified system command usingsubprocess.check_output, returning the command’s output in plain text.- Errors during command execution are caught, and a
500 Internal Server Errorresponse is returned with the error message.
- Dynamic Endpoint Creation:
- The program iterates over
COMMANDSand creates a route for each command using Flask’sadd_url_rulefunction. Each command inCOMMANDSgets its own endpoint (e.g.,/top,/free,/df). - Each endpoint is mapped to a POST request, allowing clients to retrieve system data securely.
- The program iterates over
- Running the App:
- When executed, the app runs on host
0.0.0.0and listens on port5000.
- When executed, the app runs on host
Usage Instructions
To use this service, a user would:
- Set Up the Token:
- Replace
"your_secret_token"inAUTH_TOKENwith a secure, complex token.
- Replace
- Make a Request:
- Send a POST request to any of the defined endpoints (e.g.,
/top,/free,/df).Include anAuthorizationheader with the valueBearer your_secret_token(replaceyour_secret_tokenwith the actual token used in the app).
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.
- Send a POST request to any of the defined endpoints (e.g.,
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.