Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- <?php
- /**
- * SSH login and halt hosts
- * For Ubuntu Server (or sudo environment)
- */
- $user = 'username';
- $password = 'password';
- $hosts = [
- '192.168.1.10',
- '192.168.1.11',
- '192.168.1.12',
- ];
- $command = 'sudo halt -p';
- $timeout = 15; // seconds
- foreach ($hosts as $host) {
- $connection = ssh2_connect($host, 22);
- if ($connection === false) {
- echo $host . ' connection fail' . PHP_EOL;
- continue;
- }
- if (ssh2_auth_password($connection, $user, $password) === false) {
- echo $host . ' auth fail' . PHP_EOL;
- continue;
- }
- $shell = ssh2_shell($connection, 'xterm', null, 80, 25, SSH2_TERM_UNIT_CHARS);
- ssh_read($shell, '#' . $user . '\@[^:]+\:\~\$#');
- fwrite($shell, $command . "\n");
- ssh_read($shell, '#\[sudo\][^:]+:#');
- fwrite($shell, $password . "\n");
- stream_set_blocking($shell, true);
- fread($shell, 1024 * 32);
- echo $host . ' halted' . PHP_EOL;
- }
- function ssh_read($shell, $waitFor) {
- global $timeout;
- for ($i = 0; $i < $timeout * 10; ++$i) {
- usleep(100 * 1000);
- $out = fread($shell, 1024 * 32);
- if ($out === false) {
- break;
- }
- echo $out;
- if (preg_match($waitFor, $out)) {
- break;
- }
- }
- }
Add Comment
Please, Sign In to add comment