Java調用遠程Shell腳本

package org.shirdrn.shell;


import java.io.IOException;
import java.io.InputStream;
import java.nio.charset.Charset;

import ch.ethz.ssh2.Connection;
import ch.ethz.ssh2.Session;

/**
* 遠程Shell腳本執行工具

* @author Administrator
*/
public class RemoteShellTool {

private Connection conn;
private String ipAddr;
private String charset = Charset.defaultCharset().toString();
private String userName;
private String password;

public RemoteShellTool(String ipAddr, String userName, String password, String charset) {
   this.ipAddr = ipAddr;
   this.userName = userName;
   this.password = password;
   if(charset != null) {
    this.charset = charset;
   }
}
/**
* 登錄遠程Linux主機

* @return
* @throws IOException
*/
public boolean login() throws IOException {
   conn = new Connection(ipAddr);
   conn.connect(); // 連接
   return conn.authenticateWithPassword(userName, password); // 認證
}


/**
* 執行Shell腳本或命令

* @param cmds 命令行序列
* @return
*/
public String exec(String cmds) {
   InputStream in = null;
   String result = "";
   try {
    if (this.login()) {
     Session session = conn.openSession(); // 打開一個會話
     session.execCommand(cmds);
     in = session.getStdout();
     result = this.processStdout(in, this.charset);
     conn.close();
    }
   } catch (IOException e1) {
    e1.printStackTrace();
   }
   return result;
}

/**
* 解析流獲取字符串信息

* @param in 輸入流對象
* @param charset 字符集
* @return
*/
public String processStdout(InputStream in, String charset) {
   byte[] buf = new byte[1024];
   StringBuffer sb = new StringBuffer();
   try {
    while (in.read(buf) != -1) {
     sb.append(new String(buf, charset));
    }
   } catch (IOException e) {
    e.printStackTrace();
   }
   return sb.toString();
}
}

發佈了27 篇原創文章 · 獲贊 1 · 訪問量 4萬+
發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章