1. 程式人生 > 程式設計 >Java實踐-遠端呼叫Shell指令碼並獲取輸出資訊

Java實踐-遠端呼叫Shell指令碼並獲取輸出資訊

1、新增依賴

<dependency>
    <groupId>ch.ethz.ganymed</groupId>
    <artifactId>ganymed-ssh2</artifactId>
    <version>262</version>
</dependency>
<dependency>
    <groupId>commons-io</groupId>
    <artifactId>commons-io</artifactId>
<version>2.6</version> </dependency> 複製程式碼

2、Api說明

  1. 首先構造一個聯結器,傳入一個需要登陸的ip地址;
Connection conn = new Connection(ipAddr);
複製程式碼
  1. 模擬登陸目的伺服器,傳入使用者名稱和密碼;
boolean isAuthenticated = conn.authenticateWithPassword(userName,passWord);
複製程式碼

它會返回一個布林值,true 代表成功登陸目的伺服器,否則登陸失敗。

  1. 開啟一個session,執行你需要的linux 指令碼命令;
Session session = conn.openSession();
session.execCommand(“ifconfig”);
複製程式碼
  1. 接收目標伺服器上的控制檯返回結果,讀取br中的內容;
InputStream stdout = new StreamGobbler(session.getStdout());
BufferedReader br = new BufferedReader(new InputStreamReader(stdout));
複製程式碼
  1. 得到指令碼執行成功與否的標誌 :0-成功 非0-失敗
System.out.println(“ExitCode: ” + session.getExitStatus());
複製程式碼
  1. 關閉session和connection
session.close();
conn.close();
複製程式碼

Tips:

  1. 通過第二部認證成功後當前目錄就位於/home/username/目錄之下,你可以指定指令碼檔案所在的絕對路徑,或者通過cd導航到指令碼檔案所在的目錄,然後傳遞執行指令碼所需要的引數,完成指令碼呼叫執行。
  2. 執行指令碼以後,可以獲取指令碼執行的結果文字,需要對這些文字進行正確編碼後返回給客戶端,避免亂碼產生。
  3. 如果你需要執行多個linux控制檯指令碼,比如第一個指令碼的返回結果是第二個指令碼的入參,你必須開啟多個Session,也就是多次呼叫 Session sess = conn.openSession();,使用完畢記得關閉就可以了。

3. 例項:工具類

public class SSHTool {

    private Connection conn;
    private String ipAddr;
    private Charset charset = StandardCharsets.UTF_8;
    private String userName;
    private String password;

    public SSHTool(String ipAddr,String userName,String password,Charset charset) {
        this.ipAddr = ipAddr;
        this.userName = userName;
        this.password = password;
        if (charset != null) {
            this.charset = charset;
        }
    }

    /**
     * 登入遠端Linux主機
     *
     * @return 是否登入成功
     */
    private boolean login() {
        conn = new Connection(ipAddr);

        try {
            // 連線
            conn.connect();
            // 認證
            return conn.authenticateWithPassword(userName,password);
        } catch (IOException e) {
            e.printStackTrace();
            return false;
        }
    }


    /**
     * 執行Shell指令碼或命令
     *
     * @param cmds 命令列序列
     * @return 指令碼輸出結果
     */
    public StringBuilder exec(String cmds) throws IOException {
        InputStream in = null;
        StringBuilder result = new StringBuilder();
        try {
            if (this.login()) {
                // 開啟一個會話
                Session session = conn.openSession();
                session.execCommand(cmds);
                in = session.getStdout();
                result = this.processStdout(in,this.charset);
                conn.close();
            }
        } finally {
            if (null != in) {
                in.close();
            }
        }
        return result;
    }

    /**
     * 解析流獲取字串資訊
     *
     * @param in      輸入流物件
     * @param charset 字符集
     * @return 指令碼輸出結果
     */
    public StringBuilder processStdout(InputStream in,Charset charset) throws FileNotFoundException {
        byte[] buf = new byte[1024];
        StringBuilder sb = new StringBuilder();
//        OutputStream os = new FileOutputStream("./data.txt");
        try {
            int length;
            while ((length = in.read(buf)) != -1) {
//                os.write(buf,c);
                sb.append(new String(buf,0,length));
            }
        } catch (IOException e) {
            e.printStackTrace();
        }
        return sb;
    }

    public static void main(String[] args) throws IOException {
        SSHTool tool = new SSHTool("192.168.100.40","root","123456",StandardCharsets.UTF_8);
        StringBuilder exec = tool.exec("bash /root/test12345.sh");
        System.out.println(exec);
    }
}

複製程式碼

4、測試指令碼

echo "Hello"
複製程式碼

輸出結果

輸出結果