java使用SSH连接Linux系统
SSH连接linux系统使我们在开发项目中常用到的,现在留下来,做个记录
1 package com.log; 2 3 import java.io.BufferedReader; 4 import java.io.IOException; 5 import java.io.InputStream; 6 import java.io.InputStreamReader; 7 import java.io.PrintWriter; 8 9 import ch.ethz.ssh2.Connection; 10 import ch.ethz.ssh2.Session; 11 import ch.ethz.ssh2.StreamGobbler; 12 13 public class Test8 { 14 15 /** 16 * 连接linux系统 17 * @param args 18 */ 19 public static void main(String[] args) { 20 try { 21 Connection conn = new Connection("192.168.81.129"); 22 conn.connect(); 23 boolean isAuthenticated = conn.authenticateWithPassword("root", 24 "123456"); 25 if (isAuthenticated == false) { 26 throw new IOException("Authentication failed"); 27 } 28 Session sess = conn.openSession(); 29 sess.requestPTY("bash"); 30 sess.startShell(); 31 InputStream stdout = new StreamGobbler(sess.getStdout()); 32 InputStream stderr = new StreamGobbler(sess.getStderr()); 33 BufferedReader stdoutReader = new BufferedReader( 34 new InputStreamReader(stdout)); 35 BufferedReader stderrReader = new BufferedReader( 36 new InputStreamReader(stderr)); 37 BufferedReader inputReader = new BufferedReader( 38 new InputStreamReader(System.in)); 39 PrintWriter out = new PrintWriter(sess.getStdin()); 40 String temp = ""; 41 while (!temp.equals("exit")) { 42 System.out.print("[root@vmone ~]#"); 43 temp = inputReader.readLine(); 44 out.println(temp); 45 out.flush(); 46 String line = null; 47 while ((line = stdoutReader.readLine()) != null) { 48 if (line.length() == 0) {// line等于null从来不会发生,导致程序卡在这里 49 continue; 50 } else{ 51 System.out.println(line); 52 } 53 } 54 System.out.println("Here is the output from stderr:"); 55 while (true) { 56 line = stderrReader.readLine(); 57 if (line == null) 58 break; 59 System.out.println(line); 60 } 61 } 62 System.out.println("ExitCode: " + sess.getExitStatus()); 63 sess.close(); 64 conn.close(); 65 System.out.println("close connection"); 66 } catch (IOException e) { 67 e.printStackTrace(System.err); 68 System.exit(2); 69 } 70 } 71 72 73 }
下面截图是次程序运行结果
llh