/** * */ public function connect() { $this->ssh = new SSH2($this->configuration['hostname'], $this->configuration['port']); $authenticationMethod = $this->configuration[SftpDriver::CONFIG_AUTHENTICATION_METHOD]; if (static::AUTHENTICATION_PASSWORD === (int) $authenticationMethod) { $authentication = $this->configuration['password']; } elseif (static::AUTHENTICATION_PUBKEY === (int) $authenticationMethod) { $authentication = new RSA(); if (!empty($this->configuration['privateKeyPassword'])) { $authentication->setPassword($this->configuration['privateKeyPassword']); } $authentication->loadKey(file_get_contents($this->configuration['privateKey'])); } else { throw new \LogicException('Wrong authentication type for phpseclibAdapter', 1476626149); } $sshConnected = $this->ssh->login($this->configuration['username'], $authentication); if ($sshConnected) { $this->sftp = new SFTP($this->configuration['hostname'], $this->configuration['port']); $sftpConnected = $this->sftp->login($this->configuration['username'], $authentication); if ($sftpConnected) { $this->info['userId'] = (int) $this->ssh->exec('echo $EUID'); $this->info['groupIds'] = GeneralUtility::intExplode(' ', $this->ssh->exec('echo ${GROUPS[*]}'), true); return true; } } return false; }
/** * @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); } }
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); }
/** * 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; }
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.'); }
/** * Establish a SSH connection to the switch if necessary * * @throws ConnectionException If the connection fails */ protected function connect() { if (false == $this->ssh instanceof SSH2) { $this->ssh = new SSH2($this->ip); $this->ssh->setWindowSize($this->terminalColumn, $this->terminalLine); if (false == @$this->ssh->login($this->user, $this->password)) { throw new ConnectionException(sprintf("Connection to %s with user %s failed", $this->ip, $this->user)); } $this->ssh->read('continue'); $this->ssh->write($this->enterKey); $this->ssh->read('`' . $this->promptPattern . '`', SSH2::READ_REGEX); } }
/** * 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'); }
<?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(); }
public function testConstructSSH2() { $ssh = new SSH2($this->getEnv('SSH_HOSTNAME')); $this->assertTrue($ssh->login($this->getEnv('SSH_USERNAME'), $this->getEnv('SSH_PASSWORD'))); return $ssh; }
/** * @param SSH2 $ssh2 * @return bool|void */ public function loginForConnection(SSH2 $ssh2) { return $ssh2->login($this->getUsername()); }
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); } }
/** * 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; }
/** * @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; }
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); } }
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'); }