Example #1
5
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;
}
Example #2
0
 function coneccionSshImg($ids, $mBanner, $config)
 {
     $porciones = explode(",", $ids);
     foreach ($porciones as $value) {
         $dataBanner = $mBanner->select($value);
         $avanzado = ROOT_IMG_DINAMIC . '/banner/avanzado/' . $dataBanner["ImgAvanzado"];
         $basico128 = ROOT_IMG_DINAMIC . '/banner/basico128/' . $dataBanner["ImgBasico128"];
         $basico240 = ROOT_IMG_DINAMIC . '/banner/basico240/' . $dataBanner["ImgBasico240"];
         $basico360 = ROOT_IMG_DINAMIC . '/banner/basico360/' . $dataBanner["ImgBasico360"];
         if (!function_exists("ssh2_connect")) {
             die("function ssh2_connect doesn't exist");
         }
         if (!($con = ssh2_connect($config['app']['server'], $config['app']['puerto']))) {
             echo "fail: unable to establish connection\n";
         } else {
             if (!ssh2_auth_password($con, $config['app']['user'], $config['app']['pass'])) {
                 echo "fail: unable to authenticate\n";
             } else {
                 ssh2_scp_send($con, $avanzado, $config['app']['rutaImg'] . 'banner/avanzado/' . $dataBanner["ImgAvanzado"], 0644);
                 ssh2_scp_send($con, $basico128, $config['app']['rutaImg'] . 'banner/basico128/' . $dataBanner["ImgBasico128"], 0644);
                 ssh2_scp_send($con, $basico240, $config['app']['rutaImg'] . 'banner/basico240/' . $dataBanner["ImgBasico240"], 0644);
                 ssh2_scp_send($con, $basico360, $config['app']['rutaImg'] . 'banner/basico360/' . $dataBanner["ImgBasico360"], 0644);
             }
             ssh2_exec($con, 'exit');
         }
     }
     return;
 }
Example #3
0
 public function ssh()
 {
     if (!function_exists("ssh2_connect")) {
         die("function ssh2_connect doesn't exist");
     }
     // log in at server1.example.com on port 22
     if (!($con = ssh2_connect("nao.local", 22))) {
         echo "fail: unable to establish connection\n";
     } else {
         //try to authenticate with username root, password secretpassword
         if (!ssh2_auth_password($con, "nao", "nao")) {
             echo "fail: unable to authenticate\n";
         } else {
             // allright, we're in!
             echo "okay: logged in...\n";
             // execute a command
             if (!($stream = ssh2_exec($con, "ls -al"))) {
                 echo "fail: unable to execute command\n";
             } else {
                 // collect returning data from command
                 stream_set_blocking($stream, true);
                 $data = "";
                 while ($buf = fread($stream, 4096)) {
                     $data .= $buf;
                 }
                 fclose($stream);
             }
         }
     }
 }
Example #4
0
 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!');
 }
Example #5
0
 protected static function conn_close($conn)
 {
     if (ssh2_exec($conn, 'exit') === false) {
         return false;
     }
     return true;
 }
function get_list($myhost, $usern, $passw, $mypath, &$data)
{
    if (!function_exists("ssh2_connect")) {
        die("function ssh2_connect doesn't exist");
    }
    if (!($conn = ssh2_connect($myhost, 22))) {
        echo "fail: unable to establish connection\n";
    } else {
        if (!ssh2_auth_password($conn, $usern, $passw)) {
            echo "fail: unable to authenticate\n";
        } else {
            if (!($stream = ssh2_exec($conn, "ls -1 " . $mypath))) {
                echo "fail: unable to execute command\n";
            } else {
                stream_set_blocking($stream, true);
                // allow command to finish
                $data = "";
                while ($buf = fread($stream, 4096)) {
                    $data .= $buf;
                }
                fclose($stream);
            }
        }
    }
    ssh2_exec($conn, 'exit');
}
Example #7
0
 /**
  * @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;
 }
Example #8
0
 /**
  * 执行远程命令。
  * 
  * @param string $command 指定命令字符串。
  * @return resource|boolean
  * @throws NetworkException
  */
 function execute($command)
 {
     if (!$this->shell_ok) {
         throw new NetworkException('尚未连接远程主机。', -1);
     }
     $r = ssh2_exec($this->shell_session, $command);
     return $r;
 }
Example #9
0
 function execute($command, $pty = null, array $env = array(), $width = 80, $height = 25, $width_height_type = SSH2_TERM_UNIT_CHARS)
 {
     $stream = ssh2_exec($this->ssh, $command, $env, $width, $height, $width_height_type);
     if (false === $stream) {
         throw new SSHException('Couldnt execute command, no stream returned');
     }
     stream_set_blocking($stream, true);
     return stream_get_contents($stream);
 }
Example #10
0
 public function doExec($obj, $out_cb)
 {
     if (empty($this->_cmd)) {
         throw new \Exception('cmd is invaild');
     }
     $stream = ssh2_exec($this->_ins, $this->_cmd);
     stream_set_blocking($stream, true);
     call_user_func_array(array($obj, $out_cb), array($stream));
 }
Example #11
0
 public function command($command)
 {
     $stream = ssh2_exec($this->connection, $command);
     $this->logs[] = '$ ' . $command;
     stream_set_blocking($stream, true);
     $d = fread($stream, 4096);
     fclose($stream);
     $this->logs[] = $d;
     return $d;
 }
Example #12
0
 public function killSc_Trans($sc_rel_id)
 {
     $PID = \DB::queryFirstRow("SELECT sc_trans_pid FROM sc_rel WHERE id=%s", $sc_rel_id);
     $SSHConf = $this->getSSHConf();
     $connection = ssh2_connect($SSHConf['ip'], $SSHConf['port']);
     ssh2_auth_password($connection, $SSHConf['user'], $SSHConf['pass']);
     ssh2_exec($connection, 'kill ' . $PID['sc_trans_pid']);
     sleep(1);
     $this->setPID($sc_rel_id, '0');
 }
Example #13
0
 public function exec($command = "")
 {
     if ($this->cwd && strlen($this->cwd) > 0) {
         $command = 'cd "' . $this->cwd . '"; ' . $command;
     }
     $stream = ssh2_exec($this->session, $command);
     stream_set_blocking($stream, true);
     // The command may not finish properly if the stream is not read to end
     $output = stream_get_contents($stream);
     return trim($output);
 }
Example #14
0
 public function sshExec($id)
 {
     $node = Node::getById($id);
     $connection = ssh2_connect(Config::get('ssh.host'), Config::get('ssh.port'));
     if (!$connection) {
         die('Connection failed');
     }
     ssh2_auth_password($connection, Config::get('ssh.username'), Config::get('ssh.password'));
     $stream = ssh2_exec($connection, '/usr/local/bin/php -i');
     return Redirect::back();
 }
 private function run($cmd)
 {
     if ($h = ssh2_exec($this->handle, $cmd)) {
         stream_set_blocking($h, true);
         stream_set_timeout($h, $this->timeout);
         $result = stream_get_contents($h);
         fclose($h);
         return $result;
     }
     return false;
 }
Example #16
0
 private function removeKey($key)
 {
     $connection = ssh2_connect($this->server->ip);
     $rC = 0;
     do {
         ssh2_exec($connection, "grep -v #{$key->contact}@{$this->server} {$this->home}/.ssh/authorized_keys > akTmp && mv akTmp {$this->home}/.ssh/authorized_keys");
         ssh2_exec($connection, "grep -v {$key->pubKey} {$this->home}/.ssh/authorized_keys > akTmp && mv akTmp {$this->home}/.ssh/authorized_keys");
         sleep(1);
         $rC++;
     } while (!$stream && $rC < 3);
 }
Example #17
0
 public function exec($command, $callback = null)
 {
     if ($this->isInBlock) {
         return $this->addCommand($command);
     }
     $stream = \ssh2_exec($this->resource, $command);
     if (null !== $callback) {
         $this->callCallback($stream, $callback);
     }
     return $this;
 }
Example #18
0
 /**
  * Executes provided command string through an SSH session in a remote terminal.
  * @return String The command's output
  */
 protected function _executeStringRemotely($commandString, Garp_Shell_RemoteSession $session)
 {
     if (!($stream = ssh2_exec($session->getSshSession(), $commandString))) {
         return false;
     }
     stream_set_blocking($stream, true);
     $content = stream_get_contents($stream);
     $this->_bubbleSshErrors($stream, $commandString);
     fclose($stream);
     return $content;
 }
Example #19
0
 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;
 }
Example #21
0
 function exec($cmd)
 {
     //$shell = ssh2_shell($this->ssh_connection, 'xterm');
     //fwrite($shell, 'cd /tmp && pwd;'.PHP_EOL);
     if (strstr($cmd, "&&")) {
         $stream = ssh2_exec($this->ssh_connection, $cmd);
     }
     stream_set_blocking($stream, TRUE);
     $cmd_ret = fread($stream, 4096);
     fclose($stream);
     return $cmd_ret;
 }
Example #22
0
 /**
  * @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);
 }
Example #23
0
 function exec($command)
 {
     $stdout = ssh2_exec($this->ssh2, $command);
     if (!$stdout) {
         throw new \Exception("can't execute {$command}");
     }
     // set stdour stream to blocking as it is non-blocking by default
     stream_set_blocking($stdout, true);
     $out = stream_get_contents($stdout);
     fclose($stdout);
     return $out;
 }
Example #24
0
 /**
  * Execute a SSH command
  *
  * @param string $cmd The SSH command
  *
  * @return string The output
  */
 protected function exec($cmd)
 {
     if (false === ($stream = ssh2_exec($this->con, $cmd))) {
         throw new SshException(sprintf('"%s" : SSH command failed', $cmd));
     }
     stream_set_blocking($stream, true);
     $data = '';
     while ($buf = fread($stream, 4096)) {
         $data .= $buf;
     }
     fclose($stream);
     return $data;
 }
Example #25
0
 public function exec($string, $async = false)
 {
     $this->_reset_status();
     $stream = ssh2_exec($this->conn, $string);
     if ($async) {
         stream_set_blocking($stream, 0);
         return $this->_reset_status();
     } else {
         stream_set_blocking($stream, 1);
         $this->_reset_status();
         return fread($stream, 10240);
     }
 }
Example #26
0
 public function execute($command, SSHConnection $context)
 {
     $ret = null;
     $stream = ssh2_exec($this->resource, $command);
     if (!is_resource($stream)) {
         throw new \RuntimeException();
     }
     stream_set_blocking($stream, true);
     while (($line = \fgets($stream, 4096)) !== false) {
         $ret .= $line;
     }
     return $ret;
 }
Example #27
0
 /**
  * Typically called from Connection::execute()
  *
  * @param string     $command
  * @param Connection $connection
  * @param Terminal   $terminal
  * @param string     $pty
  */
 function __construct($command, Connection $connection, Terminal $terminal, $pty = null)
 {
     $this->command = $command;
     $this->connection = $connection;
     $this->terminal = $terminal;
     if (!$connection->isConnected()) {
         throw new NotConnectedException();
     }
     if (!$connection->isAuthenticated()) {
         throw new NotAuthenticatedException();
     }
     $this->resource = ssh2_exec($connection->getResource(), $command, $pty, $terminal->getEnv(), $terminal->getWidth(), $terminal->getHeight(), $terminal->getDimensionUnitType());
 }
Example #28
0
 public function exec($cmd)
 {
     if (!($stream = ssh2_exec($this->con, $cmd))) {
         throw new Exception('SSH command failed');
     }
     stream_set_blocking($stream, true);
     $data = "";
     while ($buf = fread($stream, 4096)) {
         $data .= $buf;
     }
     fclose($stream);
     //        return $data;
 }
Example #29
-1
 /**
  * @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);
 }
Example #30
-1
 function sync_logos()
 {
     if ($this->ssh2_connection) {
         debug("Syncing logos");
         ssh2_exec($this->ssh2_connection, "/bin/rsync_scripts/download-content-partners.cgi");
     }
 }