clusev/app/Support/Ssh/SshClient.php

66 lines
1.5 KiB
PHP

<?php
namespace App\Support\Ssh;
use App\Models\Server;
use phpseclib3\Net\SSH2;
use RuntimeException;
/**
* Thin wrapper around phpseclib SSH2 for command execution. The control plane
* orchestrates real servers over SSH — it does not reimplement daemons.
*/
class SshClient
{
private ?SSH2 $ssh = null;
public function __construct(
private readonly CredentialVault $vault,
private readonly int $timeout = 15,
) {}
public function connect(Server $server): self
{
$ssh = new SSH2($server->ip, $server->ssh_port ?: 22);
$ssh->setTimeout($this->timeout);
$login = $this->vault->resolve($server);
if (! $ssh->login($login['username'], $login['secret'])) {
throw new RuntimeException("SSH-Login auf {$server->name} ({$server->ip}) fehlgeschlagen.");
}
$this->ssh = $ssh;
return $this;
}
public function exec(string $command): string
{
return (string) $this->client()->exec($command);
}
/**
* Run a command and return [stdout, exitCode].
*
* @return array{0: string, 1: int|false}
*/
public function run(string $command): array
{
$out = $this->exec($command);
return [$out, $this->client()->getExitStatus()];
}
public function disconnect(): void
{
$this->ssh?->disconnect();
$this->ssh = null;
}
private function client(): SSH2
{
return $this->ssh ?? throw new RuntimeException('Nicht verbunden — connect() zuerst aufrufen.');
}
}