Author: Jim Wigginton (terrafrost@php.net)
Example #1
1
 /**
  * @param string $commandName
  * @param string $target
  * @param array  $targetConfig
  * @param array  $inputCommand
  * @param array  $userHomeDir
  * @return string
  */
 public function executeCommand($commandName, $target, $targetConfig, $inputCommand, $userHomeDir)
 {
     $remoteCommand = str_replace([sprintf('\'%s\'', $commandName), sprintf('target=\'%s\'', $target)], [$commandName, sprintf('root=%s', $targetConfig['root'])], $inputCommand);
     $remoteCommand = sprintf('%s %s', $targetConfig['console'], $remoteCommand);
     $key = null;
     if (array_key_exists('password', $targetConfig)) {
         $key = $targetConfig['password'];
     }
     if (!$key) {
         $key = new RSA();
         if (array_key_exists('passphrase', $targetConfig['keys'])) {
             $passphrase = $targetConfig['keys']['passphrase'];
             $passphrase = realpath(preg_replace('/~/', $userHomeDir, $passphrase, 1));
             $key->setPassword(trim(file_get_contents($passphrase)));
         }
         $private = $targetConfig['keys']['private'];
         $private = realpath(preg_replace('/~/', $userHomeDir, $private, 1));
         if (!$key->loadKey(trim(file_get_contents($private)))) {
             return $this->getTranslator()->trans('commands.site.debug.messages.private-key');
         }
     }
     $ssh = new SSH2($targetConfig['host'], $targetConfig['port']);
     if (!$ssh->login($targetConfig['user'], $key)) {
         return sprintf('%s - %s', $ssh->getExitStatus(), $ssh->getErrors());
     } else {
         return $ssh->exec($remoteCommand);
     }
 }
Example #2
1
 /**
  * Allow to execute and get the result of a command which can return more than one page on the CLI
  *
  * @param string   $cmd      The command to run
  * @param string   $regexp   A regex which will filter the rows. If a rows doesn't satisfy the regex, it will be
  *                           skipped.
  * @param Callable $callback A callback wich will be called for each rows. The first parameter is the rows itself,
  *                           the second parameter is the result of preg_match call on the row wich the regexp
  *                           provided
  * 
  * @return array
  *
  * @throws InvalidArgumentException If $callback is not a valid callback
  */
 protected function execPageableCommand(string $cmd, string $regexp, $callback) : array
 {
     if (false == is_callable($callback)) {
         throw new InvalidArgumentException("You must provide a valid callback");
     }
     $result = [];
     $this->ssh->write($cmd . $this->enterKey);
     $readPattern = '`' . $this->morePattern . '|' . $this->promptPattern . '`';
     while ($stdout = $this->ssh->read($readPattern, SSH2::READ_REGEX)) {
         foreach (explode("\n", $stdout) as $line) {
             if ($regexp == '' || $regexp == '`.*`' || $regexp == '`.+`') {
                 $result[] = $line;
                 continue;
             }
             preg_match($regexp, $line, $match);
             if (count($match) > 0) {
                 list($index, $value) = $callback($line, $match);
                 if ($index !== null) {
                     $result[$index] = $value;
                 } else {
                     $result[] = $value;
                 }
             }
         }
         if (preg_match('`' . $this->promptPattern . '`', $stdout) === 1) {
             break;
         }
         $this->ssh->write($this->spaceKey);
     }
     return $result;
 }
 public function testAgentLogin()
 {
     $ssh = new SSH2($this->getEnv('SSH_HOSTNAME'));
     $agent = new Agent();
     $this->assertTrue($ssh->login($this->getEnv('SSH_USERNAME'), $agent), 'SSH2 login using Agent failed.');
     return array('ssh' => $ssh, 'ssh-agent' => $agent);
 }
Example #4
0
 public function testOpenSocketConnect()
 {
     $fsock = fsockopen($this->getEnv('SSH_HOSTNAME'), 22);
     $ssh = new SSH2($fsock);
     $username = $this->getEnv('SSH_USERNAME');
     $password = $this->getEnv('SSH_PASSWORD');
     $this->assertTrue($ssh->login($username, $password), 'SSH2 login using an open socket failed.');
 }
 /**
  * Gets the SSH session using the auth given
  *
  * @param \App\Models\Auth $auth Auth model
  * @param \Ssh\Configuration $configuration SSH configuration object
  */
 protected function getSSHSession($auth, $host)
 {
     $session = new SSH2($host);
     if ($auth->isKeyAuthentication()) {
         $key = new RSA();
         $key->loadKey($auth->credentials->key);
         if (!$session->login($auth->credentials->username, $key)) {
             \log::error('Login Failed');
         }
     } else {
         if (!$session->login($auth->credentials->username, $auth->credentials->password)) {
             \log::error('Login Failed');
         }
     }
     return $session;
 }
Example #6
0
 /**
  * Tests connection reuse functionality same as ssh2 extension:
  * {@link http://php.net/manual/en/wrappers.ssh2.php#refsect1-wrappers.ssh2-examples}
  */
 public function testConnectionReuse()
 {
     $originalConnectionsCount = count(\phpseclib\Net\SSH2::getConnections());
     $session = $this->sftp;
     $dirs = scandir("sftp://{$session}/");
     $this->assertCount($originalConnectionsCount, \phpseclib\Net\SSH2::getConnections());
     $this->assertEquals(array('.', '..'), array_slice($dirs, 0, 2));
 }
Example #7
0
 /**
  * "Proper" disconnect
  */
 public function __destruct()
 {
     if ($this->ssh instanceof SSH2) {
         $this->ssh->disconnect();
     }
     if ($this->sftp instanceof SFTP) {
         $this->sftp->disconnect();
     }
 }
 /**
  * Send authentication
  *
  * @return bool
  */
 protected function _auth()
 {
     // check to see if already authenticated
     if ($this->_authenticated === true) {
         return true;
     }
     switch ($this->config('ssh.authType')) {
         case 'password':
             // perform password auth
             if ($this->_phpseclib->login($this->_credentials->getUsername(), $this->_credentials->getPassword())) {
                 //get last line and set as prompt
                 $response = $this->_phpseclib->read($this->config('prompt.command'));
                 $lines = split("\n", $response);
                 $this->config('prompt.command', trim(end($lines)));
                 $this->_authenticated = true;
                 return true;
             }
             break;
         case 'publicKey':
             // perform public key auth
             $this->_writeTmpKeys();
             $privkey = new \Crypt_RSA();
             //phpseclib has no DSA support :(
             $privkey->loadKey($this->_pubKeyTempFile);
             if ($this->_phpseclib->login($this->_credentials->getUsername(), $privkey)) {
                 $this->_destroyTmpKeys();
                 $this->_authenticated = true;
                 return true;
             }
             $this->_destroyTmpKeys();
             break;
     }
     //end switch()
     //return false;
     throw new \Exception('SSH ' . $this->config('ssh.authType') . ' Authentication Failed');
 }
Example #9
0
 /**
  * Disconnect
  *
  * @param int $reason
  * @return bool
  * @access private
  */
 function _disconnect($reason)
 {
     $this->pwd = false;
     parent::_disconnect($reason);
 }
 /**
  * @param SSH2 $ssh2
  * @return bool|void
  */
 public function loginForConnection(SSH2 $ssh2)
 {
     return $ssh2->login($this->getUsername());
 }
Example #11
0
 public function testGetConnectionByResourceId()
 {
     $ssh = new \phpseclib\Net\SSH2('localhost');
     $this->assertSame($ssh, \phpseclib\Net\SSH2::getConnectionByResourceId($ssh->getResourceId()));
 }
Example #12
0
 /**
  * Path Parser
  *
  * Extract a path from a URI and actually connect to an SSH server if appropriate
  *
  * If "notification" is set as a context parameter the message code for successful login is
  * NET_SSH2_MSG_USERAUTH_SUCCESS. For a failed login it's NET_SSH2_MSG_USERAUTH_FAILURE.
  *
  * @param string $path
  * @return string
  * @access private
  */
 function _parse_path($path)
 {
     $orig = $path;
     extract(parse_url($path) + array('port' => 22));
     if (isset($query)) {
         $path .= '?' . $query;
     } elseif (preg_match('/(\\?|\\?#)$/', $orig)) {
         $path .= '?';
     }
     if (isset($fragment)) {
         $path .= '#' . $fragment;
     } elseif ($orig[strlen($orig) - 1] == '#') {
         $path .= '#';
     }
     if (!isset($host)) {
         return false;
     }
     if (isset($this->context)) {
         $context = stream_context_get_params($this->context);
         if (isset($context['notification'])) {
             $this->notification = $context['notification'];
         }
     }
     if (preg_match('/^{[a-z0-9]+}$/i', $host)) {
         $host = SSH2::getConnectionByResourceId($host);
         if ($host === false) {
             return false;
         }
         $this->sftp = $host;
     } else {
         if (isset($this->context)) {
             $context = stream_context_get_options($this->context);
         }
         if (isset($context[$scheme]['session'])) {
             $sftp = $context[$scheme]['session'];
         }
         if (isset($context[$scheme]['sftp'])) {
             $sftp = $context[$scheme]['sftp'];
         }
         if (isset($sftp) && $sftp instanceof SFTP) {
             $this->sftp = $sftp;
             return $path;
         }
         if (isset($context[$scheme]['username'])) {
             $user = $context[$scheme]['username'];
         }
         if (isset($context[$scheme]['password'])) {
             $pass = $context[$scheme]['password'];
         }
         if (isset($context[$scheme]['privkey']) && $context[$scheme]['privkey'] instanceof RSA) {
             $pass = $context[$scheme]['privkey'];
         }
         if (!isset($user) || !isset($pass)) {
             return false;
         }
         // casting $pass to a string is necessary in the event that it's a \phpseclib\Crypt\RSA object
         if (isset(self::$instances[$host][$port][$user][(string) $pass])) {
             $this->sftp = self::$instances[$host][$port][$user][(string) $pass];
         } else {
             $this->sftp = new SFTP($host, $port);
             $this->sftp->disableStatCache();
             if (isset($this->notification) && is_callable($this->notification)) {
                 /* if !is_callable($this->notification) we could do this:
                 
                                        user_error('fopen(): failed to call user notifier', E_USER_WARNING);
                 
                                        the ftp wrapper gives errors like that when the notifier isn't callable.
                                        i've opted not to do that, however, since the ftp wrapper gives the line
                                        on which the fopen occurred as the line number - not the line that the
                                        user_error is on.
                                     */
                 call_user_func($this->notification, STREAM_NOTIFY_CONNECT, STREAM_NOTIFY_SEVERITY_INFO, '', 0, 0, 0);
                 call_user_func($this->notification, STREAM_NOTIFY_AUTH_REQUIRED, STREAM_NOTIFY_SEVERITY_INFO, '', 0, 0, 0);
                 if (!$this->sftp->login($user, $pass)) {
                     call_user_func($this->notification, STREAM_NOTIFY_AUTH_RESULT, STREAM_NOTIFY_SEVERITY_ERR, 'Login Failure', NET_SSH2_MSG_USERAUTH_FAILURE, 0, 0);
                     return false;
                 }
                 call_user_func($this->notification, STREAM_NOTIFY_AUTH_RESULT, STREAM_NOTIFY_SEVERITY_INFO, 'Login Success', NET_SSH2_MSG_USERAUTH_SUCCESS, 0, 0);
             } else {
                 if (!$this->sftp->login($user, $pass)) {
                     return false;
                 }
             }
             self::$instances[$host][$port][$user][(string) $pass] = $this->sftp;
         }
     }
     return $path;
 }
 /**
  * SSH connect via user&passwd or user&rsakey
  *
  * @param string $addr
  * @param string $port
  * @param bool $type - connect via user&rsakey(true), user&password(false)
  * @return mixed object | false
  */
 protected function sshConnect($addr, $port, $type)
 {
     set_error_handler(array($this, "myErrorHandler"), E_ALL);
     $ssh = new SSH2($addr, $port);
     // user&password
     $ssh->setWindowSize(1024, 768);
     if (!$type && $ssh->login($this->config['routerboard']['rblogin'], $this->config['routerboard']['rbpasswd'])) {
         return $ssh;
     }
     // user&rsakey
     if ($type) {
         $key = new RSA();
         $key->loadKey(file_get_contents($this->config['system']['ssh-dir'] . DIRECTORY_SEPARATOR . 'id_rsa'));
         if ($ssh->login($this->config['routerboard']['backupuser'], $key)) {
             return $ssh;
         }
     }
     return false;
 }
Example #14
0
 /**
  * @param SSH2|SFTP $connector
  * @return SSH2|SFTP
  * @throws \Exception
  */
 protected function auth($connector)
 {
     switch ($this->auth) {
         case self::AUTH_KEYFILE:
             $password = new RSA();
             if (!is_null($this->getPassword())) {
                 $password->setPassword($this->getPassword());
             }
             $password->loadKey($this->getKeyfile());
             break;
         case self::AUTH_PASSWORD:
             // break intentionally omitted
         // break intentionally omitted
         default:
             $password = $this->getPassword();
             break;
     }
     if (!isset($password)) {
         $loggedIn = $connector->login($this->username);
     } else {
         $loggedIn = $connector->login($this->username, $password);
     }
     if (!$loggedIn) {
         throw new \Exception(sprintf('SSH authentication (%s) with %s on %s:%s failed!', $this->auth, $this->username, $this->hostname, $this->port));
     }
     return $connector;
 }
Example #15
0
 private function deleteVirtualHost($filehosts)
 {
     $this->info("Deleting virtualhost");
     $this->error('Attenzione il virtual host di ' . $this->workbenchSettings->requested['domain']['valore'] + ' verrĂ  eliminato.');
     $apachedir = "/var/www/html/";
     $ssh = new SSH2($this->workbenchSettings->requested['sshhost']['valore']);
     //ToDo
     if (!$ssh->login($this->workbenchSettings->requested['sshuser']['valore'], $this->workbenchSettings->requested['sshpassword']['valore'])) {
         exit('SSH login failed at ' . $this->workbenchSettings->requested['sshuser']['valore'] . '@' . $this->workbenchSettings->requested['sshuser']['valore']);
     }
     $ssh->exec('a2dissite ' . $this->workbenchSettings->requested['domain']['valore']);
     $ssh->exec('/etc/init.d/apache2 reload');
     $ssh->exec('rm /etc/apache2/sites-available/' . $this->workbenchSettings->requested['domain']['valore'] . '.conf');
     $this->info("Virtualhost deleted");
     if ($filehosts) {
         $this->removeToFileHosts($ssh);
     }
 }
 public function testConstructSSH2()
 {
     $ssh = new SSH2($this->getEnv('SSH_HOSTNAME'));
     $this->assertTrue($ssh->login($this->getEnv('SSH_USERNAME'), $this->getEnv('SSH_PASSWORD')));
     return $ssh;
 }
Example #17
0
 public function refreshHardware()
 {
     $this->view = false;
     $db = $this->di['db']->sql(DB_DEFAULT);
     $sql = "SELECT * FROM `mysql_server` WHERE `key_public_path` != '' and `key_public_user` != ''";
     $res = $db->sql_query($sql);
     while ($ob = $db->sql_fetch_object($res)) {
         echo $ob->ip . "\n";
         $ssh = new SSH2($ob->ip);
         $key = new RSA();
         $key->loadKey(file_get_contents($ob->key_public_path));
         if (!$ssh->login($ob->key_public_user, $key)) {
             echo "Login Failed";
             continue;
         }
         $memory = $ssh->exec("grep MemTotal /proc/meminfo | awk '{print \$2}'");
         $nb_cpu = $ssh->exec("cat /proc/cpuinfo | grep processor | wc -l");
         $brut_memory = $ssh->exec("cat /proc/meminfo | grep MemTotal");
         preg_match("/[0-9]+/", $brut_memory, $memory);
         $mem = $memory[0];
         $memory = sprintf('%.2f', $memory[0] / 1024 / 1024) . " Go";
         $freq_brut = $ssh->exec("cat /proc/cpuinfo | grep 'cpu MHz'");
         preg_match("/[0-9]+\\.[0-9]+/", $freq_brut, $freq);
         $frequency = sprintf('%.2f', $freq[0] / 1000) . " GHz";
         $os = trim($ssh->exec("lsb_release -ds"));
         $distributor = trim($ssh->exec("lsb_release -si"));
         if (empty($os)) {
             $os = trim($ssh->exec("cat /etc/centos-release"));
             $distributor = trim("Centos");
         }
         $product_name = $ssh->exec("dmidecode -s system-product-name");
         $arch = $ssh->exec("uname -m");
         $kernel = $ssh->exec("uname -r");
         $hostname = $ssh->exec("hostname");
         $swapiness = $ssh->exec("cat /proc/sys/vm/swappiness");
         /*
          $system = $ssh->exec("uptime");// get the uptime stats
         
          $uptime = explode(" ", $system); // break up the stats into an array
         
          $up_days = $uptime[4]; // grab the days from the array
         
          $hours = explode(":", $uptime[7]); // split up the hour:min in the stats
         
          $up_hours = $hours[0]; // grab the hours
          $mins = $hours[1]; // get the mins
          $up_mins = str_replace(",", "", $mins); // strip the comma from the mins
         
          echo "The server has been up for " . $up_days . " days, " . $up_hours . " hours, and " . $up_mins . " minutes.";
         */
         $sql = "UPDATE mysql_server SET operating_system='" . $db->sql_real_escape_string($os) . "',\r\n                   distributor='" . trim($distributor) . "',\r\n                   processor='" . trim($nb_cpu) . "',\r\n                   cpu_mhz='" . trim($freq[0]) . "',\r\n                   product_name='" . trim($product_name) . "',\r\n                   arch='" . trim($arch) . "',\r\n                   kernel='" . trim($kernel) . "',\r\n                   hostname='" . trim($hostname) . "',\r\n                   memory_kb='" . trim($mem) . "', \r\n                   swappiness='" . trim($swapiness) . "' \r\n                   WHERE id='" . $ob->id . "'";
         $db->sql_query($sql);
     }
 }
Example #18
0
<?php

include 'vendor/autoload.php';
use phpseclib\Net\SSH2;
use phpseclib\File\ANSI;
$ansi = new ANSI();
echo <<<HTML
\t<form action="ssh.php" method="POST">
\t\t<label for="host">Host</label>
\t\t<input name="host">
\t\t<label for="user">Username</label>
\t\t<input name="user">
\t\t<label for="pass">Password</label>
\t\t<input name="pass" type="password">
\t\t<label for="port">Port</label>
\t\t<input name="port" value="22">
\t\t<input type="submit">
\t</form>
HTML;
extract($_POST);
if (isset($host, $user, $pass)) {
    $ssh = new SSH2($host, $port);
    if (!$ssh->login($user, $pass)) {
        exit('Login Failed');
    }
    $ansi->appendString($ssh->read('username@username:~$'));
    $ansi->appendString($ssh->read());
    echo $ansi->getScreen();
}
Example #19
0
 function ssh2()
 {
     $ssh = new SSH2('10.0.51.117');
     if (!$ssh->login('root', 'zeb33tln')) {
         exit('Login Failed');
     }
     echo $ssh->exec('pwd');
     echo $ssh->exec('ls -la');
     echo $ssh->exec('whereis screen');
 }