SshClient.class.php 1.9 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869
  1. <?php
  2. /*
  3. Pour utiliser cette classe, penser a ajouter le paquet :
  4. apt-get install php7.2-ssh
  5. service apache2 reload
  6. */
  7. class SshClient{
  8. public $connection;
  9. public function connect($ip,$port = 22,$publicKeyPath,$privateKeyPath,$privateKeyPassword = ''){
  10. $this->connection = ssh2_connect($ip, $port, array('hostkey'=>'ssh-rsa'));
  11. if (!ssh2_auth_pubkey_file($this->connection, 'root',
  12. $publicKeyPath ,
  13. $privateKeyPath, $privateKeyPassword)) throw new Exception("Authentification par clé loupée");
  14. }
  15. public function send_file($localPath,$remotePath,$permissions = 0755){
  16. return ssh2_scp_send($this->connection, $localPath, $remotePath,$permissions);
  17. }
  18. public function send_stream($stream,$remotePath,$permissions = 0755){
  19. $tempPath = File::temp().SLASH.sha1(rand(0,1000));
  20. file_put_contents($tempPath, $stream);
  21. $return = $this->send_file($tempPath,$remotePath);
  22. unlink($tempPath);
  23. return $return;
  24. }
  25. public function execute($command){
  26. $stream = ssh2_exec($this->connection, $command);
  27. $errorStream = ssh2_fetch_stream($stream, SSH2_STREAM_STDERR);
  28. stream_set_blocking($errorStream, true);
  29. stream_set_blocking($stream, true);
  30. $error = stream_get_contents($errorStream);
  31. $response = stream_get_contents($stream);
  32. if(!empty($error)){
  33. $response = $error;
  34. }
  35. fclose($errorStream);
  36. fclose($stream);
  37. return $response;
  38. }
  39. public static function format_output($output){
  40. $output = nl2br($output);
  41. //$output = str_replace('', 'blue ?', $output);
  42. $output = str_replace('', '<span class="text-danger">', $output);
  43. $output = str_replace('', '<span class="text-success">', $output);
  44. $output = str_replace('', '</span>', $output);
  45. $output = str_replace('', '', $output);
  46. $output = str_replace('', '', $output);
  47. return $output;
  48. }
  49. public function disconnect(){
  50. ssh2_disconnect ($this->connection );
  51. }
  52. }
  53. ?>