Home | History | Annotate | Download | only in examples
      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 StdoutAndStderr
     15 {
     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 
     34 			boolean isAuthenticated = conn.authenticateWithPassword(username, password);
     35 
     36 			if (isAuthenticated == false)
     37 				throw new IOException("Authentication failed.");
     38 
     39 			/* Create a session */
     40 
     41 			Session sess = conn.openSession();
     42 
     43 			sess.execCommand("echo \"Text on STDOUT\"; echo \"Text on STDERR\" >&2");
     44 
     45 			InputStream stdout = new StreamGobbler(sess.getStdout());
     46 			InputStream stderr = new StreamGobbler(sess.getStderr());
     47 
     48 			BufferedReader stdoutReader = new BufferedReader(new InputStreamReader(stdout));
     49 			BufferedReader stderrReader = new BufferedReader(new InputStreamReader(stderr));
     50 
     51 			System.out.println("Here is the output from stdout:");
     52 
     53 			while (true)
     54 			{
     55 				String line = stdoutReader.readLine();
     56 				if (line == null)
     57 					break;
     58 				System.out.println(line);
     59 			}
     60 
     61 			System.out.println("Here is the output from stderr:");
     62 
     63 			while (true)
     64 			{
     65 				String line = stderrReader.readLine();
     66 				if (line == null)
     67 					break;
     68 				System.out.println(line);
     69 			}
     70 
     71 			/* Close this session */
     72 
     73 			sess.close();
     74 
     75 			/* Close the connection */
     76 
     77 			conn.close();
     78 
     79 		}
     80 		catch (IOException e)
     81 		{
     82 			e.printStackTrace(System.err);
     83 			System.exit(2);
     84 		}
     85 	}
     86 }
     87