> For the complete documentation index, see [llms.txt](https://docs.clore.ai/llms.txt). Markdown versions of documentation pages are available by appending `.md` to page URLs; this page is available as [Markdown](https://docs.clore.ai/guides/guides_v2-de/erweitert/cli-automation.md).

# CLI-Automatisierung

{% hint style="success" %}
**Voraussetzungen:** Installieren Sie das SDK (`pip install clore-ai`) und konfigurieren Sie Ihren API-Schlüssel. Siehe das [Python Quickstart](/guides/guides_v2-de/erste-schritte/python-quickstart.md) falls Sie es noch nicht getan haben.
{% endhint %}

## Grundlegender Arbeitsablauf

Die Kernschleife: **suchen → bereitstellen → verbinden → abbrechen**.

```bash
# 1. Finde eine GPU
clore search --gpu "RTX 4090" --max-price 2.0 --sort price --limit 5

# 2. Bereitstellen (verwenden Sie eine Server-ID aus Schritt 1)
clore deploy 142 \
  --image cloreai/ubuntu22.04-cuda12 \
  --type on-demand \
  --currency bitcoin \
  --ssh-password MySecurePass \
  --port 22:tcp \
  --port 8888:http

# 3. Überprüfen Sie Ihre Bestellungen
clore orders

# 4. SSH in den Server
clore ssh 38

# 5. Abbrechen, wenn fertig
clore cancel 38

# 6. Wallet-Guthaben prüfen
clore wallets
```

***

## CLI-Befehlsreferenz

| Befehl                                | Beschreibung                                               |
| ------------------------------------- | ---------------------------------------------------------- |
| `clore search`                        | GPU-Marktplatz durchsuchen                                 |
| `clore deploy <server_id>`            | Erstellen Sie eine neue Bestellung                         |
| `clore orders`                        | Aktive Bestellungen auflisten                              |
| `clore orders --completed`            | Alle Bestellungen einschließlich abgeschlossener auflisten |
| `clore ssh <order_id>`                | Per SSH in eine aktive Bestellung einloggen                |
| `clore cancel <order_id>`             | Eine Bestellung stornieren                                 |
| `clore wallets`                       | Wallet-Guthaben anzeigen                                   |
| `clore servers`                       | Ihre gehosteten Server auflisten                           |
| `clore server-config <name>`          | Serverkonfiguration anzeigen                               |
| `clore spot <server_id>`              | Spotmarkt für einen Server anzeigen                        |
| `clore spot-price <order_id> <price>` | Spotpreis für eine Bestellung festlegen                    |
| `clore config set <key> <value>`      | Konfigurationswert setzen                                  |
| `clore config get <key>`              | Konfigurationswert abrufen                                 |
| `clore config show`                   | Alle Konfigurationen anzeigen                              |

***

## Scripting mit der CLI

### Bereitstellen und auf SSH warten

```bash
#!/bin/bash
# deploy-and-connect.sh — Einen Server bereitstellen und sich per SSH verbinden, wenn er bereit ist

set -euo pipefail

SERVER_ID=${1:?Usage: $0 <server_id>}
IMAGE=${2:-cloreai/ubuntu22.04-cuda12}
PASSWORD="AutoDeploy$(date +%s)"

echo "🚀 Bereitstellung des Servers $SERVER_ID..."
clore deploy "$SERVER_ID" \
  --image "$IMAGE" \
  --type on-demand \
  --currency bitcoin \
  --ssh-password "$PASSWORD" \
  --port 22:tcp

echo "⏳ Warte darauf, dass die Bestellung bereit ist..."
sleep 15

echo "📦 Aktive Bestellungen:"
clore orders

echo ""
echo "🔑 SSH-Passwort: $PASSWORD"
echo "💡 Verbinden mit: clore ssh <order_id>"
```

### Günstigste GPU finden und bereitstellen

```bash
#!/bin/bash
# cheapest-gpu.sh — Finde und bereitstelle die günstigste GPU, die den Kriterien entspricht

GPU_MODEL=${1:-"RTX 4090"}
MAX_PRICE=${2:-5.0}

echo "🔍 Suche nach der günstigsten $GPU_MODEL unter \$$MAX_PRICE/h..."
clore search --gpu "$GPU_MODEL" --max-price "$MAX_PRICE" --sort price --limit 5

echo ""
read -p "Geben Sie die Server-ID zum Bereitstellen ein (oder 'q' zum Beenden): " SERVER_ID

if [ "$SERVER_ID" = "q" ]; then
    echo "Abgebrochen."
    exit 0
fi

read -sp "SSH-Passwort: " SSH_PASS
echo ""

clore deploy "$SERVER_ID" \
  --image cloreai/ubuntu22.04-cuda12 \
  --type on-demand \
  --currency bitcoin \
  --ssh-password "$SSH_PASS" \
  --port 22:tcp \
  --port 8888:http

echo "✅ Bereitgestellt! Prüfen Sie 'clore orders' auf den Status."
```

### Alle Bestellungen stornieren

```bash
#!/bin/bash
# cancel-all.sh — Alle aktiven Bestellungen stornieren

echo "📦 Aktuelle Bestellungen:"
clore orders

echo ""
read -p "ALLE aktiven Bestellungen stornieren? (yes/no): " CONFIRM

if [ "$CONFIRM" = "yes" ]; then
    # Verwenden Sie einen Python-Einzeiler, da die CLI jeweils eine Bestellung storniert
    python3 -c "
from clore_ai import CloreAI
client = CloreAI()
orders = client.my_orders()
for o in orders:
    client.cancel_order(o.id, issue='Batch cleanup')
    print(f'Cancelled order {o.id}')
print(f'Done. Cancelled {len(orders)} orders.')
"
else
    echo "Abgebrochen."
fi
```

***

## CI/CD-Integration

### GitHub Actions: GPU für Training bereitstellen

```yaml
# .github/workflows/train.yml
name: GPU Training

on:
  workflow_dispatch:
    inputs:
      gpu_model:
        description: 'GPU-Modell'
        default: 'RTX 4090'
      max_price:
        description: 'Maximaler Preis USD/h'
        default: '2.0'

env:
  CLORE_API_KEY: ${{ secrets.CLORE_API_KEY }}

jobs:
  train:
    runs-on: ubuntu-latest
    steps:
      - uses: actions/checkout@v4

      - name: Installiere clore-ai
        run: pip install clore-ai

      - name: GPU finden und bereitstellen
        run: |
          python3 << 'EOF'
          import time, os
          from clore_ai import CloreAI

          client = CloreAI()

          # Finde die günstigste passende GPU
          servers = client.marketplace(
              gpu="${{ github.event.inputs.gpu_model }}",
              max_price_usd=float("${{ github.event.inputs.max_price }}")
          )
          servers.sort(key=lambda s: s.price_usd or float("inf"))

          if not servers:
              print("Keine Server verfügbar!")
              exit(1)

          best = servers[0]
          print(f"Bereitstellung auf Server {best.id}: {best.gpu_model} @ ${best.price_usd:.4f}/h")

          order = client.create_order(
              server_id=best.id,
              image="cloreai/ubuntu22.04-cuda12",
              type="on-demand",
              currency="bitcoin",
              ssh_password=os.environ.get("SSH_PASSWORD", "CITraining123"),
              ports={"22": "tcp"},
              command="bash /workspace/train.sh"
          )

          print(f"Order {order.id} erstellt")

          # Auf Bereitschaft warten
          for _ in range(30):
              orders = client.my_orders()
              o = next((x for x in orders if x.id == order.id), None)
              if o and o.pub_cluster:
                  print(f"Bereit: {o.pub_cluster}")
                  break
              time.sleep(10)

          # Bestell-ID für Bereinigung speichern
          with open(os.environ["GITHUB_ENV"], "a") as f:
              f.write(f"ORDER_ID={order.id}\n")
          EOF

      - name: Auf Abschluss des Trainings warten
        run: |
          echo "Training läuft..."
          # Fügen Sie hier Ihre Überwachungslogik hinzu
          sleep 60

      - name: GPU bereinigen
        if: always()
        run: |
          python3 -c "
          from clore_ai import CloreAI
          import os
          client = CloreAI()
          order_id = int(os.environ.get('ORDER_ID', 0))
          if order_id:
              client.cancel_order(order_id, issue='CI job complete')
              print(f'Cancelled order {order_id}')
          "
```

### GitLab CI: Stapelverarbeitung

```yaml
# .gitlab-ci.yml
gpu-batch-job:
  stage: process
  image: python:3.11
  variables:
    CLORE_API_KEY: $CLORE_API_KEY
  before_script:
    - pip install clore-ai
  script:
    - |
      python3 << 'EOF'
      from clore_ai import CloreAI
      import time

      client = CloreAI()

      servers = client.marketplace(gpu="RTX 4090", max_price_usd=3.0)
      if not servers:
          print("Keine GPUs verfügbar")
          exit(1)

      servers.sort(key=lambda s: s.price_usd or float("inf"))
      order = client.create_order(
          server_id=servers[0].id,
          image="cloreai/ubuntu22.04-cuda12",
          type="spot",
          currency="bitcoin",
          spot_price=0.00005,
          ports={"22": "tcp"}
      )
      print(f"Bereitgestellt: Bestellung {order.id}")

      # ... Arbeit ausführen ...

      client.cancel_order(order.id)
      print("Fertig und bereinigt")
      EOF
  after_script:
    - |
      python3 -c "
      from clore_ai import CloreAI
      client = CloreAI()
      for o in client.my_orders():
          client.cancel_order(o.id, issue='CI cleanup')
      "
```

***

## Überwachung

### Bestellungen periodisch prüfen

```bash
#!/bin/bash
# monitor.sh — Bestellungen alle 60 Sekunden prüfen

while true; do
    echo "=== $(date) ==="
    clore orders
    clore wallets
    echo ""
    sleep 60
done
```

### Python-Überwachungsskript

```python
#!/usr/bin/env python3
"""monitor-orders.py — Aktive Bestellungen überwachen und bei Problemen alarmieren."""

import time
from clore_ai import CloreAI

POLL_INTERVAL = 60  # Sekunden
LOW_BALANCE_THRESHOLD = 0.001  # BTC

def monitor():
    client = CloreAI()

    while True:
        try:
            # Bestellungen prüfen
            orders = client.my_orders()
            print(f"[{time.strftime('%H:%M:%S')}] Aktive Bestellungen: {len(orders)}")
            for o in orders:
                print(f"  Bestellung {o.id}: type={o.type}, IP={o.pub_cluster or 'pending'}")

            # Guthaben prüfen
            wallets = client.wallets()
            for w in wallets:
                if w.name.lower() == "bitcoin" and w.balance < LOW_BALANCE_THRESHOLD:
                    print(f"  ⚠️  Niedriger BTC-Guthabenstand: {w.balance:.8f}")

        except Exception as e:
            print(f"  ❌ Fehler: {e}")

        time.sleep(POLL_INTERVAL)

if __name__ == "__main__":
    monitor()
```

***

## Stapeloperationen

### Auf mehreren Servern bereitstellen

```bash
#!/bin/bash
# batch-deploy.sh — Auf mehreren Servern bereitstellen

SERVER_IDS=(142 305 891 450)
IMAGE="cloreai/ubuntu22.04-cuda12"
PASSWORD="BatchRun$(date +%s)"

for SID in "${SERVER_IDS[@]}"; do
    echo "🚀 Bereitstellung auf Server $SID..."
    clore deploy "$SID" \
      --image "$IMAGE" \
      --type on-demand \
      --currency bitcoin \
      --ssh-password "$PASSWORD" \
      --port 22:tcp \
      || echo "⚠️  Bereitstellung auf $SID fehlgeschlagen"
    sleep 6  # Respektieren Sie Rate-Limits
done

echo ""
echo "📦 Alle Bestellungen:"
clore orders
echo "🔑 Passwort: $PASSWORD"
```

### Stapelbereitstellung mit Python (Async)

```python
#!/usr/bin/env python3
"""batch-deploy.py — Auf mehreren Servern gleichzeitig bereitstellen."""

import asyncio
from clore_ai import AsyncCloreAI
from clore_ai.exceptions import CloreAPIError

async def batch_deploy(server_ids, image="cloreai/ubuntu22.04-cuda12"):
    async with AsyncCloreAI() as client:
        tasks = [
            client.create_order(
                server_id=sid,
                image=image,
                type="on-demand",
                currency="bitcoin",
                ssh_password="BatchPass123",
                ports={"22": "tcp"}
            )
            for sid in server_ids
        ]

        results = await asyncio.gather(*tasks, return_exceptions=True)

        for sid, result in zip(server_ids, results):
            if isinstance(result, CloreAPIError):
                print(f"❌ Server {sid}: {result}")
            elif isinstance(result, Exception):
                print(f"❌ Server {sid}: {result}")
            else:
                print(f"✅ Server {sid}: Bestellung {result.id}")

if __name__ == "__main__":
    import sys
    server_ids = [int(x) for x in sys.argv[1:]]
    if not server_ids:
        print("Verwendung: python batch-deploy.py 142 305 891")
        exit(1)
    asyncio.run(batch_deploy(server_ids))
```

Verwendung:

```bash
python batch-deploy.py 142 305 891
```

### Spotmarkt-Scanner

```bash
#!/bin/bash
# spot-scanner.sh — Spotpreise für eine Liste von Servern scannen

SERVERS=(6 12 42 100)

echo "📊 Spotmarkt-Scan — $(date)"
echo "---"

for SID in "${SERVERS[@]}"; do
    echo "Server $SID:"
    clore spot "$SID"
    echo ""
done
```

***

## Cron-Jobs

### Tägliche GPU-Preisprüfung

```bash
# In crontab hinzufügen: crontab -e
# Jeden Tag um 9 Uhr ausführen
0 9 * * * CLORE_API_KEY=your_key /usr/local/bin/clore search --gpu "RTX 4090" --sort price --limit 5 >> /var/log/clore-prices.log 2>&1
```

### Stündliche Guthabenprüfung

```bash
# Prüfe Guthaben jede Stunde
0 * * * * CLORE_API_KEY=your_key /usr/local/bin/clore wallets >> /var/log/clore-balance.log 2>&1
```

***

## Tipps

1. **Setzen Sie immer `CLORE_API_KEY`** als Umgebungsvariable in Skripten und CI
2. **Fügen Sie hinzu `sleep 6`** zwischen Deploy-Befehlen in Bash-Schleifen ein, um Rate-Limits zu respektieren
3. **Verwenden Sie `--type spot`** für Stapel-/CI-Jobs — günstiger und unterbrechbar ist in Ordnung
4. **Bestellungen stornieren in `after_script`** / `if: always()` um vergessene Abrechnung zu vermeiden
5. **Speichern Sie SSH-Passwörter in Secrets** (GitHub Secrets, GitLab CI-Variablen usw.)
6. **Verwenden Sie `clore orders --completed`** um vergangene Nutzung zu prüfen

***

## Nächste Schritte

* [Python-SDK-Anleitung](/guides/guides_v2-de/erweitert/python-sdk.md) — Vollständige SDK-Referenz mit asynchronen Mustern
* [Stapelverarbeitung](/guides/guides_v2-de/erweitert/batch-processing.md) — Große KI-Workloads verarbeiten
* [API-Integration](/guides/guides_v2-de/erweitert/api-integration.md) — KI-Dienste mit Ihren Anwendungen verbinden


---

# Agent Instructions
This documentation is published with GitBook. GitBook is the documentation platform designed so that both humans and AI agents can read, navigate, and reason over technical content effectively. Learn more at gitbook.com.

## Querying This Documentation
If you need additional information that is not directly available in this page, you can query the documentation dynamically by asking a question.

Perform an HTTP GET request on the current page URL with the `ask` query parameter:

```
GET https://docs.clore.ai/guides/guides_v2-de/erweitert/cli-automation.md?ask=<question>
```

The question should be specific, self-contained, and written in natural language.
The response will contain a direct answer to the question and relevant excerpts and sources from the documentation.

Use this mechanism when the answer is not explicitly present in the current page, you need clarification or additional context, or you want to retrieve related documentation sections.
