1 package test.tomcat; 2 3 import java.io.BufferedReader; 4 import java.io.InputStream; 5 import java.io.InputStreamReader; 6 import java.io.OutputStream; 7 import java.util.Arrays; 8 9 import ch.ethz.ssh2.Connection; 10 import ch.ethz.ssh2.Session; 11 12 /** 13 * @author simone (wangxinsh55@126.com) 14 */ 15 public class SshTerm { 16 private static final String hostname = "IP"; 17 private static final String userid = "userid"; 18 private static final String password = "password"; 19 20 private static String keyBuf = "hogehogehoge"; 21 22 public static void main(String[] arg) throws Exception { 23 Connection con = new Connection(hostname); 24 con.connect(); 25 boolean ret = con.authenticateWithPassword(userid, password); 26 if (!ret) { 27 System.out.println("loggin error!"); 28 } 29 Session session = con.openSession(); 30 session.requestDumbPTY(); 31 session.startShell(); 32 OutputStream os = session.getStdin(); 33 34 Thread t1 = new Std(session.getStdout()); 35 Thread t2 = new Std(session.getStderr()); 36 37 t1.start(); 38 t2.start(); 39 40 BufferedReader br = new BufferedReader(new InputStreamReader(System.in)); 41 while (true) { 42 keyBuf = br.readLine(); 43 keyBuf = keyBuf += "\r"; 44 byte[] buf = keyBuf.getBytes(); 45 os.write(buf, 0, buf.length); 46 if (keyBuf.equals("exit" + "\r")) { 47 session.close(); 48 con.close(); 49 System.exit(0); 50 } 51 } 52 } 53 54 public static String getKeyBuf() { 55 return keyBuf; 56 } 57 } 58 59 class Std extends Thread { 60 private InputStream is; 61 private final byte[] buf1 = new byte[4096]; 62 private final byte[] buf2 = new byte[2048]; 63 64 public Std() { 65 } 66 67 public Std(InputStream is) { 68 this.is = is; 69 } 70 71 @Override 72 public void run() { 73 while (true) { 74 try { 75 Arrays.fill(buf1, (byte) 0x00); 76 Arrays.fill(buf2, (byte) 0x00); 77 int n = is.read(buf1); 78 Thread.sleep(500); 79 int len = is.read(buf2); 80 System.arraycopy(buf2, 0, buf1, n, len); 81 len += n; 82 if (len > 0) { 83 String st = new String(buf1, "UTF-8"); 84 st = st.replaceAll("\00", ""); 85 System.out.print(st); 86 } 87 } catch (Exception e) { 88 e.printStackTrace(); 89 } 90 } 91 } 92 }