ZZ Java遠程調用shell腳本

                                                                                 Java調用遠程Shell腳本

 

最近,需要開發一個Web管理系統,通過Web控制來執行遠程Linux主機上的服務腳本,參考了http://blog.csdn.net/sheismylife/archive/2009/11/17/4823696.aspx使用的一個小工具,確實很好地解決了這個問題,做個記錄,以供查閱。

這個小工具打成一個jar文件:ganymed-ssh2-build210.jar,可以在http://www.ganymed.ethz.ch/ssh2/處下載。該工具是基於SSH2協議的實現,在使用它的過程中非常容易,只需要指定合法的用戶名口令,或者授權認證文件,就可以創建到遠程Linux主機的連接,在建立起來的會話中調用該Linux主機上的腳本文件,執行相關操作。

下面是我基於ganymed-ssh2-build210.jar庫,寫的一個Demo,代碼如下所示:

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();
}
}

需要說明的一點是,執行腳本以後,可以獲取腳本執行的結果文本,需要對這些文本進行正確編碼後返回給客戶端(我們的Web管理控制檯),才能看到實際腳本執行的結果。

另外,當執行login方法時,登錄成功,位於當前的***.***.***.***:/home/username/目錄之下,你可以指定腳本文件所在的絕對路徑,或者通過cd導航到腳本文件所在的目錄,然後傳遞執行腳本所需要的參數,完成腳本調用執行。

 

 

 

原文在http://hi.baidu.com/shirdrn/blog/item/59223b129a7322c5c3fd78a9.html  謝謝作者

發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章