function sshiconn($cmd, $pass, $ip, $sshp = 22) { $ip = $_REQUEST['ip']; $pass = $_REQUEST['pass']; $sshp = $_REQUEST['sshp']; if (!isset($_REQUEST['sshp'])) { $sshp = '22'; } $connection = ssh2_connect($ip, $sshp); if (!$connection) { throw new Exception("fail: unable to establish connection\nPlease IP or if server is on and connected"); } $pass_success = ssh2_auth_password($connection, 'root', $pass); if (!$pass_success) { throw new Exception("fail: unable to establish connection\nPlease Check your password"); } $stream = ssh2_exec($connection, $cmd); $errorStream = ssh2_fetch_stream($stream, SSH2_STREAM_STDERR); stream_set_blocking($errorStream, true); stream_set_blocking($stream, true); print_r($cmd); $output = stream_get_contents($stream); fclose($stream); fclose($errorStream); ssh2_exec($connection, 'exit'); unset($connection); return $output; }
/** * @param $command * @param bool $display * @return array * @throws \Exception */ public function exec($command, $display = true) { $outStream = ssh2_exec($this->stream, $command); $errStream = ssh2_fetch_stream($outStream, SSH2_STREAM_STDERR); stream_set_blocking($outStream, true); stream_set_blocking($errStream, true); $err = $this->removeEmptyLines(explode("\n", stream_get_contents($errStream))); if (count($err)) { if (strpos($err[0], 'Cloning into') === false) { // throw new \Exception(implode("\n", $err)); } } $out = $this->removeEmptyLines(explode("\n", stream_get_contents($outStream))); fclose($outStream); fclose($errStream); if ($display) { if (!$this->output instanceof OutputInterface) { throw new \LogicException('You should set output first'); } foreach ($out as $line) { $this->output->writeln(sprintf('<info>%s</info>', $line)); } } return $out; }
public function handle() { /** * Estamblish SSH connection, * put site under maintenance, * pull chamges from git, * install composer dependencies, * execute migrations, * put site online */ $remote = config('pckg.framework.' . DeployProject::class . '.remotes.default'); $path = $remote['root']; $commands = ['cd ' . $path => 'Changing root directory', 'php ' . $path . 'console project:down' => 'Putting project offline', 'php ' . $path . 'console project:pull' => 'Executing project:pull', 'php ' . $path . 'console migrator:install' => 'Installing migrations', 'php ' . $path . 'console project:up' => 'Putting project up', 'php ' . $path . 'console cache:clear' => 'Clearing cache']; $this->output('Estamblishing SSH connection.'); $sshConnection = ssh2_connect($remote['host'], $remote['port']); $this->output('SSH connection estamblished.'); /** * Authenticate. */ if (!ssh2_auth_password($sshConnection, $remote['username'], $remote['password'])) { throw new Exception('Cannot estamblish SSH connection to remote'); } foreach ($commands as $command => $notice) { $this->output($notice); $stream = ssh2_exec($sshConnection, $command); $errorStream = ssh2_fetch_stream($stream, SSH2_STREAM_STDERR); stream_set_blocking($errorStream, true); stream_set_blocking($stream, true); $errorStreamContent = stream_get_contents($errorStream); $streamContent = stream_get_contents($stream); $this->output($errorStreamContent . "\n" . $streamContent); } $this->output('Done!'); }
function getOS($pass = false) { $ip = $_REQUEST['ip']; $lsbresult1 = array(); if (isset($pass) && $pass) { $connection = ssh2_connect($ip, 22); echo ssh2_auth_password($connection, 'root', $pass) ? 'success' : 'fail'; $cmd = "lsb_release -as"; $stream = ssh2_exec($connection, $cmd); $errorStream = ssh2_fetch_stream($stream, SSH2_STREAM_STDERR); stream_set_blocking($errorStream, true); stream_set_blocking($stream, true); $lsbresult1 = stream_get_contents($stream); } else { $lsbresult1 = array(); exec("ssh sysad@{$ip} 'lsb_release -as'", $lsbresult1); } $lsbresult = explode("\n", $lsbresult1); if (!empty($lsbresult)) { $OS = $lsbresult[0]; $version = $lsbresult[3]; $releasever = $lsbresult[2]; } else { echo "No values present"; die; } return array($OS, $version, $releasever); }
/** * Get the complete output from the command, separating stdout and stderr * * Returns an associative array: * ['stdout' => string, 'stderr' => string] * * @return string[] */ public function getSegmentedOutput() { $this->close(); $stderr = ssh2_fetch_stream($this->resource, SSH2_STREAM_STDERR); stream_set_blocking($this->resource, true); stream_set_blocking($stderr, true); $out = stream_get_contents($this->resource); $err = stream_get_contents($stderr); return ['stdout' => $out, 'stderr' => $err]; }
protected function _bubbleSshErrors($sshStream, $commandString) { $errorStream = ssh2_fetch_stream($sshStream, SSH2_STREAM_STDERR); stream_set_blocking($errorStream, true); $error = stream_get_contents($errorStream); fclose($errorStream); if ($error) { $error = 'While executing [' . $commandString . '] ' . $error; throw new Exception($error); } }
public function run($cmd, $pty = false, $env = null, $width = 80, $height = 25, $width_height_type = SSH2_TERM_UNIT_CHARS) { $stdout = ssh2_exec($this->getResource(), $cmd, $pty, $env, $width, $height, $width_height_type); $stderr = ssh2_fetch_stream($stdout, SSH2_STREAM_STDERR); stream_set_blocking($stderr, true); stream_set_blocking($stdout, true); $error = stream_get_contents($stderr); if ($error !== '') { throw new RuntimeException($error); } return stream_get_contents($stdout); }
private function executeCommand($command) { echo "\nrunning command....." . $command . PHP_EOL; $stream = ssh2_exec($this->connection, $command); echo "\ntimeout is....." . $this->timeout . PHP_EOL; $connectionTimeout = time(); $connectionTimeout = $connectionTimeout + (int) $this->timeout * 60; stream_set_blocking($stream, false); $error_stream = ""; $result = 0; $finalresult = 1; $errMessage = ""; sleep(30); $err_stream = ssh2_fetch_stream($stream, SSH2_STREAM_STDERR); while (time() < $connectionTimeout) { sleep(1); if ($err = fgets($err_stream)) { //flush(); echo $err; $errMessage .= $err; $err = ""; $connectionTimeout = time(); $connectionTimeout = $connectionTimeout + (int) $this->timeout * 60; } if ($cmd = fgets($stream)) { //flush(); echo $cmd . PHP_EOL; if (strstr($cmd, "EXECCOMPLETED=") == true) { if (strstr($cmd, "EXECCOMPLETED=0") == false && strstr($cmd, "EXECCOMPLETED=%ERRORLEVEL%") == false) { $result = 1; } if (strstr($cmd, "EXECCOMPLETED=0") == true) { $finalresult = 0; } break; } $connectionTimeout = time(); $connectionTimeout = $connectionTimeout + (int) $this->timeout * 60; } $connectionTimeout = time(); $connectionTimeout = $connectionTimeout + (int) $this->timeout * 60; //else { // break; // } } if (empty($errMessage) == false && $finalresult != 0) { echo "\nUnable to execute" . $errMessage . PHP_EOL; $result = 1; } fclose($err_stream); fclose($stream); return $result; }
/** * @param $cmd * @param bool $pty * @param null $env * @return string * @throws RemoteShellCommandException */ public function exec($cmd, $pty = FALSE, $env = NULL) { $result = ssh2_exec($this->connection->getConnection(), $cmd, $pty, $env); $errorStream = ssh2_fetch_stream($result, SSH2_STREAM_STDERR); stream_set_blocking($errorStream, TRUE); stream_set_blocking($result, TRUE); $error = stream_get_contents($errorStream); if (!empty($error)) { throw new RemoteShellCommandException($error); } return stream_get_contents($result); }
/** * Construct an execution stream in blocking mode. * * @param resource $stream * * @throws UnexpectedValueException if $stream is not a valid stream */ public function __construct($stream) { if (!Valid::streamResource($stream)) { throw new UnexpectedValueException('Parameter must be a valid stream resource'); } $stderr = ssh2_fetch_stream($stream, SSH2_STREAM_STDERR); if (!$stderr) { throw new UnexpectedValueException('Parameter is a valid stream, but does not contain an »stderr« substream'); } $this->stdio = $stream; $this->stderr = $stderr; }
public function run($cmd, $pty = null, array $env = array(), $width = 80, $height = 25, $width_height_type = SSH2_TERM_UNIT_CHARS) { $cmd .= ';echo -ne "[return_code:$?]"'; $stdout = ssh2_exec($this->getResource(), $cmd, $pty, $env, $width, $height, $width_height_type); $stderr = ssh2_fetch_stream($stdout, SSH2_STREAM_STDERR); stream_set_blocking($stderr, true); stream_set_blocking($stdout, true); $output = stream_get_contents($stdout); preg_match('/\\[return_code:(.*?)\\]/', $output, $match); if ((int) $match[1] !== 0) { throw new RuntimeException(stream_get_contents($stderr), (int) $match[1]); } return preg_replace('/\\[return_code:(.*?)\\]/', '', $output); }
/** * Execute a SSH command * * @param string $cmd The SSH command * * @return string The output */ public function execute($cmd) { // if ( false === $stream = ssh2_exec( $this->connection, $cmd ) ) { // throw new SshException( sprintf( '"%s" : SSH command failed', $cmd ) ); // } $stdout = ssh2_exec($this->connection, $cmd); $stderr = ssh2_fetch_stream($stdout, SSH2_STREAM_STDERR); stream_set_blocking($stderr, true); stream_set_blocking($stdout, true); $error = stream_get_contents($stderr); if ($error !== '') { throw new \RuntimeException($error); } return stream_get_contents($stdout); }
function ssh_command($command, $blocking) { global $connection; $reply = ssh2_exec($connection, $command); $errorReply = ssh2_fetch_stream($reply, SSH2_STREAM_STDERR); stream_set_blocking($reply, $blocking); stream_set_blocking($errorReply, $blocking); $output = stream_get_contents($reply); $error = stream_get_contents($errorReply); if (!empty($output)) { return $output; } else { return $error; } }
public function exec($cmd) { $stdout = ssh2_exec($this->connection, $cmd . '; echo "__RETURNS__:$?"', 'ansi'); $stderr = ssh2_fetch_stream($stdout, SSH2_STREAM_STDERR); stream_set_blocking($stderr, true); $this->lastError = stream_get_contents($stderr); stream_set_blocking($stdout, true); $this->lastOutput = stream_get_contents($stdout); $returnCode = null; $pos = strpos($this->lastOutput, '__RETURNS__:'); if (false !== $pos) { $returnCode = substr($this->lastOutput, $pos + 12); $this->lastOutput = substr($this->lastOutput, 0, $pos); } return $returnCode; }
public function exec() { if (ssh2_auth_password($this->connection, 'root', 'root')) { $stream = ssh2_exec($connection, "ls -al"); $errorStream = ssh2_fetch_stream($stream, SSH2_STREAM_STDERR); // Enable blocking for both streams // stream_set_blocking($errorStream, true); stream_set_blocking($stream, true); // Whichever of the two below commands is listed first will receive its appropriate output. The second command receives nothing echo '<pre>'; var_dump(stream_get_contents($stream)); echo '</pre>'; // echo "Error: " . stream_get_contents($errorStream); // Close the streams fclose($stream); } }
public function exec($cmd) { $stdout = ssh2_exec($this->connection, $cmd . '; echo "' . self::RETURN_TOKEN . '$?"', 'ansi'); $stderr = ssh2_fetch_stream($stdout, SSH2_STREAM_STDERR); stream_set_blocking($stderr, true); $this->lastError = stream_get_contents($stderr); stream_set_blocking($stdout, true); $this->lastOutput = stream_get_contents($stdout); $this->exitCode = -1; $pos = strpos($this->lastOutput, self::RETURN_TOKEN); if (false === $pos) { return false; } $this->exitCode = substr($this->lastOutput, $pos + strlen(self::RETURN_TOKEN)); $this->lastOutput = substr($this->lastOutput, 0, $pos); return $this->isSuccessful(); }
function ssh2_value($cmd) { session_start(); $user = $_SESSION['username']; $pw = $_SESSION['password']; $connection = ssh2_connect("127.0.0.1", 22); if (!$connection) { die("Connection failed."); } if (!ssh2_auth_password($connection, $user, $pw)) { die("Auth failed"); } $stream = ssh2_exec($connection, $cmd); stream_set_blocking($stream, true); $stream_out = ssh2_fetch_stream($stream, SSH2_STREAM_STDIO); return stream_get_contents($stream_out); }
function ssh2Auth($sendData) { if (!($connection = ssh2_connect($sendData, "22"))) { return false; } if (!ssh2_auth_password($connection, "administrator", "Spb78sts!")) { return false; } if (!($stream = ssh2_exec($connection, 'ifconfig'))) { return false; } else { stream_set_blocking($stream, true); $stream_out = ssh2_fetch_stream($stream, SSH2_STREAM_STDIO); $config = stream_get_contents($stream_out); } fclose($stream); return $config; }
function exec($cmd) { //echo $this->date->getCurrentTime() . " executing: " . $cmd . "\n"; $executingInfo = "executing: {$cmd}"; $this->logger->addLog("cmds", 100, $executingInfo, $this->host_ip); $stream = ssh2_exec($this->ssh_connection, $cmd); if ($stream == false) { $errorExecInfo = "execute cmds: {$cmd} error!"; $this->logger->addLog("cmds", 0, $errorExecInfo, $this->host_ip); throw new Exception(Utils::red($errorExecInfo)); } $errStream = ssh2_fetch_stream($stream, SSH2_STREAM_STDERR); stream_set_blocking($stream, TRUE); stream_set_blocking($errStream, TRUE); $stdout = stream_get_contents($stream); $stderr = stream_get_contents($errStream); if (strstr($cmd, "ftp") or strstr($cmd, "lftp")) { echo "\n" . $stdout . "\n"; if (strstr($stdout, "530")) { echo Utils::red("\nftp login failed, please try again!\n"); } } $this->logger->addLog("cmds", 100, $stdout, $this->host_ip); //echo $this->date->getCurrentTime() . " STDOUT: " . $stdout . "\n"; if ($stderr != null || $stderr != "") { if (strstr($stderr, "Permission denied")) { echo Utils::red("\nyou need higher authority!\n"); exit; } echo $this->date->getCurrentTime() . " WARNING: " . $stderr . "\n"; $this->logger->addLog("cmds", 0, $stderr, $this->host_ip); } if (strstr($stderr, "Error:") || strstr($stderr, "Warning:") || strstr($stderr, "Cannot")) { throw new Exception(Utils::red("have error info please check your cmd is true!")); } //if ($errStream != null ) { // throw new Exception(Utils::red("execute cmds: $cmd error!")); //} fclose($stream); fclose($errStream); return $stdout; }
/** * These parameters match those passed to the ssh2_exec function, except for the second * parameter, $cwd. * * @param $command * @param string|null $cwd * @param string|null $pty * @param array $env * @param int $width * @param int $height * @param int $width_height_type */ public function execTerm($command, $cwd = null, $pty = null, array $env = [], $width = 80, $height = 25, $width_height_type = SSH2_TERM_UNIT_CHARS) { $commandAugmented = $command; // if we need to change the cwd if ($cwd !== null) { $cwdEscaped = escapeshellarg($cwd); $commandAugmented = "cd {$cwdEscaped}; {$commandAugmented}"; } // tack on the exit status so we can get it later $commandAugmented .= ';echo -en "\\n$?"'; // execute the command $stream = ssh2_exec($this->session, $commandAugmented, $pty, $env, $width, $height, $width_height_type); /* * Get the output */ $errorStream = ssh2_fetch_stream($stream, SSH2_STREAM_STDERR); $standardStream = ssh2_fetch_stream($stream, SSH2_STREAM_STDIO); stream_set_blocking($errorStream, true); stream_set_blocking($standardStream, true); $errorOutput = stream_get_contents($errorStream); $standardOutputRaw = stream_get_contents($standardStream); $standardOutput = $standardOutputRaw; fclose($stream); fclose($errorStream); fclose($standardStream); /* * Extract the exit status we tacked on earlier. */ $exitStatus = null; if (preg_match("/^(.*)\n(0|-?[1-9][0-9]*)\$/s", $standardOutputRaw, $matches)) { $exitStatus = (int) $matches[2]; $standardOutput = $matches[1]; } /* * Finish up. */ $this->_hasRun = true; $this->lastCommand = $command; $this->lastExitStatus = $exitStatus; $this->lastStandardOutput = $standardOutput; $this->lastErrorOutput = $errorOutput; }
function exec($cmd) { $this->log->verbose("Executing remote command: {$cmd}"); $stdout = ssh2_exec($this->conn, $cmd . " && echo 'RETOK'", 'ansi'); $stderr = ssh2_fetch_stream($stdout, SSH2_STREAM_STDERR); stream_set_blocking($stderr, true); $errors = stream_get_contents($stderr); if ($errors) { $this->log->verbose("STDERR: " . trim($errors)); } stream_set_blocking($stdout, true); $output = stream_get_contents($stdout); if (!strstr($output, 'RETOK')) { $this->log->error($output); } else { $output = substr($output, 0, strpos($output, 'RETOK')); } $this->log->verbose(trim($output)); return $output; }
public function run($command) { if ($this->status) { $this->stream = ssh2_exec($this->session, $command); $this->errorStream = ssh2_fetch_stream($this->stream, SSH2_STREAM_STDERR); stream_set_blocking($this->errorStream, 1); stream_set_blocking($this->stream, 1); $this->data = trim(stream_get_contents($this->stream)); $this->error = trim(stream_get_contents($this->errorStream)); if ($this->data) { fclose($this->stream); return true; } else { fclose($this->errorStream); return false; } } else { $this->output->info("Session is not connected"); return false; } }
public function checkConnec($settings, $checkPackage) { //PING HOST //http://www.cyberciti.biz/tips/simple-linux-and-unix-system-monitoring-with-ping-command-and-scripts.html // echo " checkConnec1 "; $ping_result = exec("ping -c2 -n -i 0.2 " . $settings->host . " | grep 'received' | awk -F',' '{ print \$2}' | awk '{ print \$1}'"); if ($ping_result != 2) { return new Notification(notificationType::Danger, 'Error!', 'The host ' . $settings->host . ' Este equipo no responde a la conexion remota...'); } // echo " checkConnec2 ".$settings->host." , ".intval($settings->port); //TRY SSH TO THE HOST+CHECK IF DOCKER IS INSTALLED //http://www.php.net/manual/en/function.ssh2-exec.php $connection = @ssh2_connect($settings->host, intval($settings->port)); // echo "checkConnec3 "; if (!$connection) { return new Notification(notificationType::Danger, 'Error!', 'la conexion SSH ' . $settings->host . ':' . $settings->port . ' tiene problemas, verifique el puerto en que corre el servicio.'); } if (!@ssh2_auth_password($connection, $settings->user, $settings->password)) { return new Notification(notificationType::Danger, 'Problema!', 'El intento de conexión a ' . $settings->host . ':' . $settings->port . ' <b>NO</b> fue correcto, inténtelo de nuevo.'); } // echo " checkConnec4 "; if ($checkPackage) { $stream = ssh2_exec($connection, 'dpkg -s ' . $this->dockerPackage); // echo " checkPackage: ".$stream; $errorStream = ssh2_fetch_stream($stream, SSH2_STREAM_STDERR); // echo " checkPackage: ".$errorStream; // Enable blocking for both streams stream_set_blocking($errorStream, true); stream_set_blocking($stream, true); $errorOutput = stream_get_contents($errorStream); $output = stream_get_contents($stream); fclose($errorStream); fclose($stream); if ($errorOutput != "") { return new Notification(notificationType::Danger, 'Error!', $errorOutput . ' @ ' . $settings->host); } } // echo " checkConnec5 <br/> "; return 0; }
/** * @param ConnectionInterface $connection * @param CommandInterface $command * * @return ResultInterface * @throws \RuntimeException */ public function exec(ConnectionInterface $connection, CommandInterface $command) { $command->execBegin(); $stream = @ssh2_exec($connection->getConnection(), $command->asString(), $command instanceof ExecCommandInterface ? $command->getPty() : null, $command->getEnv(), $command->getWidth(), $command->getHeight(), $command->getWidthHeightType()); $connection->history()->add($command); if (!$stream) { throw new \RuntimeException(sprintf('Can not execute command `%s`', $command->asString())); } $errorStream = ssh2_fetch_stream($stream, SSH2_STREAM_STDERR); stream_set_blocking($stream, 1); stream_set_blocking($errorStream, 1); $error = stream_get_contents($errorStream); $content = stream_get_contents($stream); fclose($errorStream); fclose($stream); if ($error) { $result = $this->createResult($error, true, $command); } else { $result = $this->createResult($content, false, $command); } $command->execEnd(); return $result; }
static function execute($user, $mdp, $cmd) { $connection = \ssh2_connect('localhost', 22); \ssh2_auth_password($connection, $user, $mdp); $table = array(); $stream = \ssh2_exec($connection, $cmd); sleep(1); stream_set_blocking($stream, true); $stderr_stream = \ssh2_fetch_stream($stream, SSH2_STREAM_STDERR); $res = ""; while ($line = fgets($stream)) { /*echo $line; flush();*/ $res .= $line . "\n"; } $table["sortie"] = $res; fclose($stream); $res = ""; while ($line = fgets($stderr_stream)) { $res .= $line . "\n"; } $table["error"] = $res; fclose($stderr_stream); return $table; }
public function execute($command) { $result_stream = ssh2_exec($this->ssh_connection, $command); $error_stream = ssh2_fetch_stream($result_stream, SSH2_STREAM_STDERR); stream_set_blocking($result_stream, true); stream_set_blocking($error_stream, true); $result = ""; while ($line = fgets($result_stream)) { flush(); $result .= $line; } $result_error = ""; while ($line = fgets($error_stream)) { flush(); $result_error .= $line; } fclose($result_stream); fclose($error_stream); if (!empty($result_error)) { return (object) array("stream" => "stderr", "result" => $result_error); } else { return (object) array("stream" => "stdout", "result" => $result); } }
/** * Start/Stop/Reboot an Host * * @param $ip_converter * @param string $command * * @return array */ protected function _rebootHost($ip_converter, $command = "restart") { $cmd = array(); $ret = array(); switch ($command) { case 'start': $cmd[] = "screen -d -m -S " . $this->host_machine_map[$ip_converter]['instance_name'] . " VBoxHeadless --startvm '" . $this->host_machine_map[$ip_converter]['instance_name'] . "'"; break; case 'stop': $cmd[] = " VBoxManage controlvm '" . $this->host_machine_map[$ip_converter]['instance_name'] . "' poweroff"; break; case 'restart': default: $cmd[] = " VBoxManage controlvm '" . $this->host_machine_map[$ip_converter]['instance_name'] . "' poweroff"; $cmd[] = "screen -d -m -S " . $this->host_machine_map[$ip_converter]['instance_name'] . " VBoxHeadless --startvm '" . $this->host_machine_map[$ip_converter]['instance_name'] . "'"; } self::_prettyEcho("Connecting to " . $this->host_machine_map[$ip_converter]['ip_machine_host']); $conn = ssh2_connect($this->host_machine_map[$ip_converter]['ip_machine_host'], 22); $authResult = ssh2_auth_password($conn, $this->host_machine_map[$ip_converter]['machine_host_user'], $this->host_machine_map[$ip_converter]['machine_host_pass']); if (!$authResult) { $ret[] = "Incorrect password !!!\n"; return array(-1, $ret); } else { $ret[] = "Password OK\n"; self::_prettyEcho("Sending Reboot Command to " . $ip_converter); foreach ($cmd as $c) { $stream = ssh2_exec($conn, $c); stream_set_blocking($stream, true); $stream_out = ssh2_fetch_stream($stream, SSH2_STREAM_STDIO); $ret_content = stream_get_contents($stream_out); sleep(15); fclose($stream); $ret[] = "command is {$c}"; $ret[] = $ret_content; } } return array(0, $ret); }
<?php $ip = 'banglaitalia.unibz.it'; $user = '******'; $pswd = 'bangla'; $connection = ssh2_connect($ip, 22); ssh2_auth_password($connection, $user, $pswd); include 'sql_details.php'; $result = mysql_query("SELECT active FROM dot_matrix_printer WHERE id = '1'"); if (!$result) { echo 'Could not run query: ' . mysql_error(); exit; } $row = mysql_fetch_row($result); $status = $row[0]; //print the status if ($status == 0) { //$stream = ssh2_exec($connection, './print.sh'); //$stream = ssh2_exec($connection, 'echo $PWD'); mysql_query("UPDATE dot_matrix_printer SET active = 1 WHERE id = 1"); $stream = ssh2_exec($connection, './print.sh'); stream_set_blocking($stream, true); $stream_out = ssh2_fetch_stream($stream, SSH2_STREAM_STDIO); echo stream_get_contents($stream_out); //echo "printing"; } else { echo "Failed printing"; } // fclose($stream);
/** * Execute a command and returns both stdout and stderr output * @access public * @param string $command remote shell command to execute * @return bool */ public function exec($command, $stopstring = false) { try { if ($this->isConnected()) { $stream = @ssh2_exec($this->connection, "{$command}", null, null, $this->termWidth, $this->termHeight, $this->termUnits); @stream_set_blocking($stream, true); @stream_set_timeout($stream, $this->timeout); $stderr_stream = @ssh2_fetch_stream($stream, SSH2_STREAM_STDERR); $this->stdErr = @fread($stderr_stream, 4096); @fclose($stderr_stream); if ($this->stdErr != '') { $this->logger->info("STDERR: {$this->stdErr}"); } // Read from stream while ($l = @fgets($stream, 4096)) { $meta = stream_get_meta_data($stream); if ($meta["timed_out"]) { break; } $retval .= $l; if ($stopstring && stripos($l, $stopstring) !== false) { break; } } if ($retval == '') { $retval = true; } // Close stream @fclose($stream); } else { return false; } } catch (Exception $e) { return false; } return $retval; }
/** * @param Queue $queue */ public function handle(Queue $queueService) { $waitingQueue = $queueService->getWaiting(); /** * Set queue as started, we'll execute it later. */ $waitingQueue->each(function (QueueRecord $queue) { $this->output('#' . $queue->id . ': ' . 'started (' . date('Y-m-d H:i:s') . ')'); $queue->changeStatus('started'); }, false); /** * Execute jobs. */ $waitingQueue->each(function (QueueRecord $queue) { $this->output('#' . $queue->id . ': ' . 'running (' . date('Y-m-d H:i:s') . ')'); $queue->changeStatus('running'); $this->output('#' . $queue->id . ': ' . $queue->command); $output = null; $sha1Id = sha1($queue->id); try { $timeout = strtotime($queue->execute_at) - time(); $command = $queue->command . ' && echo ' . $sha1Id; $lastLine = null; if (false && $timeout > 0) { exec('timeout -k 60 ' . $timeout . ' ' . $command, $output); } else { if (strpos($command, 'furs:')) { $command = str_replace(['/www/schtr4jh/derive.foobar.si/htdocs/', '/www/schtr4jh/beta.derive.foobar.si/htdocs/'], '/www/schtr4jh/bob.pckg.derive/htdocs/', $command); $connection = ssh2_connect(config('furs.sship'), 22); ssh2_auth_password($connection, config('furs.sshuser'), config('furs.sshpass')); $stream = ssh2_exec($connection, $command); $errorStream = ssh2_fetch_stream($stream, SSH2_STREAM_STDERR); stream_set_blocking($errorStream, true); stream_set_blocking($stream, true); $errorStreamContent = stream_get_contents($errorStream); $streamContent = stream_get_contents($stream); $output = $errorStreamContent . "\n" . $streamContent; $lastLine = substr($streamContent, -41, 40); } else { exec($command, $output); $lastLine = end($output); } } if ($lastLine != $sha1Id) { $queue->changeStatus('failed_permanently', ['log' => 'FAILED: ' . (is_string($output) ? $output : implode("\n", $output))]); return; throw new Exception('Job failed'); } } catch (Throwable $e) { $queue->changeStatus('failed_permanently', ['log' => exception($e)]); return; } if (!$output) { $queue->changeStatus('failed_permanently', ['log' => 'No output']); return; } $this->output('#' . $queue->id . ': ' . 'finished (' . date('Y-m-d H:i:s') . ')'); $queue->changeStatus('finished', ['log' => is_string($output) ? $output : implode("\n", $output)]); }, false); }