66 lines
2.1 KiB
PHP
66 lines
2.1 KiB
PHP
<?php
|
|
|
|
namespace App\Network\Clients\Hisfocus;
|
|
|
|
use App\Network\Clients\Hsgq\HsgqCliClient;
|
|
use phpseclib3\Net\SSH2;
|
|
use RuntimeException;
|
|
|
|
class HisfocusSshClient implements HsgqCliClient
|
|
{
|
|
private SSH2 $ssh;
|
|
|
|
public function __construct(private readonly string $host, private readonly int $port, private readonly int $timeout = 10) {}
|
|
|
|
public function connect(string $username, string $password): void
|
|
{
|
|
$this->ssh = new SSH2($this->host, $this->port, $this->timeout);
|
|
$this->ssh->setTimeout($this->timeout);
|
|
if (! $this->ssh->login($username, $password)) {
|
|
throw new RuntimeException('AUTHENTICATION_FAILED: login SSH Hisfocus ditolak.');
|
|
}
|
|
$this->readPrompt();
|
|
}
|
|
|
|
public function enterEnable(string $password): void
|
|
{
|
|
$this->ssh->write("enable\n");
|
|
$output = $this->ssh->read('/(?:Password\s*:|[#>]\s*$)/i', SSH2::READ_REGEX);
|
|
if (preg_match('/Password\s*:/i', (string) $output)) {
|
|
$this->ssh->write($password."\n");
|
|
$output = $this->readPrompt();
|
|
}
|
|
if (! str_ends_with(trim((string) $output), '#')) {
|
|
throw new RuntimeException('ENABLE_FAILED: gagal masuk privileged mode Hisfocus.');
|
|
}
|
|
}
|
|
|
|
public function command(string $command): string
|
|
{
|
|
$this->ssh->write($command."\n");
|
|
$output = $this->readPrompt();
|
|
if (preg_match('/(?:%\s*)?(?:Error|Invalid|Incomplete|Ambiguous|unknown command|not found)/i', $output)) {
|
|
throw new RuntimeException('COMMAND_REJECTED: Hisfocus menolak perintah read-only.');
|
|
}
|
|
|
|
return $output;
|
|
}
|
|
|
|
public function disconnect(): void
|
|
{
|
|
if (isset($this->ssh)) {
|
|
$this->ssh->disconnect();
|
|
}
|
|
}
|
|
|
|
private function readPrompt(): string
|
|
{
|
|
$output = $this->ssh->read('/(?:\([^\r\n]+\))?[#>]\s*$/', SSH2::READ_REGEX);
|
|
if ($output === false || $output === '') {
|
|
throw new RuntimeException('CONNECTION_TIMEOUT: prompt CLI Hisfocus tidak diterima.');
|
|
}
|
|
|
|
return $output;
|
|
}
|
|
}
|