66 lines
2.2 KiB
PHP
66 lines
2.2 KiB
PHP
<?php
|
|
|
|
namespace App\Network\Clients\Hsgq;
|
|
|
|
use phpseclib3\Net\SSH2;
|
|
use RuntimeException;
|
|
|
|
class HsgqSshClient 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 HSGQ ditolak.');
|
|
}
|
|
$this->readPrompt();
|
|
}
|
|
|
|
public function command(string $command): string
|
|
{
|
|
$this->ssh->write($command."\n");
|
|
$output = $this->readPrompt();
|
|
if (preg_match('/(?:Error|Invalid|Failed|failure|unknown command|Command incomplete|There is no matched command)/i', $output)) {
|
|
preg_match('/^(?!.*user\s+(?:add|password)).*(?:Error|Invalid|Failed|failure|unknown command|Command incomplete|There is no matched command).*$/mi', $output, $detail);
|
|
throw new RuntimeException('COMMAND_REJECTED: '.str($detail[0] ?? 'HSGQ menolak perintah CLI.')->trim()->limit(180));
|
|
}
|
|
|
|
return $output;
|
|
}
|
|
|
|
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', $output)) {
|
|
$this->ssh->write($password."\n");
|
|
$output = $this->readPrompt();
|
|
}
|
|
if (! str_ends_with(trim($output), '#')) {
|
|
throw new RuntimeException('ENABLE_FAILED: gagal masuk privileged mode HSGQ.');
|
|
}
|
|
}
|
|
|
|
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 HSGQ tidak diterima.');
|
|
}
|
|
|
|
return $output;
|
|
}
|
|
}
|