Organize project: Move old code and documentation to oldcode folder, add comprehensive README
This commit is contained in:
73
commands_module.py
Normal file
73
commands_module.py
Normal file
@@ -0,0 +1,73 @@
|
||||
"""
|
||||
System command execution with security restrictions
|
||||
"""
|
||||
|
||||
import subprocess
|
||||
import logging
|
||||
from config_settings import ALLOWED_COMMANDS, COMMAND_TIMEOUT
|
||||
from logger_module import log_with_server
|
||||
|
||||
|
||||
def execute_system_command(command, hostname, device_ip):
|
||||
"""
|
||||
Execute system commands with proper logging and security checks
|
||||
|
||||
Args:
|
||||
command: The command to execute (must be in ALLOWED_COMMANDS)
|
||||
hostname: Device hostname for logging
|
||||
device_ip: Device IP for logging
|
||||
|
||||
Returns:
|
||||
dict with status, message, and output
|
||||
"""
|
||||
try:
|
||||
# Check if command is allowed
|
||||
if command not in ALLOWED_COMMANDS:
|
||||
log_with_server(f"Command '{command}' is not allowed for security reasons", hostname, device_ip)
|
||||
return {
|
||||
"status": "error",
|
||||
"message": f"Command '{command}' is not allowed",
|
||||
"output": ""
|
||||
}
|
||||
|
||||
log_with_server(f"Executing command: {command}", hostname, device_ip)
|
||||
|
||||
# Execute the command
|
||||
result = subprocess.run(
|
||||
command.split(),
|
||||
capture_output=True,
|
||||
text=True,
|
||||
timeout=COMMAND_TIMEOUT
|
||||
)
|
||||
|
||||
output = result.stdout + result.stderr
|
||||
|
||||
if result.returncode == 0:
|
||||
log_with_server(f"Command '{command}' executed successfully", hostname, device_ip)
|
||||
return {
|
||||
"status": "success",
|
||||
"message": "Command executed successfully",
|
||||
"output": output
|
||||
}
|
||||
else:
|
||||
log_with_server(f"Command '{command}' failed with return code {result.returncode}", hostname, device_ip)
|
||||
return {
|
||||
"status": "error",
|
||||
"message": f"Command failed with return code {result.returncode}",
|
||||
"output": output
|
||||
}
|
||||
|
||||
except subprocess.TimeoutExpired:
|
||||
log_with_server(f"Command '{command}' timed out", hostname, device_ip)
|
||||
return {
|
||||
"status": "error",
|
||||
"message": "Command timed out",
|
||||
"output": ""
|
||||
}
|
||||
except Exception as e:
|
||||
log_with_server(f"Error executing command '{command}': {str(e)}", hostname, device_ip)
|
||||
return {
|
||||
"status": "error",
|
||||
"message": f"Error: {str(e)}",
|
||||
"output": ""
|
||||
}
|
||||
Reference in New Issue
Block a user