<?php

class SSHClient
{
  public string $SSHPath;
  public int $Timeout;
  public string $HostName;
  public string $UserName;
  public string $Password;
  public string $PrivateKey;
  public bool $Debug;

  function __construct($HostName = 'localhost', $UserName = 'admin', $Password = '')
  {
    $this->HostName = $HostName;
    $this->UserName = $UserName;
    $this->Password = $Password;
    $this->Debug = false;
    $this->PrivateKey = '~/.ssh/id_rsa';
    $this->SSHPath = '/usr/bin/ssh';
    $this->Timeout = 3;
  }

  function Execute(string $Commands): array
  {
    $Commands = trim($Commands);
    if ($Commands != '')
    {
      $Commands = addslashes($Commands);
      $Commands = str_replace('$', '\$', $Commands);
      //$Commands = str_replace(' ', '\ ', $Commands);
      if ($this->PrivateKey != '') $PrivKey = ' -i '.$this->PrivateKey;
        else $PrivKey = '';
      $Command = $this->SSHPath.' -oBatchMode=yes -o ConnectTimeout='.$this->Timeout.' -l '.
        $this->UserName.$PrivKey.' '.$this->HostName.' "'.$Commands.'"';
      if ($this->Debug) echo($Command);
      $Output = array();
      exec($Command, $Output);
    } else $Output = array();
    if ($this->Debug) print_r($Output);
    return $Output;
  }
}
