Buckets:

download
raw
12 kB
"""
qterminal MCP – Hermes Orchestrator Terminal.
Ermöglicht Hermes:
- Shell-Kommandos in Containern oder Host ausführen
- Spezialisierte Docker spawnen (recon, exploit, scan)
- Docker-Netze verwalten
- Dateien zwischen Containern austauschen
"""
import json
import os
import shlex
import subprocess
import sys
import tempfile
import time
import uuid
from pathlib import Path
from typing import Any
from mcp.server.fastmcp import FastMCP
mcp = FastMCP(
"qterminal", instructions="Hermes Shell & Docker Orchestrator. Execute commands, spawn containers, manage networks."
)
CONTAINER_WORK_DIR = "/tmp/qterminal"
os.makedirs(CONTAINER_WORK_DIR, exist_ok=True)
DEFAULT_SHELL = os.environ.get("QTERMINAL_SHELL", "/bin/bash")
DEFAULT_IMAGE = os.environ.get("QTERMINAL_IMAGE", "python:3.12-slim")
DOCKER_NETWORK = os.environ.get("DOCKER_NETWORK", "zen_network")
def _run_cmd(cmd: list[str], timeout: int = 60, cwd: str | None = None) -> dict:
try:
r = subprocess.run(
cmd,
capture_output=True,
text=True,
timeout=timeout,
cwd=cwd,
)
return {
"status": "ok" if r.returncode == 0 else "error",
"exit_code": r.returncode,
"stdout": r.stdout,
"stderr": r.stderr,
}
except subprocess.TimeoutExpired:
return {"status": "timeout", "exit_code": -1, "stdout": "", "stderr": "Command timed out"}
except FileNotFoundError:
return {"status": "error", "exit_code": -1, "stdout": "", "stderr": f"Command not found: {cmd[0]}"}
except Exception as e:
return {"status": "error", "exit_code": -1, "stdout": "", "stderr": str(e)}
@mcp.tool()
def exec_shell(
command: str,
timeout: int = 60,
workdir: str = "",
) -> str:
"""Execute a shell command on the host/container.
Args:
command: Shell command to execute
timeout: Timeout in seconds
workdir: Working directory (default: /tmp/qterminal)
"""
cwd = workdir or CONTAINER_WORK_DIR
result = _run_cmd(
[DEFAULT_SHELL, "-c", command],
timeout=timeout,
cwd=cwd,
)
return json.dumps(result)
@mcp.tool()
def exec_python(
code: str,
timeout: int = 60,
) -> str:
"""Execute Python code and return the result.
Args:
code: Python code to execute
timeout: Timeout in seconds
"""
with tempfile.NamedTemporaryFile(mode="w", suffix=".py", delete=False) as f:
f.write(code)
f.flush()
result = _run_cmd([sys.executable, f.name], timeout=timeout)
os.unlink(f.name)
return json.dumps(result)
@mcp.tool()
def docker_ps(
all_containers: bool = True,
filters: str = "",
) -> str:
"""List Docker containers.
Args:
all_containers: Include stopped containers
filters: Additional docker ps filters
"""
cmd = ["docker", "ps"]
if all_containers:
cmd.append("-a")
if filters:
cmd.extend(["--filter", filters])
cmd.extend(["--format", "{{.ID}}\t{{.Image}}\t{{.Status}}\t{{.Names}}\t{{.NetworkSettings.Networks}}"])
result = _run_cmd(cmd)
if result["status"] == "ok":
lines = [line.strip() for line in result["stdout"].split("\n") if line.strip()]
containers = []
for line in lines:
parts = line.split("\t")
if len(parts) >= 4:
containers.append(
{
"id": parts[0][:12],
"image": parts[1],
"status": parts[2],
"name": parts[3],
"networks": parts[4] if len(parts) > 4 else "",
}
)
return json.dumps({"status": "ok", "containers": containers, "count": len(containers)})
return json.dumps(result)
@mcp.tool()
def docker_spawn(
image: str = DEFAULT_IMAGE,
name: str = "",
command: str = "",
env: dict[str, str] | None = None,
volumes: list[str] | None = None,
network: str = DOCKER_NETWORK,
ports: list[str] | None = None,
detach: bool = True,
labels: dict[str, str] | None = None,
) -> str:
"""Spawn a new Docker container.
Args:
image: Docker image to use
name: Container name (auto-generated if empty)
command: Command to run (default: sleep infinity for detach)
env: Environment variables dict
volumes: Volume mounts (e.g. ["/host/path:/container/path"])
network: Docker network to join
ports: Port mappings (e.g. ["8080:80"])
detach: Run in background
labels: Docker labels dict
"""
if not name:
name = f"qterminal-{uuid.uuid4().hex[:8]}"
cmd = ["docker", "run"]
if detach:
cmd.append("-d")
cmd.extend(["--name", name])
if network:
cmd.extend(["--network", network])
if labels:
for k, v in labels.items():
cmd.extend(["-l", f"{k}={v}"])
if env:
for k, v in env.items():
cmd.extend(["-e", f"{k}={v}"])
if volumes:
for v in volumes:
cmd.extend(["-v", v])
if ports:
for p in ports:
cmd.extend(["-p", p])
cmd.append(image)
if command:
cmd.extend(shlex.split(command))
elif detach:
cmd.extend(["sleep", "infinity"])
result = _run_cmd(cmd, timeout=120)
return json.dumps(result)
@mcp.tool()
def docker_exec(
container: str,
command: str,
timeout: int = 60,
) -> str:
"""Execute a command inside a running Docker container.
Args:
container: Container name or ID
command: Command to execute
timeout: Timeout in seconds
"""
result = _run_cmd(
["docker", "exec", container] + shlex.split(command),
timeout=timeout,
)
return json.dumps(result)
@mcp.tool()
def docker_kill(
container: str,
signal: str = "SIGTERM",
) -> str:
"""Stop/kill a Docker container.
Args:
container: Container name or ID
signal: Signal to send (SIGTERM, SIGKILL)
"""
result = _run_cmd(["docker", "kill", "-s", signal, container])
if result["status"] == "ok":
_run_cmd(["docker", "rm", "-f", container])
return json.dumps(result)
@mcp.tool()
def docker_logs(
container: str,
tail: int = 100,
follow: bool = False,
) -> str:
"""Get logs from a Docker container.
Args:
container: Container name or ID
tail: Number of lines from the end
follow: Stream logs (not recommended via MCP)
"""
cmd = ["docker", "logs", "--tail", str(tail)]
if follow:
cmd.append("--follow")
cmd.append(container)
result = _run_cmd(cmd, timeout=30)
return json.dumps(result)
@mcp.tool()
def docker_network_ls() -> str:
"""List Docker networks."""
result = _run_cmd(["docker", "network", "ls", "--format", "{{.ID}}\t{{.Name}}\t{{.Driver}}\t{{.Scope}}"])
if result["status"] == "ok":
lines = [ln.strip() for ln in result["stdout"].split("\n") if ln.strip()]
networks = []
for line in lines:
parts = line.split("\t")
if len(parts) >= 2:
networks.append(
{
"id": parts[0][:12],
"name": parts[1],
"driver": parts[2] if len(parts) > 2 else "",
"scope": parts[3] if len(parts) > 3 else "",
}
)
return json.dumps({"status": "ok", "networks": networks, "count": len(networks)})
return json.dumps(result)
@mcp.tool()
def docker_network_connect(
container: str,
network: str = DOCKER_NETWORK,
) -> str:
"""Connect a container to a Docker network.
Args:
container: Container name or ID
network: Network name
"""
result = _run_cmd(["docker", "network", "connect", network, container])
return json.dumps(result)
@mcp.tool()
def docker_build(
dockerfile_content: str,
tag: str = "",
build_args: dict[str, str] | None = None,
) -> str:
"""Build a Docker image from inline Dockerfile content.
Args:
dockerfile_content: Content of the Dockerfile
tag: Image tag (e.g. "zen-recon:latest")
build_args: Build arguments dict
"""
build_dir = tempfile.mkdtemp(prefix="qterminal-build-")
try:
df_path = os.path.join(build_dir, "Dockerfile")
with open(df_path, "w") as f:
f.write(dockerfile_content)
cmd = ["docker", "build", build_dir]
if tag:
cmd.extend(["-t", tag])
if build_args:
for k, v in build_args.items():
cmd.extend(["--build-arg", f"{k}={v}"])
result = _run_cmd(cmd, timeout=300)
return json.dumps(result)
finally:
_run_cmd(["rm", "-rf", build_dir])
@mcp.tool()
def image_pull(
image: str,
) -> str:
"""Pull a Docker image.
Args:
image: Image name (e.g. "kalilinux/kali-rolling")
"""
result = _run_cmd(["docker", "pull", image], timeout=300)
return json.dumps(result)
@mcp.tool()
def image_ls() -> str:
"""List Docker images."""
result = _run_cmd(["docker", "images", "--format", "{{.Repository}}:{{.Tag}}\t{{.ID}}\t{{.Size}}\t{{.CreatedSince}}"])
if result["status"] == "ok":
lines = [ln.strip() for ln in result["stdout"].split("\n") if ln.strip()]
images = []
for line in lines:
parts = line.split("\t")
if len(parts) >= 2:
images.append(
{
"tag": parts[0],
"id": parts[1][:12],
"size": parts[2] if len(parts) > 2 else "",
"created": parts[3] if len(parts) > 3 else "",
}
)
return json.dumps({"status": "ok", "images": images, "count": len(images)})
return json.dumps(result)
@mcp.tool()
def spawn_recon_agent(
target: str,
name: str = "",
) -> str:
"""Spawn a specialized reconnaissance Docker container.
Args:
target: Target IP/hostname to recon
name: Container name (auto-generated if empty)
"""
if not name:
name = f"recon-{uuid.uuid4().hex[:8]}"
result = _run_cmd(
[
"docker",
"run",
"-d",
"--name",
name,
"--network",
DOCKER_NETWORK,
"-e",
f"TARGET={target}",
"kalilinux/kali-rolling",
"bash",
"-c",
f"apt-get update -qq && apt-get install -y -qq nmap netcat-openbsd 2>/dev/null; "
f"echo '=== RECON AGENT READY ==='; "
f"nmap -sn {target} 2>&1; "
f"echo '=== DONE ==='; "
f"sleep infinity",
],
timeout=120,
)
return json.dumps(result)
@mcp.tool()
def spawn_exploit_agent(
target: str,
port: str = "80",
name: str = "",
) -> str:
"""Spawn a specialized exploit Docker container.
Args:
target: Target IP/hostname
port: Target port
name: Container name
"""
if not name:
name = f"exploit-{uuid.uuid4().hex[:8]}"
result = _run_cmd(
[
"docker",
"run",
"-d",
"--name",
name,
"--network",
DOCKER_NETWORK,
"-e",
f"TARGET={target}",
"-e",
f"PORT={port}",
"kalilinux/kali-rolling",
"bash",
"-c",
"apt-get update -qq && apt-get install -y -qq metasploit-framework netcat-openbsd 2>/dev/null; "
"echo '=== EXPLOIT AGENT READY ==='; "
"sleep infinity",
],
timeout=120,
)
return json.dumps(result)
def main():
mcp.run()
if __name__ == "__main__":
main()

Xet Storage Details

Size:
12 kB
·
Xet hash:
9eaac377cfcebd8458ba00ff7c5beb5f3f714186a7d076b8c971ecba20ad9042

Xet efficiently stores files, intelligently splitting them into unique chunks and accelerating uploads and downloads. More info.