Compare commits

...
9 Commits
Author SHA1 Message Date
duffyduckandClaude Opus 4.8 f4495f3585 docs: Vision-Roadmap-Punkt geschlossen — ARIA sieht Bilder via Read-Tool
"Claude Vision direkt (ohne Dateipfad-Umweg)" abgehakt und umformuliert:
Bildanalyse funktioniert bereits (App-Uploads + Screenshots via Read-Tool,
/shared/uploads im Proxy-Container gemountet). Die "direkte" Variante waere
reine Politur (ein Read weniger) und ist bewusst nicht geplant — vermeidet,
dass jemand den heiklen Proxy-Umbau spaeter grundlos wieder aufmacht.

Co-Authored-By: Claude Opus 4.8 <noreply@anthropic.com>
2026-09-24 16:26:45 +02:00
duffyduckandClaude Opus 4.8 d503c21211 docs: Host-Agent-Deployment in der README (Tabelle + eigener Abschnitt)
Der Host-Agent stand nur in host-agent/README.md, nicht in der zentralen Doku.
Ergaenzt: Zeile in der Deploy-Tabelle + Abschnitt "Host-Agenten" (build.sh ->
Binary, Install, sudo-Faelle inkl. Live-ISO, Sicherheit, Vision via Read-Tool).

Co-Authored-By: Claude Opus 4.8 <noreply@anthropic.com>
2026-09-24 16:22:20 +02:00
duffyduckandClaude Opus 4.8 2fc5700da0 feat(host-agent): ARIA SIEHT den Screenshot (via eigenes Read-Tool)
Der Proxy reduziert Multimodal-Content zu Text (openai-to-cli), ARIA laeuft auf
der Claude-Code-CLI. Aber: der Proxy-Container hat /shared gemountet und ARIA
laeuft mit vollen Tools (--dangerously-skip-permissions) -> sie kann die unter
/shared/uploads/ gespeicherte Screenshot-PNG mit ihrem eigenen Read-Tool
oeffnen, das Claude Code nativ als Bild rendert. Damit SIEHT sie den Bildschirm
und kann 'was ist auf meinem Bildschirm' beantworten — ganz ohne Proxy-/Vision-
Umbau. host_screenshot-Result + Tool-Beschreibung weisen sie an, den Pfad zu
Read'en (sehen) UND als [FILE:]-Marker zu setzen (im Chat zeigen).

Co-Authored-By: Claude Opus 4.8 <noreply@anthropic.com>
2026-09-24 16:20:08 +02:00
duffyduckandClaude Opus 4.8 6c185899ae feat(host-agent): host_screenshot erscheint inline im Chat (FILE-Marker)
Statt den Screenshot nur nach /shared/host-screenshots zu legen und den Pfad
zu nennen, speichert host_screenshot das PNG jetzt nach /shared/uploads/ und
liefert ARIA die Anweisung, den Pfad als [FILE: ...]-Marker in die Antwort zu
schreiben — exakt das flux_generate-Muster. Die Bridge erkennt den Marker,
broadcastet file_from_aria, und App/Diagnostic zeigen das Bild inline im Chat.

Co-Authored-By: Claude Opus 4.8 <noreply@anthropic.com>
2026-09-24 16:16:15 +02:00
duffyduckandClaude Opus 4.8 5ca348519a feat(diagnostic): Host-Agenten in der Satelliten-Flotte anzeigen (Phase E)
Diagnostic-Server trackt host_hello/host_ping (hosts-Map), broadcastet
host_update und beantwortet die host_list-Action. UI: neues Panel
"Host-Agenten" im Satelliten-Tab — zeigt Name/OS/Caps/online + ob
CONTROL_ENABLED. Reine Sichtbarkeit; Steuerung laeuft ueber ARIA.

Co-Authored-By: Claude Opus 4.8 <noreply@anthropic.com>
2026-09-24 16:12:50 +02:00
duffyduckandClaude Opus 4.8 fd2745a4b5 feat(host-agent): Backend-Anbindung — RVS + Bridge-Registry + Brain-Tools (Phase B-D)
Damit kann ARIA Host-Agenten tatsaechlich nutzen (Ende-zu-Ende):

- RVS: host_hello/host_ping/host_command/host_result in ALLOWED_TYPES.
- Bridge: _hosts-Registry (host_hello/host_ping/host_result), _host_list,
  _host_request (requestId->Future wie Satelliten), HTTP-Endpoints
  /internal/host-list und /internal/host (op via action).
- Brain: Tools host_list/host_exec/host_read/host_write/host_info/
  host_screenshot + _dispatch_host (ruft /internal/host*). host_screenshot
  speichert das PNG unter /shared/host-screenshots. host_exec kann sudo=true.

Naechste (optionale) Phase E: Host-Agenten in der Diagnostic-Flotte anzeigen.

Co-Authored-By: Claude Opus 4.8 <noreply@anthropic.com>
2026-09-24 16:11:06 +02:00
duffyduckandClaude Opus 4.8 bd518fff4c feat(host-agent): Direktzugriffs-Agent fuer einen Rechner (Phase A: Agent + Build)
Schlanker Agent, der DIREKT auf einem Linux-Rechner laeuft und sich ausgehend
zum RVS verbindet -> ARIA steuert den Rechner auch hinter NAT/Firewall, wo er
sonst nicht erreichbar ist. Anders als der Satellit (LAN-Gateway) steuert der
Agent den Rechner, auf dem er laeuft.

Faehigkeiten (host_command -> host_result): exec (opt. sudo), read, write,
info (CPU/RAM/Disk/Uptime via psutil), screenshot (grim/scrot/maim/import).
sudo-Logik: root -> direkt; SUDO_PASSWORD -> sudo -S; SUDO_NOPASSWD (Live-ISO)
-> sudo -n; sonst klare Fehlermeldung. Gate: CONTROL_ENABLED + RVS-Token.
stdout wird wie beim Satelliten gefenstert (contains/offset/max_chars).

Als portable Onefile-Binary verteilbar (PyInstaller im bullseye-Container fuer
breite glibc-Kompatibilitaet): build.sh + Dockerfile.build. Plus .env.example,
systemd-Unit und README.

Naechste Phasen: RVS ALLOWED_TYPES (host_*), Bridge-Registry + /internal/host*,
Brain-Tools host_list/exec/read/write/info/screenshot.

Co-Authored-By: Claude Opus 4.8 <noreply@anthropic.com>
2026-09-24 16:07:27 +02:00
duffyduckandClaude Opus 4.8 84f405d264 feat(satellite): ssh.exec — ARIA fuehrt Kommandos per SSH auf Geraeten aus
Neuer Credential-Typ 'ssh' (Benutzer + Passwort ODER privater Key, Port) und
Aktion ssh.exec (params: ip, cmd). paramiko-Client; grosse Ausgaben werden wie
bei http.get gefenstert (contains/offset/max_chars gemeinsam via _window_text),
Antwort mit exit_code + stdout + stderr. Auth kommt aus dem Credential-Store,
ARIA muss keine Passwoerter mitgeben.

- satellite: _do_ssh + _ssh_load_key (RSA/Ed25519/ECDSA/DSS aus String),
  ssh.exec in _control + Allowlist, 'ssh' in beide Cred-Typ-Listen; paramiko
  in requirements; .env.example ergaenzt.
- diagnostic: SSH-Sektion im Credentials-Modal (User/Port/Passwort/Key) +
  Save-Logik (User + Passwort|Key).
- brain: satellite_command-Tool um ssh.exec erweitert.

Laeuft ueber den bestehenden sat_command/sat_result-Pfad — keine RVS-Aenderung.

Co-Authored-By: Claude Opus 4.8 <noreply@anthropic.com>
2026-09-24 16:00:54 +02:00
duffyduckandClaude Opus 4.8 e81fb5b45c feat(app): Datei-Upload erlaubt alle Dateitypen (Bueroklammer)
Der DocumentPicker war auf images/pdf/docx/plainText beschraenkt -> vom
Smartphone liessen sich nur Bilder/Dokumente hochladen. Auf allFiles
umgestellt; die Komponente verarbeitet beliebige Typen ohnehin (Base64 +
octet-stream-Fallback), und die Server-Seite hat kein MIME-Gate.

Co-Authored-By: Claude Opus 4.8 <noreply@anthropic.com>
2026-09-24 15:57:56 +02:00
18 changed files with 1198 additions and 52 deletions
+54 -1
View File
@@ -96,6 +96,7 @@ ARIA hat zwei Rollen:
| ARIA Brain/Bridge/Diagnostic | Debian 13 VM | `./init.sh && ./aria-setup.sh && docker compose up -d` |
| Compute-Node(s) (STT/TTS/LLM) | 1..n GPU-Rechner | `cd xtts && cp .env.example .env && docker compose up -d` |
| Satellit(en) 🛰️ (optional) | Fremdes Netz (Büro …) | `cd satellite && cp .env.example .env && docker compose up -d --build` |
| Host-Agent(en) 💻 (optional) | Direkt auf einem Rechner | `cd host-agent && ./build.sh` → Binary + `.env` auf den Rechner, starten (Details unten & in [`host-agent/README.md`](host-agent/README.md)) |
| Android App | Stefans Handy | APK installieren (Auto-Update via RVS) |
> Compute-Nodes sind optional: ohne sie faellt STT auf lokales Whisper (CPU,
@@ -936,6 +937,58 @@ dem Cache wiederverwendet.
---
## Host-Agenten 💻 — Direktzugriff auf einen Rechner
Ein **Host-Agent** läuft als **Standalone-Binary direkt auf einem Rechner**
(Linux) und verbindet sich **ausgehend** zum RVS (gleicher Token). Damit steuert
ARIA diesen Rechner direkt — auch wenn er sonst aus dem Netz **nicht erreichbar**
ist (hinter NAT/Firewall, kein offener Port). Unterschied zum Satelliten: der
Satellit ist ein LAN-Gateway (entdeckt/steuert *andere* Geräte); der Host-Agent
steuert den Rechner, auf dem er *läuft*.
**Fähigkeiten** (ARIA-Tools `host_list` / `host_exec` / `host_read` /
`host_write` / `host_info` / `host_screenshot`): Shell-Kommandos (optional
`sudo`), Datei lesen/schreiben, System-Info (CPU/RAM/Disk/Uptime), Screenshot
(ARIA öffnet ihn mit ihrem Read-Tool und *sieht* den Bildschirm; erscheint zudem
inline im Chat).
### 1. Binary bauen (portabel, Linux x86_64)
```bash
cd host-agent
./build.sh # braucht Docker; erzeugt dist/aria-host-agent (~15 MB)
```
Gebaut wird via PyInstaller in einem bullseye-Container (altes glibc) → läuft auf
möglichst vielen Distributionen. Keine Runtime auf dem Ziel nötig.
### 2. Auf dem Ziel-Rechner installieren
```bash
# dist/aria-host-agent auf den Rechner kopieren, dann:
cp .env.example .env # RVS-Zugang + CONTROL_ENABLED=true eintragen
chmod +x aria-host-agent && ./aria-host-agent
```
Oder als Dienst: `host-agent/aria-host-agent.service` (systemd).
### sudo
Der Agent wählt automatisch: **root** → direkt · `SUDO_PASSWORD` in der `.env`
→ `sudo -S` · **`SUDO_NOPASSWD=true`** → `sudo -n` (Live-ISO / passwortloses
sudo, z.B. Linux Mint vom Stick) · sonst klare Fehlermeldung.
### Sicherheit
Reagiert nur auf den eigenen RVS-Raum (Token) und nur bei `CONTROL_ENABLED=true`;
keine offenen Ports; alle Kommandos werden geloggt. Gibt **vollen** Rechnerzugriff
— nur auf Maschinen einsetzen, denen du ARIA anvertraust. Details:
[`host-agent/README.md`](host-agent/README.md).
> Sichtbar in der Diagnostic unter **Satelliten → Host-Agenten 💻**.
---
## Docker Volumes
| Volume / Bind | Pfad im Container | Zweck |
@@ -1134,4 +1187,4 @@ docker exec aria-brain curl localhost:8080/memory/stats
- [ ] Desktop Client (Tauri)
- [ ] bKVM Remote IT-Support
- [ ] Custom-`.onnx`-Upload fuer Wake-Word ueber Diagnostic (ohne App-Rebuild)
- [ ] Claude Vision direkt (Bildanalyse ohne Dateipfad-Umweg)
- [x] Bildanalyse / Vision — ARIA sieht App-Uploads & Screenshots via Read-Tool (`/shared/uploads/` ist im Proxy-Container gemountet). „Direkt ohne Dateipfad" waere reine Politur (ein Read weniger) und ist bewusst NICHT geplant.
+5 -8
View File
@@ -34,13 +34,10 @@ interface FileUploadProps {
onCancel: () => void;
}
// Unterstuetzte Dateitypen
const SUPPORTED_TYPES = [
DocumentPicker.types.images,
DocumentPicker.types.pdf,
DocumentPicker.types.docx,
DocumentPicker.types.plainText,
];
// Alle Dateitypen zulassen — Stefan will ueber die Bueroklammer jede Datei
// hochladen koennen, nicht nur Bilder/Dokumente. Die Komponente verarbeitet
// beliebige Typen ohnehin (Base64 + application/octet-stream als Fallback).
const SUPPORTED_TYPES = [DocumentPicker.types.allFiles];
// --- Komponente ---
@@ -112,7 +109,7 @@ const FileUpload: React.FC<FileUploadProps> = ({ onFileSelected, onCancel }) =>
<TouchableOpacity style={styles.pickButton} onPress={pickFile} activeOpacity={0.7}>
<Text style={styles.pickIcon}>{'\uD83D\uDCC1'}</Text>
<Text style={styles.pickText}>Datei ausw\u00E4hlen</Text>
<Text style={styles.pickHint}>JPG, PNG, PDF, DOCX, TXT</Text>
<Text style={styles.pickHint}>Alle Dateitypen</Text>
</TouchableOpacity>
) : (
// Vorschau und Senden
+232 -3
View File
@@ -20,6 +20,7 @@ import json
import logging
import os
import re
import time
import urllib.error
import urllib.parse
import urllib.request
@@ -1233,9 +1234,13 @@ META_TOOLS = [
"(params={'ip':'...','oid':'...','community':'public'}) fuer beliebige "
"SNMP-Werte. 'fritzbox.info' / 'fritzbox.hosts' (params={'ip':'<fritzbox>'}) "
"— Internetverbindung/Datenrate/externe IP bzw. verbundene Geraete (braucht "
"hinterlegten FritzBox-Login). Fuer Geraete mit hinterlegten Zugangsdaten "
"(community/v3/Login) nutzt der Satellit diese automatisch — Du musst keine "
"Passwoerter mitgeben. "
"hinterlegten FritzBox-Login). 'ssh.exec' (params={'ip':'...','cmd':'...'}) "
"— fuehrt EIN Shell-Kommando per SSH auf einem Geraet aus (Server, Pi, NAS) "
"und gibt exit_code + stdout (gefenstert: contains/offset/max_chars) + "
"stderr zurueck; braucht hinterlegte SSH-Credentials (Benutzer + Passwort "
"oder Key). Fuer Geraete mit hinterlegten Zugangsdaten "
"(community/v3/Login/SSH) nutzt der Satellit diese automatisch — Du musst "
"keine Passwoerter mitgeben. "
"'http.get'/'http.post' (params={'url':'...'}) fuer lokale Webhooks UND "
"um Geraete-Statusseiten zu lesen (Fallback fuer Tinte, NAS ...). Bei grossen "
"Seiten NICHT blind paginieren: setze params['contains'] (String oder "
@@ -1258,6 +1263,107 @@ META_TOOLS = [
},
},
},
{
"type": "function",
"function": {
"name": "host_list",
"description": (
"Zeigt die ARIA-Host-Agenten (Rechner, auf denen ein Agent DIREKT "
"laeuft und sich per RVS meldet) die ONLINE sind + was sie koennen "
"(exec/read/write/info/screenshot). Ein Host-Agent gibt Dir vollen "
"Zugriff auf GENAU DIESEN Rechner — auch wenn er hinter NAT/Firewall "
"sitzt. Nutze das, wenn Stefan etwas 'auf meinem Laptop/PC/Server X' "
"machen will, das kein Geraet im Netz ist."
),
"parameters": {"type": "object", "properties": {}},
},
},
{
"type": "function",
"function": {
"name": "host_exec",
"description": (
"Fuehrt EIN Shell-Kommando auf einem Host-Agenten aus (bash -lc). "
"Gibt exit_code + stdout (gefenstert: contains/offset/max_chars) + "
"stderr. Fuer Root-Rechte sudo=true setzen (Agent nutzt root/"
"SUDO_PASSWORD/NOPASSWD automatisch). Sei vorsichtig — das ist "
"vollwertiger Rechnerzugriff."
),
"parameters": {
"type": "object",
"properties": {
"host": {"type": "string", "description": "Host-ID/Name aus host_list."},
"cmd": {"type": "string", "description": "Shell-Kommando."},
"sudo": {"type": "boolean", "description": "Mit Root-Rechten ausfuehren."},
"timeout": {"type": "number", "description": "max. Laufzeit in Sekunden (Default 60)."},
},
"required": ["host", "cmd"],
},
},
},
{
"type": "function",
"function": {
"name": "host_read",
"description": "Liest eine Datei von einem Host-Agenten (Text). Fuer Binaerdateien liefert der Agent Base64.",
"parameters": {
"type": "object",
"properties": {
"host": {"type": "string", "description": "Host-ID/Name."},
"path": {"type": "string", "description": "Absoluter Pfad auf dem Rechner."},
},
"required": ["host", "path"],
},
},
},
{
"type": "function",
"function": {
"name": "host_write",
"description": "Schreibt Text in eine Datei auf einem Host-Agenten (ueberschreibt; append=true haengt an).",
"parameters": {
"type": "object",
"properties": {
"host": {"type": "string", "description": "Host-ID/Name."},
"path": {"type": "string", "description": "Zielpfad."},
"text": {"type": "string", "description": "Inhalt."},
"append": {"type": "boolean", "description": "Anhaengen statt ueberschreiben."},
},
"required": ["host", "path", "text"],
},
},
},
{
"type": "function",
"function": {
"name": "host_info",
"description": "System-Info eines Host-Agenten: OS, CPU/RAM/Disk-Auslastung, Uptime, IP.",
"parameters": {
"type": "object",
"properties": {"host": {"type": "string", "description": "Host-ID/Name."}},
"required": ["host"],
},
},
},
{
"type": "function",
"function": {
"name": "host_screenshot",
"description": (
"Macht ein Bildschirmfoto auf einem Host-Agenten (nur wenn dort eine "
"grafische Session laeuft). Liefert einen Datei-Pfad unter /shared/uploads/. "
"Du KANNST den Screenshot selbst ansehen: oeffne den Pfad mit deinem "
"Read-Tool (Bild wird gerendert) — so beantwortest Du 'was ist auf meinem "
"Bildschirm'. Und schreibe den Pfad als [FILE: ...]-Marker in die Antwort, "
"damit die App das Bild inline zeigt."
),
"parameters": {
"type": "object",
"properties": {"host": {"type": "string", "description": "Host-ID/Name."}},
"required": ["host"],
},
},
},
{
"type": "function",
"function": {
@@ -2424,6 +2530,126 @@ class Agent:
except Exception as exc:
return f"FEHLER: Satellit/Bridge nicht erreichbar: {exc}"
def _dispatch_host(self, name: str, arguments: dict) -> str:
"""host_list / host_exec / host_read / host_write / host_info /
host_screenshot — via Bridge (/internal/host*) → RVS → Host-Agent."""
import base64 as _b64
def _post(path: str, body: dict, timeout: float) -> dict:
data = json.dumps(body).encode("utf-8")
req = urllib.request.Request(f"{BRIDGE_URL}{path}", data=data, method="POST",
headers={"Content-Type": "application/json"})
with urllib.request.urlopen(req, timeout=timeout) as resp:
return json.loads(resp.read().decode("utf-8", "ignore"))
try:
if name == "host_list":
result = _post("/internal/host-list", {}, 10)
hosts = result.get("hosts") or []
if not hosts:
return ("Gerade ist kein Host-Agent online. (Ein Host-Agent laeuft "
"direkt auf einem Rechner und erlaubt Dir, ihn zu steuern — "
"auch hinter NAT/Firewall.)")
lines = []
for h in hosts:
status = "online" if h.get("online") else "offline"
caps = ", ".join(h.get("caps") or [])
lines.append(f"- {h.get('name')} (id={h.get('hostId')}, {status}, "
f"{h.get('os', '')}; kann: {caps})")
return "Host-Agenten (Rechner):\n" + "\n".join(lines)
host = (arguments.get("host") or "").strip()
if not host:
return "FEHLER: host ist Pflicht (siehe host_list)."
if name == "host_exec":
cmd = (arguments.get("cmd") or "").strip()
if not cmd:
return "FEHLER: cmd ist Pflicht."
params = {"cmd": cmd}
if arguments.get("sudo"):
params["sudo"] = True
timeout = float(arguments.get("timeout") or 60)
result = _post("/internal/host", {"host": host, "action": "exec",
"params": params, "timeout": timeout + 10},
timeout + 20)
if not result.get("ok"):
return f"FEHLER: {result.get('error')}"
r = result.get("result") or {}
note = f"exit={r.get('exit_code')}"
if r.get("truncated"):
note += f" (stdout gekuerzt, {r.get('total_chars')} Zeichen gesamt)"
out = f"[{note}]\n{r.get('body', '')}"
stderr = (r.get("stderr") or "").strip()
if stderr:
out += f"\n--- stderr ---\n{stderr[:1500]}"
return out
if name == "host_read":
path = (arguments.get("path") or "").strip()
result = _post("/internal/host", {"host": host, "action": "read",
"params": {"path": path}}, 30)
if not result.get("ok"):
return f"FEHLER: {result.get('error')}"
r = result.get("result") or {}
try:
text = _b64.b64decode(r.get("base64", "")).decode("utf-8", "replace")
except Exception:
text = "(Binaerdatei — nicht als Text darstellbar)"
trunc = " (gekuerzt)" if r.get("truncated") else ""
return f"{r.get('path')} ({r.get('size')} Bytes){trunc}:\n{text[:8000]}"
if name == "host_write":
text = arguments.get("text") or ""
params = {"path": (arguments.get("path") or "").strip(),
"base64": _b64.b64encode(text.encode("utf-8")).decode("ascii"),
"append": bool(arguments.get("append"))}
result = _post("/internal/host", {"host": host, "action": "write",
"params": params}, 30)
if not result.get("ok"):
return f"FEHLER: {result.get('error')}"
r = result.get("result") or {}
return f"OK — {r.get('bytes')} Bytes nach {r.get('path')} geschrieben."
if name == "host_info":
result = _post("/internal/host", {"host": host, "action": "info",
"params": {}}, 20)
if not result.get("ok"):
return f"FEHLER: {result.get('error')}"
return f"System-Info {host}:\n" + json.dumps(result.get("result") or {},
ensure_ascii=False, indent=2)
if name == "host_screenshot":
result = _post("/internal/host", {"host": host, "action": "screenshot",
"params": {}}, 30)
if not result.get("ok"):
return f"FEHLER: {result.get('error')}"
r = result.get("result") or {}
# Wie flux_generate: PNG nach /shared/uploads/ (nur dieser Pfad
# matcht den [FILE:]-Marker) -> Bridge broadcastet file_from_aria,
# App/Diagnostic zeigen es inline im Chat.
try:
d = "/shared/uploads"
os.makedirs(d, exist_ok=True)
safe = re.sub(r"[^a-zA-Z0-9_-]+", "-", host).strip("-") or "host"
fp = os.path.join(d, f"aria_screenshot_{safe}_{int(time.time())}.png")
with open(fp, "wb") as f:
f.write(_b64.b64decode(r.get("base64", "")))
except Exception as exc:
return f"Screenshot erstellt ({r.get('bytes')} Bytes), Speichern fehlgeschlagen: {exc}"
return (
f"OK — Screenshot von {host} erstellt ({r.get('bytes', 0) // 1024} KB).\n"
f"path: {fp}\n\n"
f"UM DEN BILDSCHIRM ZU SEHEN: Oeffne die Datei mit deinem Read-Tool "
f"(Read {fp}) — Du bekommst das Bild dann angezeigt und kannst "
f"beschreiben/entscheiden, was darauf zu sehen ist.\n"
f"UM ES STEFAN ZU ZEIGEN: Schreibe den Pfad EXAKT als Marker "
f"[FILE: {fp}] in deine Antwort — dann erscheint das Bild inline im Chat."
)
return f"FEHLER: unbekanntes Host-Tool {name}"
except Exception as exc:
return f"FEHLER: Host/Bridge nicht erreichbar: {exc}"
def _dispatch_tool(self, name: str, arguments: dict, project_id: str = "") -> str:
"""Fuehrt einen Tool-Call aus und gibt ein kurzes Text-Resultat zurueck.
Niemals werfen — Fehler werden als Text-Resultat reportet damit Claude
@@ -3216,6 +3442,9 @@ class Agent:
return f"OK — Projekt '{updated['name']}' ist wieder ein normaler Chat."
if name in ("satellite_list", "satellite_devices", "satellite_command"):
return self._dispatch_satellite(name, arguments)
if name in ("host_list", "host_exec", "host_read", "host_write",
"host_info", "host_screenshot"):
return self._dispatch_host(name, arguments)
if name == "vm_register":
pid = (project_id or "").strip()
if not pid:
+95
View File
@@ -766,6 +766,11 @@ class ARIABridge:
# requestId → Future (sat_devices / sat_result), analog _pending_flux.
self._satellites: dict[str, dict] = {}
self._pending_sat: dict[str, asyncio.Future] = {}
# Host-Agenten (Direktzugriff auf einen Rechner). hostId → {name, os,
# caps, control, last_seen}. Registrierung via host_hello/host_ping.
# _pending_host: requestId → Future (host_result), analog _pending_sat.
self._hosts: dict[str, dict] = {}
self._pending_host: dict[str, asyncio.Future] = {}
# Compute-Fleet: GPU-Worker (voxtral/whisper/f5tts/llm) melden sich per
# worker_hello, halten sich per worker_ping frisch. instanceId →
# {service, node, gpus, model, busy, last_seen}. Genutzt fuer die
@@ -3550,6 +3555,40 @@ class ARIABridge:
self._satellites[sid]["caps"], self._satellites[sid]["control"])
return
elif msg_type == "host_hello":
hid = (payload.get("hostId") or "").strip()
if hid:
new = hid not in self._hosts
self._hosts[hid] = {
"hostId": hid,
"name": payload.get("name") or hid,
"os": payload.get("os") or "",
"caps": payload.get("caps") or [],
"control": bool(payload.get("control")),
"last_seen": time.time(),
}
if new:
logger.info("[host] Agent online: %s (%s) caps=%s control=%s",
hid, self._hosts[hid]["name"],
self._hosts[hid]["caps"], self._hosts[hid]["control"])
return
elif msg_type == "host_ping":
hid = (payload.get("hostId") or "").strip()
if hid and hid in self._hosts:
self._hosts[hid]["last_seen"] = time.time()
return
elif msg_type == "host_result":
req_id = payload.get("requestId", "")
future = self._pending_host.get(req_id)
if future is not None and not future.done():
future.set_result(payload)
hid = (payload.get("hostId") or "").strip()
if hid and hid in self._hosts:
self._hosts[hid]["last_seen"] = time.time()
return
elif msg_type == "worker_hello":
iid = (payload.get("instanceId") or "").strip()
if iid:
@@ -4523,6 +4562,24 @@ class ARIABridge:
elif method in ("GET", "POST") and path == "/internal/worker-list":
# Diagnostic/Brain fragt: welche Compute-Worker sind online (Flotte).
await _send_response(writer, 200, {"ok": True, "workers": self._worker_list()})
elif method == "POST" and path == "/internal/host-list":
# Brain fragt: welche Host-Agenten (Rechner) sind online + Capabilities.
await _send_response(writer, 200, {"ok": True, "hosts": self._host_list()})
elif method == "POST" and path == "/internal/host":
# Brain-Tool: Kommando an einen Host-Agenten.
# body: {host, action, params?, timeout?}
try:
data = json.loads(body.decode("utf-8", "ignore"))
except Exception as exc:
await _send_response(writer, 400, {"error": f"bad json: {exc}"})
return
result = await self._host_request(
host=str(data.get("host") or ""),
action=str(data.get("action") or ""),
params=data.get("params") if isinstance(data.get("params"), dict) else {},
timeout=float(data.get("timeout") or 60.0),
)
await _send_response(writer, 200, result)
elif method == "POST" and path == "/internal/satellite":
# Brain-Tool: Discovery oder Command an einen Satelliten.
# body: {op:'discover'|'command', satellite, device?, action?, params?}
@@ -4862,6 +4919,44 @@ class ARIABridge:
finally:
self._pending_sat.pop(request_id, None)
def _host_list(self) -> list[dict]:
"""Bekannte Host-Agenten (frisch = in den letzten 5 Min gesehen)."""
now = time.time()
return [{
"hostId": h["hostId"], "name": h.get("name") or h["hostId"],
"os": h.get("os") or "", "caps": h.get("caps") or [],
"control": bool(h.get("control")),
"online": (now - h.get("last_seen", 0)) < 300,
} for h in self._hosts.values()]
async def _host_request(self, host: str = "", action: str = "",
params: Optional[dict] = None,
timeout: float = 60.0) -> dict:
"""Schickt host_command an einen Host-Agenten (via RVS) und wartet auf
host_result. Muster identisch zu _satellite_request."""
if self.ws_rvs is None:
return {"ok": False, "error": "RVS-Verbindung nicht aktiv"}
request_id = str(uuid.uuid4())
loop = asyncio.get_event_loop()
future: asyncio.Future = loop.create_future()
self._pending_host[request_id] = future
try:
msg = {"type": "host_command",
"payload": {"requestId": request_id, "host": host,
"action": action, "params": params or {}},
"timestamp": int(time.time() * 1000)}
ok = await self._send_to_rvs(msg)
if not ok:
return {"ok": False, "error": "Host-Request konnte nicht gesendet werden"}
result = await asyncio.wait_for(future, timeout=timeout)
return result if isinstance(result, dict) else {"ok": False, "error": "ungueltige Antwort"}
except asyncio.TimeoutError:
return {"ok": False, "error": f"Host '{host or 'all'}' antwortet nicht (Timeout)."}
except Exception as exc:
return {"ok": False, "error": str(exc)}
finally:
self._pending_host.pop(request_id, None)
async def _delete_chat_message(self, ts: int) -> dict:
"""Entfernt eine Bubble: aus chat_backup.jsonl + Brain conversation,
broadcastet chat_message_deleted via RVS.
+64 -2
View File
@@ -248,6 +248,16 @@
<input id="dc-fb-pass" type="password" placeholder="FritzBox-Passwort" style="width:100%;">
</div>
<div style="border:1px solid #1E1E2E;border-radius:6px;padding:10px;">
<div style="color:#E0E0F0;font-weight:600;margin-bottom:6px;">SSH</div>
<div style="display:flex;gap:4px;margin-bottom:4px;">
<input id="dc-ssh-user" placeholder="Benutzer" style="flex:2;">
<input id="dc-ssh-port" placeholder="Port 22" style="flex:1;">
</div>
<input id="dc-ssh-pass" type="password" placeholder="Passwort (oder Key unten)" style="width:100%;margin-bottom:4px;">
<textarea id="dc-ssh-key" placeholder="Privater SSH-Key (optional, PEM/OpenSSH)" style="width:100%;height:60px;font-family:monospace;font-size:10px;"></textarea>
</div>
<div style="display:flex;gap:8px;justify-content:flex-end;">
<button class="btn secondary" onclick="deleteDeviceCreds()" style="color:#FF6E6E;">Alle loeschen</button>
<button class="btn" onclick="saveDeviceCreds()">Speichern</button>
@@ -1457,6 +1467,22 @@
<div id="sat-list" style="font-size:12px;color:#8888AA;">(Lade...)</div>
</div>
<div style="display:flex;justify-content:space-between;align-items:center;margin:16px 0 8px;">
<h2 style="margin:0;">Host-Agenten 💻</h2>
<button class="btn secondary" onclick="requestHosts()" style="padding:4px 10px;font-size:11px;">Aktualisieren</button>
</div>
<div class="card" style="margin-bottom:8px;">
<p style="color:#8888AA;font-size:12px;margin:0;">
Agenten, die DIREKT auf einem Rechner laufen (Binary + <code>.env</code>) und
sich ausgehend mit RVS verbinden — ARIA steuert den Rechner damit auch
hinter NAT/Firewall. ARIA nutzt sie ueber <code>host_exec</code> &amp; Co.;
Setup siehe <code>host-agent/README</code>.
</p>
</div>
<div class="card">
<div id="host-list" style="font-size:12px;color:#8888AA;">(Lade...)</div>
</div>
<div id="compute-fleet" style="display:flex;justify-content:space-between;align-items:center;margin:16px 0 8px;scroll-margin-top:70px;">
<h2 style="margin:0;">Compute-Flotte 🖥️</h2>
<button class="btn secondary" onclick="requestWorkers()" style="padding:4px 10px;font-size:11px;">Aktualisieren</button>
@@ -2128,6 +2154,7 @@
satellites.forEach(s => { if (s.online !== false) requestSatCreds(s.id); });
return;
}
if (msg.type === 'host_update') { hosts = msg.hosts || []; renderHosts(); return; }
if (msg.type === 'sat_creds_list_result') {
const p = msg.payload || msg;
const sat = p.satellite || '';
@@ -4416,6 +4443,7 @@
loadTriggers();
} else if (tab === 'satellites') {
requestSatellites();
requestHosts();
requestWorkers();
}
}
@@ -4547,6 +4575,29 @@
function requestSatCreds(id) {
send({ action: 'sat_creds_list', satellite: id });
}
let hosts = []; // [{hostId, name, os, caps, control, online}]
function requestHosts() { send({ action: 'host_list' }); }
function renderHosts() {
const box = document.getElementById('host-list');
if (!box) return;
if (!hosts.length) {
box.innerHTML = '<span style="color:#8888AA;">Kein Host-Agent verbunden. ' +
'Baue die Binary (<code>host-agent/build.sh</code>), leg eine <code>.env</code> ' +
'daneben und starte sie auf dem Ziel-Rechner.</span>';
return;
}
box.innerHTML = hosts.map(h => {
const dot = h.online ? '#34C759' : '#FF3B30';
const caps = (h.caps || []).join(', ') || '—';
const ctrl = h.control ? '<span style="color:#0096FF;">steuerbar</span>' : '<span style="color:#FF6E6E;">CONTROL_ENABLED=false</span>';
return '<div style="border:1px solid #1E1E2E;border-radius:8px;padding:10px;margin-bottom:8px;">' +
'<div><span style="display:inline-block;width:8px;height:8px;border-radius:50%;background:' + dot + ';margin-right:6px;"></span>' +
'<strong style="color:#E0E0F0;">💻 ' + escapeHtml(h.name || h.hostId) + '</strong> ' +
'<span style="color:#666;font-size:11px;">id=' + escapeHtml(h.hostId) + '</span></div>' +
'<div style="color:#8888AA;font-size:11px;margin-top:4px;">' + escapeHtml(h.os || '') + ' · kann: ' + escapeHtml(caps) + ' · ' + ctrl + '</div>' +
'</div>';
}).join('');
}
function scanSatellite(id) {
satScanning = id;
renderSatellites();
@@ -4624,7 +4675,7 @@
credsModalSat = satId; credsModalIp = ip;
document.getElementById('dev-creds-title').textContent = (name || ip) + ' (' + ip + ')';
// Felder leeren — Secrets werden NIE zurueckgeliefert, nur neu gesetzt.
['dc-snmp-community','dc-v3-user','dc-v3-authkey','dc-v3-privkey','dc-http-user','dc-http-pass','dc-fb-user','dc-fb-pass'].forEach(id => document.getElementById(id).value = '');
['dc-snmp-community','dc-v3-user','dc-v3-authkey','dc-v3-privkey','dc-http-user','dc-http-pass','dc-fb-user','dc-fb-pass','dc-ssh-user','dc-ssh-port','dc-ssh-pass','dc-ssh-key'].forEach(id => document.getElementById(id).value = '');
document.getElementById('dc-snmp-version').value = '';
dcToggleV3();
const set = ((satCreds[satId] || {})[ip]) || [];
@@ -4656,7 +4707,18 @@
const fu = document.getElementById('dc-fb-user').value.trim();
const fp = document.getElementById('dc-fb-pass').value;
if (fu || fp) creds.fritzbox = { user: fu, pass: fp };
if (!Object.keys(creds).length) { document.getElementById('dc-status').textContent = 'Nichts zu speichern — mindestens einen Typ ausfuellen.'; return; }
// SSH: Benutzer + (Passwort ODER Key). Port optional.
const su = document.getElementById('dc-ssh-user').value.trim();
const sp = document.getElementById('dc-ssh-pass').value;
const sk = document.getElementById('dc-ssh-key').value.trim();
if (su && (sp || sk)) {
creds.ssh = { user: su };
if (sp) creds.ssh.pass = sp;
if (sk) creds.ssh.key = sk;
const sport = document.getElementById('dc-ssh-port').value.trim();
if (sport) creds.ssh.port = sport;
}
if (!Object.keys(creds).length) { document.getElementById('dc-status').textContent = 'Nichts zu speichern — mindestens einen Typ ausfuellen (SSH braucht Benutzer + Passwort/Key).'; return; }
send({ action: 'sat_creds_set', satellite: credsModalSat, ip: credsModalIp, creds });
document.getElementById('dc-status').textContent = 'Speichere …';
}
+35
View File
@@ -550,6 +550,21 @@ function broadcastSatellites() {
broadcast({ type: "sat_update", satellites: satelliteList() });
}
// ── Host-Agenten: Direktzugriff auf einen Rechner ────────────────
const hosts = new Map(); // hostId → {hostId, name, os, caps, control, last_seen}
function hostList() {
const now = Date.now();
return Array.from(hosts.values()).map(h => ({
hostId: h.hostId, name: h.name, os: h.os, caps: h.caps, control: h.control,
online: (now - (h.last_seen || 0)) < 300000,
}));
}
function broadcastHosts() {
broadcast({ type: "host_update", hosts: hostList() });
}
// ── Compute-Fleet: GPU-Worker (voxtral/whisper/f5tts/llm) ──────────
// Worker melden sich per worker_hello + halten sich per worker_ping (busy) frisch.
const workers = new Map(); // instanceId → {instanceId, service, node, gpus, model, busy, last_seen}
@@ -1065,6 +1080,21 @@ function connectRVS(forcePlain) {
});
broadcastSatellites();
}
} else if (msg.type === "host_hello") {
// Ein Host-Agent (Direktzugriff auf einen Rechner) meldet sich.
const p = msg.payload || {};
if (p.hostId) {
const wasKnown = hosts.has(p.hostId);
hosts.set(p.hostId, {
hostId: p.hostId, name: p.name || p.hostId, os: p.os || "",
caps: p.caps || [], control: !!p.control, last_seen: Date.now(),
});
if (!wasKnown) broadcastHosts();
else hosts.get(p.hostId).last_seen = Date.now();
}
} else if (msg.type === "host_ping") {
const p = msg.payload || {};
if (p.hostId && hosts.has(p.hostId)) hosts.get(p.hostId).last_seen = Date.now();
} else if (msg.type === "sat_devices") {
// Antwort eines Satelliten auf sat_discover → Geraeteliste an Browser.
const p = msg.payload || {};
@@ -2721,6 +2751,8 @@ wss.on("connection", (ws) => {
if (currentDiskStatus) ws.send(JSON.stringify(currentDiskStatus));
// Aktuell bekannte Satelliten mitgeben (RVS replayt sat_hello nicht).
ws.send(JSON.stringify({ type: "sat_update", satellites: satelliteList() }));
// Aktuell bekannte Host-Agenten mitgeben.
ws.send(JSON.stringify({ type: "host_update", hosts: hostList() }));
// Aktuell bekannte Compute-Worker mitgeben (RVS replayt worker_hello nicht).
ws.send(JSON.stringify({ type: "worker_update", workers: workerList() }));
@@ -2754,6 +2786,9 @@ wss.on("connection", (ws) => {
} else if (msg.action === "sat_list") {
// Browser will die aktuelle Satelliten-Liste.
ws.send(JSON.stringify({ type: "sat_update", satellites: satelliteList() }));
} else if (msg.action === "host_list") {
// Browser will die aktuelle Host-Agenten-Liste.
ws.send(JSON.stringify({ type: "host_update", hosts: hostList() }));
} else if (msg.action === "worker_list") {
// Browser will die aktuelle Compute-Flotte.
ws.send(JSON.stringify({ type: "worker_update", workers: workerList() }));
+31
View File
@@ -0,0 +1,31 @@
# ─── ARIA Host-Agent — Konfiguration ───────────────────────────────
# Kopiere diese Datei nach .env (neben die Binary) und passe sie an.
# RVS-Zugang (identisch zum Haupt-Stack — gleicher Raum/Token, damit ARIA
# diesen Rechner erreicht). Werte aus der Haupt-.env.
RVS_HOST=rvs.example.de
RVS_PORT=443
RVS_TLS=true
RVS_TOKEN=
# ─── Identitaet dieses Rechners ────────────────────────────────────
# HOST_ID = technisch eindeutig (a-z0-9-_), Default = Hostname-Slug.
# HOST_NAME = menschlicher Name, so spricht ARIA den Rechner an ("Stefans Laptop").
HOST_ID=
HOST_NAME=
# ─── Steuerung (Sicherheit!) ───────────────────────────────────────
# MUSS auf true, sonst fuehrt der Agent nichts aus (reiner Idle-Client).
CONTROL_ENABLED=true
# ─── sudo ──────────────────────────────────────────────────────────
# Reihenfolge: 1) Agent laeuft als root -> braucht kein sudo. 2) SUDO_PASSWORD
# gesetzt -> sudo -S mit Passwort. 3) SUDO_NOPASSWD=true -> sudo -n (Live-ISO /
# passwortloses sudo, z.B. Linux Mint vom Stick). 4) sonst schlaegt sudo fehl.
SUDO_PASSWORD=
SUDO_NOPASSWD=false
# ─── Limits (optional) ─────────────────────────────────────────────
EXEC_TIMEOUT=60 # max. Laufzeit eines Kommandos (s)
OUT_MAX_CHARS=20000 # stdout-Ausschnitt (offset/max_chars pro Request)
FILE_MAX_BYTES=10485760 # max. Datei-Transfer (10 MB)
+5
View File
@@ -0,0 +1,5 @@
.env
build/
dist/
*.spec
__pycache__/
+18
View File
@@ -0,0 +1,18 @@
# Baut die Host-Agent-Binary mit PyInstaller in einem Container mit ALTEM glibc
# (bullseye, glibc 2.31), damit die Onefile-Binary auf moeglichst vielen Linux-
# Distributionen laeuft (glibc ist abwaerts-, nicht aufwaertskompatibel).
FROM python:3.11-slim-bullseye
WORKDIR /build
RUN pip install --no-cache-dir pyinstaller
COPY requirements.txt .
RUN pip install --no-cache-dir -r requirements.txt
COPY host_agent.py .
# Onefile-Binary; psutil-Hidden-Imports werden von PyInstaller erkannt.
RUN pyinstaller --onefile --name aria-host-agent \
--collect-all psutil \
host_agent.py
# Ergebnis liegt in /build/dist/aria-host-agent
CMD ["sh", "-c", "cp /build/dist/aria-host-agent /out/ && echo 'Binary -> /out/aria-host-agent'"]
+62
View File
@@ -0,0 +1,62 @@
# ARIA Host-Agent
Ein schlanker Agent, der **direkt auf einem Rechner** läuft und ARIA erlaubt,
diesen Rechner zu steuern — auch wenn er sonst aus dem Netz **nicht erreichbar**
ist (hinter NAT/Firewall, kein offener Port). Der Agent verbindet sich
**ausgehend** zum RVS (gleicher Token wie der Rest von ARIA).
Unterschied zum **Satelliten**: der Satellit entdeckt und steuert *andere*
Geräte in einem LAN; der Host-Agent steuert *den Rechner, auf dem er läuft*.
## Fähigkeiten
| Aktion | Was |
|--------------|-----|
| `exec` | Shell-Kommando ausführen (optional `sudo`), stdout/stderr/exit |
| `read` | Datei lesen (Base64, mit Offset/Limit) |
| `write` | Datei schreiben/anhängen (Base64 oder Text) |
| `info` | OS, CPU/RAM/Disk-Auslastung, Uptime, IP |
| `screenshot` | Bildschirmfoto (X11: scrot/maim · Wayland: grim) |
ARIA nutzt diese über die Brain-Tools `host_list` / `host_exec` / `host_read` /
`host_write` / `host_info` / `host_screenshot`.
## Bauen (portable Binary)
```bash
./build.sh # braucht Docker; erzeugt dist/aria-host-agent (~15 MB)
```
Gebaut wird in einem bullseye-Container (altes glibc), damit die Binary auf
möglichst vielen Distributionen läuft.
## Installieren
1. `dist/aria-host-agent` auf den Ziel-Rechner kopieren.
2. `.env.example` → `.env` daneben, RVS-Zugang + `CONTROL_ENABLED=true` eintragen.
3. Starten: `chmod +x aria-host-agent && ./aria-host-agent`
— oder als Dienst: siehe `aria-host-agent.service`.
## sudo
Vier Fälle, der Agent wählt automatisch:
1. **Agent läuft als root** (z.B. systemd `User=root`) → volle Rechte, kein sudo nötig.
2. `SUDO_PASSWORD=…` in der `.env` → `sudo -S` mit Passwort.
3. `SUDO_NOPASSWD=true` → `sudo -n` (Live-ISO / passwortloses sudo, z.B. Linux
Mint vom Stick).
4. sonst → sudo-Kommandos scheitern mit klarer Meldung.
## Sicherheit
- Reagiert **nur** auf den eigenen RVS-Raum (Token) und **nur**, wenn
`CONTROL_ENABLED=true`.
- Keine offenen Ports (reiner ausgehender Client).
- Alle Kommandos werden geloggt.
- Der Agent gibt **vollen** Zugriff auf den Rechner — nur auf Maschinen
einsetzen, denen du ARIA anvertraust.
## Hinweis Screenshot
Als Systemdienst fehlt die grafische Session. Für `screenshot` den Agent in der
Desktop-Session starten (Autostart) oder `DISPLAY`/`XAUTHORITY` in der Unit setzen.
+30
View File
@@ -0,0 +1,30 @@
# systemd-Unit fuer den ARIA Host-Agent.
#
# Installation:
# sudo cp aria-host-agent /usr/local/bin/
# sudo mkdir -p /etc/aria-host-agent && sudo cp .env /etc/aria-host-agent/.env
# sudo cp aria-host-agent.service /etc/systemd/system/
# sudo systemctl enable --now aria-host-agent
#
# Als root (User=root): Kommandos haben volle Rechte, kein sudo/Passwort noetig.
# Fuer einen normalen User: User=<name> setzen und in der .env SUDO_PASSWORD
# oder SUDO_NOPASSWD konfigurieren.
#
# HINWEIS Screenshot: als Systemdienst fehlt die grafische Session (DISPLAY/
# WAYLAND_DISPLAY). Fuer host_screenshot den Agent stattdessen in der Desktop-
# Session starten (Autostart) oder DISPLAY/XAUTHORITY in der Unit setzen.
[Unit]
Description=ARIA Host-Agent
After=network-online.target
Wants=network-online.target
[Service]
Type=simple
User=root
WorkingDirectory=/etc/aria-host-agent
ExecStart=/usr/local/bin/aria-host-agent
Restart=always
RestartSec=5
[Install]
WantedBy=multi-user.target
+19
View File
@@ -0,0 +1,19 @@
#!/usr/bin/env bash
# Baut die portable Host-Agent-Binary (Linux x86_64) via Docker + PyInstaller.
# Ergebnis: ./dist/aria-host-agent (Onefile, ~15 MB, keine Runtime noetig).
#
# ./build.sh
#
# Danach auf den Ziel-Rechner kopieren, .env danebenlegen und starten:
# ./aria-host-agent
set -euo pipefail
cd "$(dirname "$0")"
mkdir -p dist
docker build -f Dockerfile.build -t aria-host-agent-build .
docker run --rm -v "$(pwd)/dist:/out" aria-host-agent-build
echo
echo "Fertig: dist/aria-host-agent"
echo "Auf den Ziel-Rechner kopieren, .env danebenlegen (siehe .env.example), dann:"
echo " chmod +x aria-host-agent && ./aria-host-agent"
+437
View File
@@ -0,0 +1,437 @@
"""
ARIA Host-Agent — Direktzugriff auf EINEN Rechner.
Laeuft direkt auf dem Ziel-Rechner (Linux) und verbindet sich AUSGEHEND als
RVS-Client in Stefans Raum (gleicher Token). Damit kann ARIA diesen Rechner
direkt steuern, auch wenn er sonst aus dem Netz nicht erreichbar ist (hinter
NAT/Firewall, kein offener Port). Anders als der Satellit (der ein LAN
entdeckt/steuert) ist beim Agent das "Geraet" der Rechner selbst.
Als reine Binary verteilbar (PyInstaller onefile) + .env fuer die Zugangsdaten.
Faehigkeiten (host_command → host_result):
exec Shell-Kommando ausfuehren (optional sudo)
read/write Datei lesen/schreiben (Base64)
info OS / CPU / RAM / Disk / Uptime / Netz
screenshot Bildschirmfoto (X11/Wayland, wenn grafische Session da ist)
Sicherheit: reagiert nur auf den eigenen RVS-Raum (Token) und nur, wenn
CONTROL_ENABLED=true. Alles wird geloggt. Keine offenen Ports.
"""
from __future__ import annotations
import asyncio
import base64
import json
import logging
import os
import platform
import re
import shutil
import socket
import subprocess
import time
from pathlib import Path
import websockets
logging.basicConfig(
level=logging.INFO,
format="%(asctime)s [host-agent] %(levelname)s %(message)s",
)
logger = logging.getLogger("host-agent")
def _load_dotenv() -> None:
"""Laedt eine .env neben der Binary/dem Script (oder im CWD) in os.environ.
Bereits gesetzte Werte gewinnen. Kein python-dotenv noetig."""
here = os.path.dirname(os.path.abspath(__file__))
for path in (os.path.join(here, ".env"), os.path.join(os.getcwd(), ".env")):
if not os.path.isfile(path):
continue
try:
with open(path, "r", encoding="utf-8") as f:
for line in f:
line = line.strip()
if not line or line.startswith("#") or "=" not in line:
continue
key, _, val = line.partition("=")
key = key.strip()
if key.startswith("export "):
key = key[len("export "):].strip()
val = val.strip()
if val[:1] in ("'", '"'):
q = val[0]
end = val.find(q, 1)
val = val[1:end] if end != -1 else val[1:]
else:
m = re.search(r"\s+#", val)
if m:
val = val[:m.start()]
val = val.strip()
if key and key not in os.environ:
os.environ[key] = val
except Exception as exc:
logger.warning(".env laden fehlgeschlagen (%s): %s", path, exc)
break
_load_dotenv()
# ─── Konfiguration ──────────────────────────────────────────────────
def _env_bool(name: str, default: bool) -> bool:
v = os.environ.get(name)
if v is None:
return default
return v.strip().lower() in ("1", "true", "yes", "on", "ja")
def _default_id() -> str:
host = socket.gethostname() or "host"
slug = re.sub(r"[^a-zA-Z0-9_-]+", "-", host).strip("-").lower()
return slug or "host"
RVS_HOST = os.environ.get("RVS_HOST", "")
RVS_PORT = int(os.environ.get("RVS_PORT", "443") or "443")
RVS_TLS = _env_bool("RVS_TLS", True)
RVS_TOKEN = os.environ.get("RVS_TOKEN", "")
HOST_ID = (os.environ.get("HOST_ID") or _default_id()).strip()
HOST_NAME = (os.environ.get("HOST_NAME") or HOST_ID).strip()
# Steuerung ist der Sinn des Agents — aber bewusst opt-in (Sicherheit).
CONTROL_ENABLED = _env_bool("CONTROL_ENABLED", False)
# sudo: 1) Agent laeuft als root -> direkt. 2) SUDO_PASSWORD gesetzt -> sudo -S.
# 3) SUDO_NOPASSWD=true (Live-ISO / NOPASSWD-sudoers) -> sudo -n. 4) sonst Fehler.
SUDO_PASSWORD = os.environ.get("SUDO_PASSWORD", "")
SUDO_NOPASSWD = _env_bool("SUDO_NOPASSWD", False)
EXEC_TIMEOUT = float(os.environ.get("EXEC_TIMEOUT", "60") or "60")
# Ausgabe-Fenster (wie beim Satelliten): grosse stdout klein halten fuers RVS.
OUT_MAX_CHARS = int(os.environ.get("OUT_MAX_CHARS", "20000") or "20000")
OUT_MAX_CHARS_HARD = int(os.environ.get("OUT_MAX_CHARS_HARD", "200000") or "200000")
# Datei-Transfer-Limit (Base64 durchs RVS).
FILE_MAX_BYTES = int(os.environ.get("FILE_MAX_BYTES", str(10 * 1024 * 1024)) or str(10 * 1024 * 1024))
HEARTBEAT_SEC = 25
CAPS = ["exec", "read", "write", "info", "screenshot"]
# ─── Text-/Zahl-Helfer ──────────────────────────────────────────────
def _to_int(s):
try:
return int(str(s).strip())
except (TypeError, ValueError):
return None
def _to_float(s):
try:
return float(str(s).strip())
except (TypeError, ValueError):
return None
def _window_text(text: str, params: dict) -> dict:
"""contains-Zeilenfilter + offset/max_chars-Fenster. Gibt body + Metadaten."""
total = len(text)
contains = params.get("contains")
if contains:
terms = [contains] if isinstance(contains, str) else list(contains)
terms = [str(t).lower() for t in terms if str(t).strip()]
if terms:
text = "\n".join(ln for ln in text.splitlines()
if any(t in ln.lower() for t in terms))
offset = max(0, _to_int(params.get("offset")) or 0)
max_chars = _to_int(params.get("max_chars")) or OUT_MAX_CHARS
max_chars = max(1, min(max_chars, OUT_MAX_CHARS_HARD))
body = text[offset:offset + max_chars]
return {"body": body, "total_chars": total, "filtered": bool(contains),
"offset": offset, "returned_chars": len(body),
"truncated": offset + len(body) < len(text)}
# ─── Aktionen ───────────────────────────────────────────────────────
def _wrap_sudo(cmd: str, use_sudo: bool):
"""Gibt (argv, stdin_data) oder (None, fehlertext) wenn sudo nicht moeglich."""
if not use_sudo or os.geteuid() == 0:
return ["bash", "-lc", cmd], None
if SUDO_PASSWORD:
return ["sudo", "-S", "-p", "", "bash", "-lc", cmd], SUDO_PASSWORD + "\n"
if SUDO_NOPASSWD:
return ["sudo", "-n", "bash", "-lc", cmd], None
return None, ("sudo verlangt ein Passwort. Setze SUDO_PASSWORD in der .env, "
"oder SUDO_NOPASSWD=true (Live-ISO / passwortloses sudo), oder "
"starte den Agent als root.")
def _do_exec(params: dict) -> dict:
cmd = params.get("cmd") or params.get("command") or ""
if not cmd:
return {"ok": False, "error": "cmd (Kommando) erforderlich."}
argv, stdin_data = _wrap_sudo(cmd, bool(params.get("sudo")))
if argv is None:
return {"ok": False, "error": stdin_data}
timeout = _to_float(params.get("timeout")) or EXEC_TIMEOUT
try:
r = subprocess.run(argv, input=stdin_data, capture_output=True,
text=True, timeout=timeout)
except subprocess.TimeoutExpired:
return {"ok": False, "error": f"Timeout nach {timeout:.0f}s."}
except Exception as exc:
return {"ok": False, "error": f"exec fehlgeschlagen: {exc}"}
win = _window_text(r.stdout, params)
return {"ok": True, "result": {"exit_code": r.returncode,
"stderr": (r.stderr or "")[:4000], **win}}
def _do_read(params: dict) -> dict:
path = params.get("path") or ""
if not path:
return {"ok": False, "error": "path erforderlich."}
p = Path(path).expanduser()
if not p.is_file():
return {"ok": False, "error": f"Datei nicht gefunden: {path}"}
size = p.stat().st_size
offset = max(0, _to_int(params.get("offset")) or 0)
max_bytes = _to_int(params.get("max_bytes")) or FILE_MAX_BYTES
max_bytes = max(1, min(max_bytes, FILE_MAX_BYTES))
try:
with p.open("rb") as f:
f.seek(offset)
data = f.read(max_bytes)
except Exception as exc:
return {"ok": False, "error": f"Lesen fehlgeschlagen: {exc}"}
return {"ok": True, "result": {
"path": str(p), "size": size, "offset": offset,
"returned_bytes": len(data), "truncated": offset + len(data) < size,
"base64": base64.b64encode(data).decode("ascii"),
}}
def _do_write(params: dict) -> dict:
path = params.get("path") or ""
if not path:
return {"ok": False, "error": "path erforderlich."}
b64 = params.get("base64")
text = params.get("text")
if b64 is None and text is None:
return {"ok": False, "error": "base64 ODER text erforderlich."}
try:
data = base64.b64decode(b64) if b64 is not None else str(text).encode("utf-8")
except Exception as exc:
return {"ok": False, "error": f"base64 ungueltig: {exc}"}
p = Path(path).expanduser()
try:
p.parent.mkdir(parents=True, exist_ok=True)
mode = "ab" if params.get("append") else "wb"
with p.open(mode) as f:
f.write(data)
if params.get("chmod"):
os.chmod(p, int(str(params["chmod"]), 8))
except Exception as exc:
return {"ok": False, "error": f"Schreiben fehlgeschlagen: {exc}"}
return {"ok": True, "result": {"path": str(p), "bytes": len(data)}}
def _do_info(params: dict) -> dict:
info = {
"host": HOST_NAME, "hostname": socket.gethostname(),
"os": platform.platform(), "kernel": platform.release(),
"arch": platform.machine(), "python": platform.python_version(),
"user": os.environ.get("USER") or "", "is_root": os.geteuid() == 0,
}
try:
import psutil
info["cpu_percent"] = psutil.cpu_percent(interval=0.3)
info["cpu_count"] = psutil.cpu_count()
vm = psutil.virtual_memory()
info["ram_used_mb"] = round(vm.used / 1024 / 1024)
info["ram_total_mb"] = round(vm.total / 1024 / 1024)
info["ram_percent"] = vm.percent
du = psutil.disk_usage("/")
info["disk_used_gb"] = round(du.used / 1024 / 1024 / 1024, 1)
info["disk_total_gb"] = round(du.total / 1024 / 1024 / 1024, 1)
info["disk_percent"] = du.percent
info["uptime_s"] = round(time.time() - psutil.boot_time())
info["load_avg"] = list(os.getloadavg()) if hasattr(os, "getloadavg") else None
except Exception:
# Fallback ohne psutil: das Noetigste aus os/shutil.
try:
info["load_avg"] = list(os.getloadavg())
except Exception:
info["load_avg"] = None
try:
total, used, free = shutil.disk_usage("/")
info["disk_used_gb"] = round(used / 1024 ** 3, 1)
info["disk_total_gb"] = round(total / 1024 ** 3, 1)
except Exception:
pass
# Primaere IP (best effort).
try:
s = socket.socket(socket.AF_INET, socket.SOCK_DGRAM)
s.connect(("8.8.8.8", 80))
info["primary_ip"] = s.getsockname()[0]
s.close()
except Exception:
info["primary_ip"] = ""
return {"ok": True, "result": info}
def _do_screenshot(params: dict) -> dict:
"""Bildschirmfoto via System-Tool (Wayland: grim; X11: scrot/maim/import/
gnome-screenshot). Braucht eine aktive grafische Session (DISPLAY/WAYLAND)."""
import tempfile
tmp = os.path.join(tempfile.gettempdir(), f"aria_shot_{int(time.time())}.png")
wayland = bool(os.environ.get("WAYLAND_DISPLAY"))
candidates = []
if wayland and shutil.which("grim"):
candidates.append(["grim", tmp])
for tool, argv in (("scrot", ["scrot", "-o", tmp]),
("maim", ["maim", tmp]),
("gnome-screenshot", ["gnome-screenshot", "-f", tmp]),
("import", ["import", "-window", "root", tmp])):
if shutil.which(tool):
candidates.append(argv)
if not candidates:
return {"ok": False, "error":
"Kein Screenshot-Tool gefunden. Installiere grim (Wayland) oder "
"scrot/maim (X11)."}
last_err = ""
for argv in candidates:
try:
r = subprocess.run(argv, capture_output=True, text=True, timeout=15)
if r.returncode == 0 and os.path.isfile(tmp) and os.path.getsize(tmp) > 0:
with open(tmp, "rb") as f:
b = f.read()
os.remove(tmp)
return {"ok": True, "result": {"format": "png", "bytes": len(b),
"base64": base64.b64encode(b).decode("ascii")}}
last_err = (r.stderr or r.stdout or "").strip()[:200]
except Exception as exc:
last_err = str(exc)[:200]
return {"ok": False, "error": f"Screenshot fehlgeschlagen ({last_err}). "
"Laeuft der Agent in derselben grafischen Session?"}
ACTIONS = {
"exec": _do_exec, "read": _do_read, "write": _do_write,
"info": _do_info, "screenshot": _do_screenshot,
}
# ─── RVS-Client ─────────────────────────────────────────────────────
class HostAgent:
def __init__(self) -> None:
self.ws = None
def _for_me(self, payload: dict) -> bool:
"""Command gilt uns, wenn kein host-Feld gesetzt ist (Broadcast) oder es
auf unsere ID/Name passt."""
target = (payload.get("host") or payload.get("hostId") or "").strip()
if not target:
return True
return target.lower() in (HOST_ID.lower(), HOST_NAME.lower())
async def _send(self, message: dict) -> None:
if self.ws is None:
return
try:
await self.ws.send(json.dumps(message))
except Exception as exc:
logger.warning("Senden fehlgeschlagen: %s", exc)
async def _hello(self, log: bool = False) -> None:
if log:
logger.info("host_hello: id=%s name=%s caps=%s control=%s",
HOST_ID, HOST_NAME, ",".join(CAPS), CONTROL_ENABLED)
await self._send({"type": "host_hello", "payload": {
"hostId": HOST_ID, "name": HOST_NAME, "os": platform.platform(),
"caps": CAPS, "control": CONTROL_ENABLED,
}, "timestamp": int(time.time() * 1000)})
async def _heartbeat(self) -> None:
while True:
await asyncio.sleep(HEARTBEAT_SEC)
await self._send({"type": "host_ping", "payload": {"hostId": HOST_ID},
"timestamp": int(time.time() * 1000)})
await self._hello()
async def _handle(self, raw: str) -> None:
try:
msg = json.loads(raw)
except Exception:
return
if msg.get("type") != "host_command":
return
payload = msg.get("payload") or {}
if not self._for_me(payload):
return
req_id = payload.get("requestId", "")
action = (payload.get("action") or "").strip()
params = payload.get("params") or {}
if not CONTROL_ENABLED:
result = {"ok": False, "error": "Steuerung ist deaktiviert (CONTROL_ENABLED=false)."}
elif action not in ACTIONS:
result = {"ok": False, "error": f"Aktion '{action}' unbekannt (bekannt: {', '.join(ACTIONS)})."}
else:
logger.info("[cmd] %s params=%s", action,
{k: str(v)[:60] for k, v in params.items() if k not in ("base64",)})
loop = asyncio.get_event_loop()
try:
result = await loop.run_in_executor(None, ACTIONS[action], params)
except Exception as exc:
result = {"ok": False, "error": f"{action} fehlgeschlagen: {exc}"}
await self._send({"type": "host_result",
"payload": {"requestId": req_id, "hostId": HOST_ID,
"action": action, **result},
"timestamp": int(time.time() * 1000)})
async def run(self) -> None:
if not RVS_HOST or not RVS_TOKEN:
logger.error("RVS_HOST und RVS_TOKEN sind Pflicht (siehe .env.example).")
return
backoff = 1
while True:
proto = "wss" if RVS_TLS else "ws"
url = f"{proto}://{RVS_HOST}:{RVS_PORT}?token={RVS_TOKEN}"
try:
logger.info("Verbinde mit RVS %s://%s:%s …", proto, RVS_HOST, RVS_PORT)
async with websockets.connect(url, max_size=16 * 1024 * 1024,
ping_interval=20, ping_timeout=20) as ws:
self.ws = ws
backoff = 1
await self._hello(log=True)
hb = asyncio.create_task(self._heartbeat())
try:
async for raw in ws:
await self._handle(raw)
finally:
hb.cancel()
except Exception as exc:
logger.warning("RVS-Verbindung verloren: %s", exc)
finally:
self.ws = None
await asyncio.sleep(backoff)
backoff = min(backoff * 2, 30)
def main() -> None:
logger.info("ARIA Host-Agent startet — id=%s name=%s control=%s root=%s",
HOST_ID, HOST_NAME, CONTROL_ENABLED, os.geteuid() == 0)
try:
asyncio.run(HostAgent().run())
except KeyboardInterrupt:
pass
if __name__ == "__main__":
main()
+2
View File
@@ -0,0 +1,2 @@
websockets>=12.0
psutil>=5.9 # System-Info (CPU/RAM/Disk/Uptime) fuer host_info
+4
View File
@@ -84,6 +84,10 @@ const ALLOWED_TYPES = new Set([
// (SNMP/HTTP/FritzBox), der Satellit speichert sie verschluesselt.
"sat_creds_set", "sat_creds_delete", "sat_creds_list",
"sat_creds_result", "sat_creds_list_result",
// Host-Agenten: ein Agent laeuft direkt auf einem Rechner, meldet sich mit
// host_hello/host_ping und fuehrt host_command aus (exec/read/write/info/
// screenshot) -> host_result. ARIA steuert so Rechner auch hinter NAT.
"host_hello", "host_ping", "host_command", "host_result",
// Compute-Flotte (AI-Boxen): Worker (f5tts/whisper/voxtral/llm-adapter) melden
// sich per worker_hello an und pingen per worker_ping; der Diagnostic-Server
// aggregiert das und broadcastet worker_update/worker_list an die Browser-UI.
+2 -1
View File
@@ -33,7 +33,8 @@ CONTROL_ENABLED=true
# snmp.info Modell/Seriennummer/Firmware-Version (params: ip)
# fritzbox.info FritzBox: Verbindung/Datenrate/externe IP (TR-064, braucht Login)
# fritzbox.hosts FritzBox: verbundene Geraete (TR-064, braucht Login)
CONTROL_ALLOWLIST=dial.launch,wol,http.get,snmp.get,snmp.walk,snmp.printer,snmp.ports,snmp.info,fritzbox.info,fritzbox.hosts
# ssh.exec Kommando per SSH ausfuehren (params: ip, cmd; Auth aus Creds 'ssh')
CONTROL_ALLOWLIST=dial.launch,wol,http.get,snmp.get,snmp.walk,snmp.printer,snmp.ports,snmp.info,fritzbox.info,fritzbox.hosts,ssh.exec
# ─── Credential-Store (optional) ───────────────────────────────────
# Pro Geraet koennen im Diagnostic Zugangsdaten hinterlegt werden (SNMP-Community/
+1
View File
@@ -2,3 +2,4 @@ websockets>=12.0
zeroconf>=0.131.0
requests>=2.31.0
cryptography>=42.0 # Verschluesselung des Geraete-Credential-Stores (Fernet)
paramiko>=3.4 # SSH-Client fuer ssh.exec (Passwort ODER Key)
+102 -37
View File
@@ -116,7 +116,7 @@ CONTROL_ALLOWLIST = [
a.strip() for a in
os.environ.get("CONTROL_ALLOWLIST",
"dial.launch,wol,http.get,snmp.get,snmp.walk,snmp.printer,"
"snmp.ports,snmp.info,fritzbox.info,fritzbox.hosts").split(",")
"snmp.ports,snmp.info,fritzbox.info,fritzbox.hosts,ssh.exec").split(",")
if a.strip()
]
@@ -131,6 +131,10 @@ HTTP_TIMEOUT_SEC = float(os.environ.get("HTTP_TIMEOUT_SEC", "10") or "10")
HTTP_MAX_CHARS = int(os.environ.get("HTTP_MAX_CHARS", "20000") or "20000")
HTTP_MAX_CHARS_HARD = int(os.environ.get("HTTP_MAX_CHARS_HARD", "200000") or "200000")
# SSH (ssh.exec): Verbindungs-/Kommando-Timeout. Auth aus dem Credential-Store
# (Typ 'ssh': user + pass ODER key). Default-Port 22, pro Request/Cred ueberschreibbar.
SSH_TIMEOUT_SEC = float(os.environ.get("SSH_TIMEOUT_SEC", "20") or "20")
# SNMP (net-snmp-CLI): Default-Community/Version + Timeout. Drucker antworten
# i.d.R. auf community 'public', v2c.
SNMP_COMMUNITY = os.environ.get("SNMP_COMMUNITY", "public") or "public"
@@ -228,7 +232,7 @@ def _creds_public_summary() -> list:
"""Fuer sat_creds_list: welche Geraete welche Cred-Typen haben — OHNE Secrets."""
out = []
for ip, entry in sorted(_CREDS.items()):
types = [t for t in ("snmp", "http", "fritzbox") if entry.get(t)]
types = [t for t in ("snmp", "http", "fritzbox", "ssh") if entry.get(t)]
out.append({"ip": ip, "types": types})
return out
@@ -541,6 +545,8 @@ async def _control(action: str, params: dict, devices: list[dict]) -> dict:
return await loop.run_in_executor(None, _do_snmp_info, params)
if action in ("fritzbox.info", "fritzbox.hosts"):
return await loop.run_in_executor(None, _do_fritzbox, action, params)
if action == "ssh.exec":
return await loop.run_in_executor(None, _do_ssh, params)
return {"ok": False, "error": f"Aktion '{action}' nicht implementiert."}
except Exception as exc:
return {"ok": False, "error": f"{action} fehlgeschlagen: {exc}"}
@@ -592,6 +598,32 @@ def _do_wol(params: dict) -> dict:
return {"ok": True, "result": f"Wake-on-LAN an {mac} gesendet."}
def _window_text(text: str, params: dict) -> dict:
"""Schneidet grosse Text-Ausgaben zu: optionaler contains-Zeilenfilter, dann
offset/max_chars-Fenster. Gibt body + Metadaten (total/returned/truncated)."""
total = len(text)
contains = params.get("contains")
if contains:
terms = [contains] if isinstance(contains, str) else list(contains)
terms = [str(t).lower() for t in terms if str(t).strip()]
if terms:
text = "\n".join(ln for ln in text.splitlines()
if any(t in ln.lower() for t in terms))
try:
offset = max(0, int(params.get("offset", 0)))
except (TypeError, ValueError):
offset = 0
try:
max_chars = int(params.get("max_chars", HTTP_MAX_CHARS))
except (TypeError, ValueError):
max_chars = HTTP_MAX_CHARS
max_chars = max(1, min(max_chars, HTTP_MAX_CHARS_HARD))
body = text[offset:offset + max_chars]
return {"body": body, "total_chars": total, "filtered": bool(contains),
"offset": offset, "returned_chars": len(body),
"truncated": offset + len(body) < len(text)}
def _do_http(action: str, params: dict) -> dict:
"""HTTP-GET/POST vom Satelliten aus (lokale Webhooks, Geraete-Statusseiten …).
@@ -627,40 +659,7 @@ def _do_http(action: str, params: dict) -> dict:
r = requests.request(method, url, data=params.get("body"),
headers=params.get("headers"), auth=auth,
timeout=HTTP_TIMEOUT_SEC)
text = r.text
total = len(text)
contains = params.get("contains")
if contains:
terms = [contains] if isinstance(contains, str) else list(contains)
terms = [str(t).lower() for t in terms if str(t).strip()]
if terms:
lines = [ln for ln in text.splitlines()
if any(t in ln.lower() for t in terms)]
text = "\n".join(lines)
try:
offset = max(0, int(params.get("offset", 0)))
except (TypeError, ValueError):
offset = 0
try:
max_chars = int(params.get("max_chars", HTTP_MAX_CHARS))
except (TypeError, ValueError):
max_chars = HTTP_MAX_CHARS
max_chars = max(1, min(max_chars, HTTP_MAX_CHARS_HARD))
body = text[offset:offset + max_chars]
returned_end = offset + len(body)
truncated = returned_end < len(text)
return {"ok": True, "result": {
"status": r.status_code,
"body": body,
"total_chars": total, # Groesse der Roh-Antwort
"filtered": bool(contains), # contains-Filter aktiv?
"offset": offset,
"returned_chars": len(body),
"truncated": truncated, # noch mehr Text nach diesem Ausschnitt?
}}
return {"ok": True, "result": {"status": r.status_code, **_window_text(r.text, params)}}
def _snmp_run(args: list, timeout: float) -> tuple:
@@ -963,6 +962,72 @@ def _do_fritzbox(action: str, params: dict) -> dict:
return {"ok": True, "result": info}
# ─── SSH ───────────────────────────────────────────────────────────
def _ssh_load_key(key_str: str):
"""Laedt einen privaten Schluessel aus einem String (RSA/Ed25519/ECDSA/DSS)."""
import io
import paramiko
for cls in (paramiko.Ed25519Key, paramiko.RSAKey, paramiko.ECDSAKey, paramiko.DSSKey):
try:
return cls.from_private_key(io.StringIO(key_str))
except Exception:
continue
return None
def _do_ssh(params: dict) -> dict:
"""Fuehrt EIN Kommando per SSH auf einem Geraet aus. params: {ip|host, cmd,
user?, pass?, key?, port?}. Auth bevorzugt aus dem Credential-Store (Typ 'ssh').
Grosse Ausgaben werden wie bei http.get gefenstert (contains/offset/max_chars)."""
import paramiko
host = _snmp_target(params)
if not host:
return {"ok": False, "error": "ip/host erforderlich."}
cmd = params.get("cmd") or params.get("command") or ""
if not cmd:
return {"ok": False, "error": "cmd (Kommando) erforderlich."}
creds = _creds_for(host).get("ssh", {})
user = str(params.get("user") or creds.get("user") or "")
if not user:
return {"ok": False, "error": "SSH-Benutzer fehlt (Credentials fuer diese IP setzen)."}
port = _to_int(params.get("port") or creds.get("port")) or 22
password = params.get("pass") or params.get("password") or creds.get("pass")
key_str = params.get("key") or creds.get("key")
client = paramiko.SSHClient()
client.set_missing_host_key_policy(paramiko.AutoAddPolicy())
try:
kwargs = {"hostname": host, "port": port, "username": user,
"timeout": SSH_TIMEOUT_SEC, "banner_timeout": SSH_TIMEOUT_SEC,
"auth_timeout": SSH_TIMEOUT_SEC, "allow_agent": False,
"look_for_keys": False}
if key_str:
pkey = _ssh_load_key(str(key_str))
if pkey is None:
return {"ok": False, "error": "Privater SSH-Key nicht lesbar (Format?)."}
kwargs["pkey"] = pkey
if password:
kwargs["password"] = str(password)
client.connect(**kwargs)
stdin, stdout, stderr = client.exec_command(cmd, timeout=SSH_TIMEOUT_SEC)
exit_code = stdout.channel.recv_exit_status()
out = stdout.read().decode("utf-8", "ignore")
err = stderr.read().decode("utf-8", "ignore")
except paramiko.AuthenticationException:
return {"ok": False, "error": "SSH-Auth fehlgeschlagen (User/Passwort/Key pruefen)."}
except Exception as exc:
return {"ok": False, "error": f"SSH fehlgeschlagen: {exc}"}
finally:
try:
client.close()
except Exception:
pass
win = _window_text(out, params)
return {"ok": True, "result": {"host": host, "exit_code": exit_code,
"stderr": err[:4000], **win}}
def _to_int(s: str):
try:
return int(str(s).strip())
@@ -1178,7 +1243,7 @@ class Satellite:
ok = False
if ip and isinstance(creds, dict):
entry = _CREDS.setdefault(ip, {})
for t in ("snmp", "http", "fritzbox"):
for t in ("snmp", "http", "fritzbox", "ssh"):
if t in creds:
if creds[t]: # leeres Objekt = Typ loeschen
entry[t] = creds[t]