1 import java.io.IOException ; 2 import java.io.InputStream ; 3 4 import ch.ethz.ssh2.ChannelCondition; 5 import ch.ethz.ssh2.Connection; 6 import ch.ethz.ssh2.Session; 7 8 public class SingleThreadStdoutStderr 9 { 10 public static void main(String [] args) 11 { 12 String hostname = "127.0.0.1"; 13 String username = "joe"; 14 String password = "joespass"; 15 16 try 17 { 18 19 20 Connection conn = new Connection(hostname); 21 22 23 24 conn.connect(); 25 26 27 28 boolean isAuthenticated = conn.authenticateWithPassword(username, password); 29 30 if (isAuthenticated == false) 31 throw new IOException ("Authentication failed."); 32 33 34 35 Session sess = conn.openSession(); 36 37 sess.execCommand("echo \"Huge amounts of text on STDOUT\"; echo \"Huge amounts of text on STDERR\" >&2"); 38 39 47 48 51 52 InputStream stdout = sess.getStdout(); 53 InputStream stderr = sess.getStderr(); 54 55 byte[] buffer = new byte[8192]; 56 57 while (true) 58 { 59 if ((stdout.available() == 0) && (stderr.available() == 0)) 60 { 61 66 67 int conditions = sess.waitForCondition(ChannelCondition.STDOUT_DATA | ChannelCondition.STDERR_DATA 68 | ChannelCondition.EOF, 2000); 69 70 71 72 if ((conditions & ChannelCondition.TIMEOUT) != 0) 73 { 74 75 throw new IOException ("Timeout while waiting for data from peer."); 76 } 77 78 79 80 if ((conditions & ChannelCondition.EOF) != 0) 81 { 82 83 84 if ((conditions & (ChannelCondition.STDOUT_DATA | ChannelCondition.STDERR_DATA)) == 0) 85 { 86 87 break; 88 } 89 } 90 91 92 93 } 97 98 103 104 while (stdout.available() > 0) 105 { 106 int len = stdout.read(buffer); 107 if (len > 0) System.out.write(buffer, 0, len); 109 } 110 111 while (stderr.available() > 0) 112 { 113 int len = stderr.read(buffer); 114 if (len > 0) System.err.write(buffer, 0, len); 116 } 117 } 118 119 120 121 sess.close(); 122 123 124 125 conn.close(); 126 127 } 128 catch (IOException e) 129 { 130 e.printStackTrace(System.err); 131 System.exit(2); 132 } 133 } 134 } 135 | Popular Tags |