1 import java.io.BufferedReader ; 2 import java.io.IOException ; 3 import java.io.InputStream ; 4 import java.io.InputStreamReader ; 5 6 import ch.ethz.ssh2.Connection; 7 import ch.ethz.ssh2.Session; 8 import ch.ethz.ssh2.StreamGobbler; 9 10 public class StdoutAndStderr 11 { 12 public static void main(String [] args) 13 { 14 String hostname = "127.0.0.1"; 15 String username = "joe"; 16 String password = "joespass"; 17 18 try 19 { 20 21 22 Connection conn = new Connection(hostname); 23 24 25 26 conn.connect(); 27 28 29 30 boolean isAuthenticated = conn.authenticateWithPassword(username, password); 31 32 if (isAuthenticated == false) 33 throw new IOException ("Authentication failed."); 34 35 36 37 Session sess = conn.openSession(); 38 39 sess.execCommand("echo \"Text on STDOUT\"; echo \"Text on STDERR\" >&2"); 40 41 InputStream stdout = new StreamGobbler(sess.getStdout()); 42 InputStream stderr = new StreamGobbler(sess.getStderr()); 43 44 BufferedReader stdoutReader = new BufferedReader (new InputStreamReader (stdout)); 45 BufferedReader stderrReader = new BufferedReader (new InputStreamReader (stderr)); 46 47 System.out.println("Here is the output from stdout:"); 48 49 while (true) 50 { 51 String line = stdoutReader.readLine(); 52 if (line == null) 53 break; 54 System.out.println(line); 55 } 56 57 System.out.println("Here is the output from stderr:"); 58 59 while (true) 60 { 61 String line = stderrReader.readLine(); 62 if (line == null) 63 break; 64 System.out.println(line); 65 } 66 67 68 69 sess.close(); 70 71 72 73 conn.close(); 74 75 } 76 catch (IOException e) 77 { 78 e.printStackTrace(System.err); 79 System.exit(2); 80 } 81 } 82 } 83 | Popular Tags |