public static void main(String[] args) throws IOException { String hostname = "somehost"; String username = "******"; String password = "******"; File knownHosts = new File("~/.ssh/known_hosts"); try { /* Load known_hosts file into in-memory database */ if (knownHosts.exists()) database.addHostkeys(knownHosts); /* Create a connection instance */ Connection conn = new Connection(hostname); /* Now connect and use the SimpleVerifier */ conn.connect(new SimpleVerifier(database)); /* Authenticate */ boolean isAuthenticated = conn.authenticateWithPassword(username, password); if (isAuthenticated == false) throw new IOException("Authentication failed."); /* Create a session */ Session sess = conn.openSession(); sess.execCommand("uname -a && date && uptime && who"); InputStream stdout = new StreamGobbler(sess.getStdout()); BufferedReader br = new BufferedReader(new InputStreamReader(stdout)); System.out.println("Here is some information about the remote host:"); while (true) { String line = br.readLine(); if (line == null) break; System.out.println(line); } /* Close this session */ sess.close(); /* Close the connection */ conn.close(); } catch (IOException e) { e.printStackTrace(System.err); System.exit(2); } }
public static void main(String[] args) { String hostname = "127.0.0.1"; String username = "******"; File keyfile = new File("~/.ssh/id_rsa"); // or "~/.ssh/id_dsa" String keyfilePass = "******"; // will be ignored if not needed try { /* Create a connection instance */ Connection conn = new Connection(hostname); /* Now connect */ conn.connect(); /* Authenticate */ boolean isAuthenticated = conn.authenticateWithPublicKey(username, keyfile, keyfilePass); if (isAuthenticated == false) throw new IOException("Authentication failed."); /* Create a session */ Session sess = conn.openSession(); sess.execCommand("uname -a && date && uptime && who"); InputStream stdout = new StreamGobbler(sess.getStdout()); BufferedReader br = new BufferedReader(new InputStreamReader(stdout)); System.out.println("Here is some information about the remote host:"); while (true) { String line = br.readLine(); if (line == null) break; System.out.println(line); } /* Close this session */ sess.close(); /* Close the connection */ conn.close(); } catch (IOException e) { e.printStackTrace(System.err); System.exit(2); } }
static void increaseCPU(OnDemandAWS pc, String keyName) throws InterruptedException { File keyfile = new File(keyName + ".pem"); // or "~/.ssh/id_dsa" String keyfilePass = "******"; // will be ignored if not needed try { Connection conn = new Connection(pc.ipAddress); conn.connect(); boolean isAuthenticated = conn.authenticateWithPublicKey("ec2-user", keyfile, keyfilePass); if (isAuthenticated == false) throw new IOException("Authentication failed."); Session sess = conn.openSession(); System.out.println("Increasing CPU usage for " + pc.machineName); sess.execCommand("while true; do true; done"); sess.close(); conn.close(); } catch (IOException e) { e.printStackTrace(System.err); System.out.println("Please use the attached script to start and stop cpu remotely"); } }
public String executeCommand(List<String> commands) throws IOException, InterruptedException { InputStream stdout; InputStream stderr; Session sess = connection.openSession(); sess.requestPTY("bash"); sess.startShell(); PrintWriter out = new PrintWriter(sess.getStdin()); for (String command : commands) { out.println(command); } out.println("exit"); out.flush(); out.close(); stdout = new StreamGobbler(sess.getStdout()); stderr = new StreamGobbler(sess.getStderr()); final BufferedReader stdoutReader = new BufferedReader(new InputStreamReader(stdout, tools.office.StringUtils.getUTF8String())); final BufferedReader stderrReader = new BufferedReader(new InputStreamReader(stderr, tools.office.StringUtils.getUTF8String())); final StringBuilder returnBuilder = new StringBuilder(); final Thread readThread = new Thread() { public void run() { String line; while (true) { try { line = stdoutReader.readLine(); if (line == null) { break; } returnBuilder.append(line + tools.file.FileUtils.Line_SEP); } catch (IOException e) { returnBuilder.append(e.getCause() + e.getMessage()); break; } } } }; Thread readErrThread = new Thread() { public void run() { String errline; while (true) { try { errline = stderrReader.readLine(); if (errline == null) { break; } returnBuilder.append(errline + tools.file.FileUtils.Line_SEP); } catch (IOException e) { returnBuilder.append(e.getCause() + e.getMessage()); break; } } } }; stdoutReader.close(); stderrReader.close(); readThread.start(); readErrThread.start(); readThread.join(); readErrThread.join(); sess.close(); return returnBuilder.toString(); }
/** * Validates the Flow target given by attempting to retrieve data * * @param target The target to validate * @return VALIDATED if the target was successfully validated, an error message otherwise */ public static String validateFlowTarget(VMTTarget target) { if (target != null) { String logPrefix = target.getNameOrAddress() + " : "; if (!FeaturesManager.vmtMANAGER.isNetworkModeEnabled()) { logger.warn(logPrefix + "Validation failed"); return UNLICENSED; } if ("NETFLOW".equals(target.getVersion())) { ch.ethz.ssh2.Connection conn = null; try { if (logger.isDebugEnabled()) logger.debug(logPrefix + "Validating " + target.getNameOrAddress()); VMTCredentials credentials = target.getCredentials(); if (credentials instanceof UsernamePassword) { UsernamePassword user = (UsernamePassword) credentials; String password = VMTEncryptionUtil.decrypt( credentials, MediationPackage.eINSTANCE.getUsernamePassword_Password()); conn = SshUtil.establishConnection( target.getNameOrAddress(), user.getUsername(), password); if (conn != null && conn.isAuthenticationComplete()) { Session ioSess = conn.openSession(); ioSess.execCommand(nFlowDumpCommand); return VALIDATED; } else { logger.warn(logPrefix + "Validation failed"); String reason = "Cannot establish SSH connection with the flow collector using the credential"; return reason; } } } catch (Exception e) { logger.warn(logPrefix + "Validation failed"); return e.getClass().getSimpleName(); } finally { SshUtil.closeConnection(conn, target); } } else if ("SFLOW".equals(target.getVersion())) { String targetAddress = target.getNameOrAddress(); String url = formUrl(targetAddress, SFLOW_REQUEST_IN_JSON); URL nodesURL; URLConnection nodesConnection = null; InputStreamReader in = null; try { nodesURL = new java.net.URL(url); nodesConnection = nodesURL.openConnection(); nodesConnection.connect(); in = new InputStreamReader((InputStream) nodesConnection.getContent()); if (in.ready()) return VALIDATED; else return "Cannot validate the SFLOW target"; } catch (Exception e) { return e.getMessage(); } finally { // Close the connection if (in != null) { try { in.close(); } catch (IOException e) { handleException( e, logger, "The following exception occured while attempting to close the connection"); } } } } } else { logger.warn("Null target : Validation failed"); return "TARGET IS NULL"; } return VALIDATED; // TODO: probably not the wanted behaviour }