1 /* 2 * Copyright (c) 2006-2011 Christian Plattner. All rights reserved. 3 * Please refer to the LICENSE.txt for licensing details. 4 */ 5 import java.io.BufferedReader; 6 import java.io.IOException; 7 import java.io.InputStream; 8 import java.io.InputStreamReader; 9 10 import ch.ethz.ssh2.Connection; 11 import ch.ethz.ssh2.Session; 12 import ch.ethz.ssh2.StreamGobbler; 13 14 public class Basic 15 { main(String[] args)16 public static void main(String[] args) 17 { 18 String hostname = "127.0.0.1"; 19 String username = "joe"; 20 String password = "joespass"; 21 22 try 23 { 24 /* Create a connection instance */ 25 26 Connection conn = new Connection(hostname); 27 28 /* Now connect */ 29 30 conn.connect(); 31 32 /* Authenticate. 33 * If you get an IOException saying something like 34 * "Authentication method password not supported by the server at this stage." 35 * then please check the FAQ. 36 */ 37 38 boolean isAuthenticated = conn.authenticateWithPassword(username, password); 39 40 if (isAuthenticated == false) 41 throw new IOException("Authentication failed."); 42 43 /* Create a session */ 44 45 Session sess = conn.openSession(); 46 47 sess.execCommand("uname -a && date && uptime && who"); 48 49 System.out.println("Here is some information about the remote host:"); 50 51 /* 52 * This basic example does not handle stderr, which is sometimes dangerous 53 * (please read the FAQ). 54 */ 55 56 InputStream stdout = new StreamGobbler(sess.getStdout()); 57 58 BufferedReader br = new BufferedReader(new InputStreamReader(stdout)); 59 60 while (true) 61 { 62 String line = br.readLine(); 63 if (line == null) 64 break; 65 System.out.println(line); 66 } 67 68 /* Show exit status, if available (otherwise "null") */ 69 70 System.out.println("ExitCode: " + sess.getExitStatus()); 71 72 /* Close this session */ 73 74 sess.close(); 75 76 /* Close the connection */ 77 78 conn.close(); 79 80 } 81 catch (IOException e) 82 { 83 e.printStackTrace(System.err); 84 System.exit(2); 85 } 86 } 87 } 88