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 }

下面截圖是次程序運行結果

 


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM