Guest User

Untitled

a guest
Feb 22nd, 2018
157
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
text 1.24 KB | None | 0 0
  1. <?php
  2.  
  3. /**
  4. * SSH login and halt hosts
  5. * For Ubuntu Server (or sudo environment)
  6. */
  7. $user = 'username';
  8. $password = 'password';
  9. $hosts = [
  10. '192.168.1.10',
  11. '192.168.1.11',
  12. '192.168.1.12',
  13. ];
  14. $command = 'sudo halt -p';
  15. $timeout = 15; // seconds
  16.  
  17. foreach ($hosts as $host) {
  18. $connection = ssh2_connect($host, 22);
  19. if ($connection === false) {
  20. echo $host . ' connection fail' . PHP_EOL;
  21. continue;
  22. }
  23. if (ssh2_auth_password($connection, $user, $password) === false) {
  24. echo $host . ' auth fail' . PHP_EOL;
  25. continue;
  26. }
  27. $shell = ssh2_shell($connection, 'xterm', null, 80, 25, SSH2_TERM_UNIT_CHARS);
  28. ssh_read($shell, '#' . $user . '\@[^:]+\:\~\$#');
  29. fwrite($shell, $command . "\n");
  30. ssh_read($shell, '#\[sudo\][^:]+:#');
  31. fwrite($shell, $password . "\n");
  32. stream_set_blocking($shell, true);
  33. fread($shell, 1024 * 32);
  34. echo $host . ' halted' . PHP_EOL;
  35. }
  36.  
  37. function ssh_read($shell, $waitFor) {
  38. global $timeout;
  39. for ($i = 0; $i < $timeout * 10; ++$i) {
  40. usleep(100 * 1000);
  41. $out = fread($shell, 1024 * 32);
  42. if ($out === false) {
  43. break;
  44. }
  45. echo $out;
  46. if (preg_match($waitFor, $out)) {
  47. break;
  48. }
  49. }
  50. }
Add Comment
Please, Sign In to add comment