The following java examples will help you to understand the usage of ch.ethz.ssh2.Session. These source code samples are taken from different open source projects.
Example 1
| Project: AmazonEC2Matlab-master File: SwingShell.java View source code |
public void run() { Connection conn = new Connection(hostname); try { /* * * CONNECT AND VERIFY SERVER HOST KEY (with callback) * */ String[] hostkeyAlgos = database.getPreferredServerHostkeyAlgorithmOrder(hostname); if (hostkeyAlgos != null) conn.setServerHostKeyAlgorithms(hostkeyAlgos); conn.connect(new AdvancedVerifier()); /* * * AUTHENTICATION PHASE * */ boolean enableKeyboardInteractive = true; boolean enableDSA = true; boolean enableRSA = true; String lastError = null; while (true) { if ((enableDSA || enableRSA) && conn.isAuthMethodAvailable(username, "publickey")) { if (enableDSA) { File key = new File(idDSAPath); if (key.exists()) { EnterSomethingDialog esd = new EnterSomethingDialog(loginFrame, "DSA Authentication", new String[] { lastError, "Enter DSA private key password:" }, true); esd.setVisible(true); boolean res = conn.authenticateWithPublicKey(username, key, esd.answer); if (res == true) break; lastError = "DSA authentication failed."; } // do not try again enableDSA = false; } if (enableRSA) { File key = new File(idRSAPath); if (key.exists()) { EnterSomethingDialog esd = new EnterSomethingDialog(loginFrame, "RSA Authentication", new String[] { lastError, "Enter RSA private key password:" }, true); esd.setVisible(true); boolean res = conn.authenticateWithPublicKey(username, key, esd.answer); if (res == true) break; lastError = "RSA authentication failed."; } // do not try again enableRSA = false; } continue; } if (enableKeyboardInteractive && conn.isAuthMethodAvailable(username, "keyboard-interactive")) { InteractiveLogic il = new InteractiveLogic(lastError); boolean res = conn.authenticateWithKeyboardInteractive(username, il); if (res == true) break; if (il.getPromptCount() == 0) { // aha. the server announced that it supports "keyboard-interactive", but when // we asked for it, it just denied the request without sending us any prompt. // That happens with some server versions/configurations. // We just disable the "keyboard-interactive" method and notify the user. lastError = "Keyboard-interactive does not work."; // do not try this again enableKeyboardInteractive = // do not try this again false; } else { lastError = "Keyboard-interactive auth failed."; } continue; } if (conn.isAuthMethodAvailable(username, "password")) { final EnterSomethingDialog esd = new EnterSomethingDialog(loginFrame, "Password Authentication", new String[] { lastError, "Enter password for " + username }, true); esd.setVisible(true); if (esd.answer == null) throw new IOException("Login aborted by user"); boolean res = conn.authenticateWithPassword(username, esd.answer); if (res == true) break; // try again, if possible lastError = "Password authentication failed."; continue; } throw new IOException("No supported authentication methods available."); } /* * * AUTHENTICATION OK. DO SOMETHING. * */
Session sess = conn.openSession(); int x_width = 90; int y_width = 30; sess.requestPTY("dumb", x_width, y_width, 0, 0, null); sess.startShell(); TerminalDialog td = new TerminalDialog(loginFrame, username + "@" + hostname, sess, x_width, y_width); /* The following call blocks until the dialog has been closed */ td.setVisible(true); } catch (IOException e) { JOptionPane.showMessageDialog(loginFrame, "Exception: " + e.getMessage()); } /* * * CLOSE THE CONNECTION. * */ conn.close(); /* * * CLOSE THE LOGIN FRAME - APPLICATION WILL BE EXITED (no more frames) * */ Runnable r = new Runnable() { public void run() { loginFrame.dispose(); } }; SwingUtilities.invokeLater(r); }Example 2
| Project: corona_src-master File: SshClient.java View source code |
private static String execCmd_(
Session sess, String command) throws IOException { sess.execCommand(command); InputStream stdout = new StreamGobbler(sess.getStdout()); BufferedReader br = new BufferedReader(new InputStreamReader(stdout)); StringBuilder sb = new StringBuilder(); while (true) { String line = br.readLine(); if (line == null) { break; } sb.append(line + "\n"); } return sb.toString(); }Example 3
| Project: Metamorphosis-master File: SSHSupport.java View source code |
public String execute(String cmd) throws RemoteExecuteException { StringBuilder result = new StringBuilder(); try { Connection conn = new Connection(this.ip); conn.connect(); boolean isAuthenticated = conn.authenticateWithPassword(this.user, this.password); if (isAuthenticated == false) { result.append("ERROR: Authentication Failed !"); }
Session session = conn.openSession(); session.execCommand(cmd); BufferedReader read = new BufferedReader(new InputStreamReader(new StreamGobbler(session.getStdout()), "GBK")); String line = ""; while ((line = read.readLine()) != null) { result.append(line).append("\r\n"); } session.close(); conn.close(); return result.toString(); } catch (Throwable e) { throw new RemoteExecuteException("ִ���������", e); } }Example 4
| Project: fastdfs-zyc-master File: Tools.java View source code |
public static List<String> exeRemoteConsole(String hostname, String username, String password, String cmd) { List<String> result = new ArrayList<String>(); //指明连接主机的IP地址 Connection conn = new Connection(hostname);
Session ssh = null; try { //连接到主机 conn.connect(); //使用用户名和密码校验 boolean isconn = conn.authenticateWithPassword(username, password); if (!isconn) { logger.error("用户名称或者是密码不正确"); } else { logger.info("已经连接OK"); ssh = conn.openSession(); //使用多个命令用分号隔开 // ssh.execCommand("pwd;cd /tmp;mkdir shb;ls;ps -ef|grep weblogic"); ssh.execCommand(cmd); //只允许使用一行命令,即ssh对象只能使用一次execCommand这个方法,多次使用则会出现异常 // ssh.execCommand("mkdir hb"); //将屏幕上的文字全部打印出来 InputStream is = new StreamGobbler(ssh.getStdout()); BufferedReader brs = new BufferedReader(new InputStreamReader(is)); for (String line = brs.readLine(); line != null; line = brs.readLine()) { result.add(line); } } //连接的Session和Connection对象都需要关闭 if (ssh != null) { ssh.close(); } conn.close(); } catch (IOException e) { logger.error("", e); } return result; }Example 5
| Project: onos-master File: NetconfSessionImpl.java View source code |
private void startSshSession() throws NetconfException { try { sshSession = netconfConnection.openSession(); sshSession.startSubSystem("netconf"); streamHandler = new NetconfStreamThread(sshSession.getStdout(), sshSession.getStdin(), sshSession.getStderr(), deviceInfo, new NetconfSessionDelegateImpl(), replies); this.addDeviceOutputListener(new FilteringNetconfDeviceOutputEventListener(deviceInfo)); sendHello(); } catch (IOException e) { log.error("Failed to create ch.ethz.ssh2.
Session session {} ", e.getMessage()); throw new NetconfException("Failed to create ch.ethz.ssh2.
Session session with device" + deviceInfo, e); } }Example 6
| Project: ankush-master File: SSHConnection.java View source code |
/** * Exec. * * @param command * the command * @return true, if successful */ public boolean exec(String command) { if (connection == null) { logger.error("Connection is empty."); return false; }
Session session = null; try { session = connection.openSession(); logger.debug("Going to execute command " + command); session.execCommand(command); Integer exitStatus = session.getExitStatus(); while (exitStatus == null) { exitStatus = session.getExitStatus(); // Waiting for the complete execution of the command. } if (session.getStdout() != null) { output = processInputStream(session.getStdout()); } if (session.getStderr() != null) { error = processInputStream(session.getStderr()); } this.exitStatus = session.getExitStatus(); if (this.exitStatus == 0) { logger.debug("Execute successfully for command: " + command); // logger.debug("Command Output: " + output); } else { logger.debug("Execution failed for command: " + command); // logger.debug("Command Output: " + output); logger.debug("Command Error: " + error); } } catch (IOException e) { logger.error(CMD_EXECUTION_FAILURE_ERR_MSG + e.getMessage()); } catch (Exception e) { logger.error(CMD_EXECUTION_FAILURE_ERR_MSG + e.getMessage()); } finally { if (session != null) { session.close(); session = null; } closeConnection(); } return exitStatus == 0; }Example 7
| Project: mina-sshd-master File: MacTest.java View source code |
@Test public void testWithJSCH() throws Exception { String macName = factory.getName(); Assume.assumeTrue("Known JSCH bug with " + macName, !BuiltinMacs.hmacsha512.equals(factory)); JSch sch = new JSch(); JSch.setConfig("cipher.s2c", "aes128-cbc,3des-cbc,blowfish-cbc,aes192-cbc,aes256-cbc,none"); JSch.setConfig("cipher.c2s", "aes128-cbc,3des-cbc,blowfish-cbc,aes192-cbc,aes256-cbc,none"); JSch.setConfig("mac.s2c", macName); JSch.setConfig("mac.c2s", macName); JSch.setConfig(macName, jschMacClass); com.jcraft.jsch.
Session session = sch.getSession(getCurrentTestName(), TEST_LOCALHOST, port); try { session.setUserInfo(new SimpleUserInfo(getCurrentTestName())); session.connect(); com.jcraft.jsch.Channel channel = session.openChannel(Channel.CHANNEL_SHELL); channel.connect(); try (OutputStream stdin = channel.getOutputStream(); InputStream stdout = channel.getInputStream(); InputStream stderr = channel.getExtInputStream()) { runShellTest(stdin, stdout); } finally { channel.disconnect(); } } finally { session.disconnect(); } }Example 8
| Project: cachecloud-master File: SSHTemplate.java View source code |
/** * 执行命令并返回结果,可以执行多次 * @param cmd * @param lineProcessor 回调处理行 * @return 如果lineProcessor不为null,那么永远返回Result.true */ public Result executeCommand(String cmd, LineProcessor lineProcessor, int timoutMillis) {
Session session = null; try { session = conn.openSession(); return executeCommand(session, cmd, timoutMillis, lineProcessor); } catch (Exception e) { logger.error("execute ip:" + conn.getHostname() + " cmd:" + cmd, e); return new Result(e); } finally { close(session); } }Example 9
| Project: gmc-master File: SshUtil.java View source code |
private ProcessResult executeCommand(Connection sshConnection, String command) {
Session session = null; try { session = sshConnection.openSession(); BufferedReader stdoutReader = new BufferedReader(new InputStreamReader(new StreamGobbler(session.getStdout()))); BufferedReader stderrReader = new BufferedReader(new InputStreamReader(new StreamGobbler(session.getStderr()))); session.execCommand(command); ProcessResult result = getResultOfExecution(session, stdoutReader, stderrReader); return result; } catch (Exception e) { String errMsg = "Exception while executing command [" + command + "] on [" + sshConnection.getHostname() + "]"; logger.error(errMsg, e); sshConnCache.remove(sshConnection.getHostname()); sshConnection.close(); if (e instanceof IllegalStateException || e instanceof IOException) { throw new ConnectionException("Couldn't open SSH session on [" + sshConnection.getHostname() + "]!", e); } else { throw new GlusterRuntimeException(errMsg, e); } } finally { if (session != null) { session.close(); } } }Example 10
| Project: jst-master File: MyScpClient.java View source code |
private void sendBytes(
Session sess, byte[] data, String fileName, String mode) throws IOException { OutputStream os = sess.getStdin(); InputStream is = new BufferedInputStream(sess.getStdout(), 512); readResponse(is); String cline = "C" + mode + " " + data.length + " " + fileName + "\n"; os.write(cline.getBytes()); os.flush(); readResponse(is); os.write(data, 0, data.length); os.write(0); os.flush(); readResponse(is); os.write("E\n".getBytes()); os.flush(); }Example 11
| Project: TinyAdmin-master File: SSHModule.java View source code |
//endmethod die /** * <p>Objekteigene Implementierung der in <i>ActionModule</i> festgelegten <i>doAction()</i>-Methode. * Hier ist der eigentliche Code, welcher das Kommando auf dem fremden Host ausfuehrt, implementiert.</p> * <p>Es wird mit <i>Ganymed SSH-2 for Java</i> eine SSH2 Verbindung zu einem Fremdrechner aufgebaut und * ein Befehl ausgefuert. Moeglich macht dies der uerbergebene Parameter, welcher neben Verbindungsinformationen, * dem Benutzernamen, dem Passwort, dem Sudo-Passwort, dem Keyfile und dem Aktionstyp, auch den noetigen Befehl speichert. * Als Trennzeichen der einzelnen Informationen dient <i>#D3l1M3t3R#</i>.</p> * <p>Ist die Variable <i>abbort</i> im Hauptprogramm auf <i>true</i> gesetzt, so bricht die Methode ab. Zur * Sicherheit ruft das <i>TaskRunnable</i> welche dieses Objekt traegt, noch die Methode <i>die()</i> auf, * welche alle laufenden Verbindungen beendet.</p> * * @see #die() * * @param param_ref Der Parameter mit Verbindungsinformationen. * @return Statusmeldung ueber Erfolg/Misserfolg der Operation. */ String doAction(String param_ref) { if (TinyAdminC.abbort) { return "Vorgang abgebrochen ..."; } //endif String retVal_ref = ""; String[] t_ref = param_ref.split("#D3l1M3t3R#"); String ip_ref = t_ref[0]; String port_ref = t_ref[1]; String keyf_ref = t_ref[2]; if (keyf_ref.equals("-----")) { hasKey = false; } else { hasKey = true; } //endif String user_ref = t_ref[3]; String pass_ref = t_ref[4]; String cmd_ref = ""; if (t_ref.length != 6) { return "Kein Befehl zur Ausführung für dieses Betriebssystem angegeben."; } else { cmd_ref = t_ref[5]; } //endif boolean reachable = false; try { reachable = InetAddress.getByName(ip_ref).isReachable(5000); } catch (Exception ex_ref) { return "FEHLER: Die Host- oder IP-Adresse ist ungültig."; } if (reachable) { try { // Feststellen, ob ein KeyFile verwendet werden soll File keyfile_ref = null; if (hasKey) { keyfile_ref = new File(keyf_ref); if (!keyfile_ref.canRead()) { return "FEHLER: Das Keyfile konnte nicht gefunden werden."; //endif } //endif } // Verbindung herstellen connection_ref = new Connection(ip_ref, Integer.parseInt(port_ref)); connection_ref.connect(); // Hier beginnt die Authentifizierung boolean isLogin; if (hasKey) { isLogin = connection_ref.authenticateWithPublicKey(user_ref, keyfile_ref, pass_ref); } else { isLogin = connection_ref.authenticateWithPassword(user_ref, pass_ref); //endif } if (isLogin == false) { return "Authentifizierung gescheitert."; //endif } // ENDE der Authentifizierung //
Session erstellen und Befehl ausfuehren session_ref = connection_ref.openSession(); session_ref.execCommand(cmd_ref); // stdout und stderr abfangen InputStream stdout_ref = new StreamGobbler(session_ref.getStdout()); InputStream stderr_ref = new StreamGobbler(session_ref.getStderr()); BufferedReader bread1_ref = new BufferedReader(new InputStreamReader(stdout_ref)); BufferedReader bread2_ref = new BufferedReader(new InputStreamReader(stderr_ref)); // Ausgabe jeder Zeile an die MessageFacility zur Auswertung umleiten String line_ref = ""; String err_ref = ""; int count = 0; while (!TinyAdminC.abbort) { line_ref = bread1_ref.readLine(); if (line_ref == null) { break; //endif } if (count == 0) { if (!line_ref.equals("")) { retVal_ref += line_ref; //endif } count++; } else { if (!line_ref.equals("")) { retVal_ref += "\n" + line_ref; //endif } //endif } //endwhile } // Ausgabe jeder Fehlermeldung an die MessageFacility weiterleiten while (!TinyAdminC.abbort) { err_ref = bread2_ref.readLine(); if (err_ref == null) { break; //endif } if (!err_ref.equals("")) { retVal_ref += "\n" + err_ref; //endif } //endwhile } bread1_ref.close(); bread2_ref.close(); die(); } catch (Exception ex_ref) { retVal_ref = ex_ref.getMessage(); } } else { retVal_ref += "Der Host \"" + ip_ref + "\" ist nicht erreichbar."; } return retVal_ref; }Example 12
| Project: lcmc-master File: ExecCommandThread.java View source code |
private void openSshSession(final ConnectionTimeout connectionTimeout) throws IOException { /* it may hang here if we lost connection, so it will be * interrupted after a timeout. */ final
Session newSession = connectionThread.getConnection().openSession(); mSessionLock.lock(); try { sess = newSession; } finally { mSessionLock.unlock(); } if (connectionTimeout.wasTimeout()) { throw new IOException("open session failed"); } connectionTimeout.setTimeout(); }Example 13
| Project: cyberduck-master File: SFTPSession.java View source code |
@Override public void sendCommand(String command) throws IOException { final ch.ethz.ssh2.
Session sess = this.getClient().openSession(); try { this.message(command); sess.execCommand(command, host.getEncoding()); BufferedReader stdoutReader = new BufferedReader(new InputStreamReader(new StreamGobbler(sess.getStdout()))); BufferedReader stderrReader = new BufferedReader(new InputStreamReader(new StreamGobbler(sess.getStderr()))); // Here is the output from stdout while (true) { String line = stdoutReader.readLine(); if (null == line) { break; } this.log(false, line); } // Here is the output from stderr StringBuilder error = new StringBuilder(); while (true) { String line = stderrReader.readLine(); if (null == line) { break; } this.log(false, line); // Standard error output contains all status messages, not only errors. if (StringUtils.isNotBlank(error.toString())) { error.append(" "); } error.append(line).append("."); } if (StringUtils.isNotBlank(error.toString())) { this.error(error.toString(), null); } } finally { sess.close(); } }Example 14
| Project: HadooperPooper-master File: HadoopCluster.java View source code |
/** * * @param host * @param command * @return * @throws CmdException */ public CmdSessionResult remoteCommand(ClusterInstance host, String command) throws CmdException { try { Connection conn = new Connection(host.getInstance().getPublicDnsName()); conn.connect(); File keyfile = new File(_config.get(ClusterConfig.KEYPAIR_FILE_KEY)); boolean isAuthenticated = conn.authenticateWithPublicKey(_config.get(ClusterConfig.USERNAME_KEY), keyfile, BLANK); if (!isAuthenticated) { throw new CmdException("Could not authenticate.", host); }
Session session = conn.openSession(); LOGGER.info("EXEC '" + command + "' on instance: " + host.getInstance().getInstanceId()); session.execCommand(command); InputStream outStrm = new StreamGobbler(session.getStdout()); InputStream errStrm = new StreamGobbler(session.getStderr()); BufferedReader stdoutRdr = new BufferedReader(new InputStreamReader(outStrm)); BufferedReader stderrRdr = new BufferedReader(new InputStreamReader(errStrm)); StringBuilder sb = new StringBuilder(); String stdout; while ((stdout = stdoutRdr.readLine()) != null) { sb.append(stdout).append("\n"); } stdout = sb.toString(); sb = new StringBuilder(); String stderr; while ((stderr = stderrRdr.readLine()) != null) { sb.append(stderr).append("\n"); } stderr = sb.toString(); conn.close(); conn = null; return new CmdSessionResult(host, session.getExitStatus(), stdout, stderr); } catch (IOException e) { throw new CmdException(e.getMessage(), e.getCause(), host); } }Example 15
| Project: BC-BSP-master File: DeployGUI.java View source code |
public void sshExe() { int a = JOptionPane.showConfirmDialog(null, "Are you sure to execute these commands?", "Note", JOptionPane.YES_NO_OPTION); if (a != 0) { return; } String[] commands = ta_command.getText().split("\n"); try { for (int i = 0; i < mm.getRowCount(); i++) { Connection conn = new Connection((String) mm.getValueAt(i, 1)); conn.connect(); boolean isAuthenticated = conn.authenticateWithPassword((String) mm.getValueAt(i, 2), (String) mm.getValueAt(i, 3)); if (isAuthenticated) {
Session sess; for (int j = 0; j < commands.length; j++) { sess = conn.openSession(); sess.execCommand(commands[j]); sess.close(); } } conn.close(); } JOptionPane.showMessageDialog(win, "Excute the command successfully!"); } catch (Exception e) { JOptionPane.showMessageDialog(win, "ERROR!\nFail to execute the command!"); } }Example 16
| Project: jstorm-master File: MyScpClient.java View source code |
private void sendBytes(
Session sess, byte[] data, String fileName, String mode) throws IOException { OutputStream os = sess.getStdin(); InputStream is = new BufferedInputStream(sess.getStdout(), 512); readResponse(is); String cline = "C" + mode + " " + data.length + " " + fileName + "\n"; os.write(cline.getBytes()); os.flush(); readResponse(is); os.write(data, 0, data.length); os.write(0); os.flush(); readResponse(is); os.write("E\n".getBytes()); os.flush(); }Example 17
| Project: arcus-misc-master File: RemoteShell.java View source code |
public
Session getSession() { return session; }
-
- Popular Classes
- Recent Additions
-
org.hibernate.type.descriptor.java.BlobTypeDescriptor
-
org.hibernate.jpamodelgen.xml.jaxb.AccessType
-
org.hibernate.resource.beans.container.spi.ContainedBean
-
org.hibernate.annotations.SortNatural
-
org.hibernate.cfg.annotations.reflection.XMLContext.Default
-
org.hibernate.Internal
-
org.hibernate.resource.beans.container.spi.BeanContainer
-
org.hibernate.cfg.QuerySecondPass
-
org.hibernate.resource.beans.spi.BeanInstanceProducer
-
org.hibernate.type.WrapperBinaryType
-
org.hibernate.type.TimeType
-
org.hibernate.type.descriptor.java.LocaleTypeDescriptor
-
org.hibernate.mapping.PersistentClassVisitor
-
org.hibernate.type.descriptor.sql.JdbcTypeFamilyInformation
-
org.hibernate.type.CharacterType
-
org.springframework.messaging.rsocket.MetadataExtractor