該工具Jar包可在: http://download.csdn.net/detail/shenjianox/7769783
ganymed-ssh2簡介:
Ganymed SSH-2 for Java是用純Java實現SSH-2協議的一個包。在使用它的過程中非常容易,只需要指定合法的使用者名稱口令,
或者授權認證檔案,就可以建立到遠程Linux主機的串連,在建立起來的會話中調用該Linux主機上的指令檔,執行相關操作。
使用方法:
將 ganymed-ssh2-build210.jar 加入到項目的lib中。
簡單樣本:
假定我在192.168.0.114的Linux系統的/home/lldu目錄下放了一個檔案夾test,test檔案夾對應測試Java類的包名test,我們在該機器上運用javac ./test/Main.java編譯後,再通過調用下面的程式碼完成遠程調用:
import ch.ethz.ssh2.Connection;
import ch.ethz.ssh2.ConnectionInfo;
import ch.ethz.ssh2.Session;
/**
*
* @author lldu
*/
public class Main {
public static void main(String[] args) {
try {
Connection con = new Connection("192.168.0.114");
ConnectionInfo info = con.connect();
boolean result = con.authenticateWithPassword("lldu", "123456");
Session session = con.openSession();
session.execCommand("java test.Main");
} catch (Exception ex) {
System.out.println(ex.getLocalizedMessage());
}
}
}
總結使用步驟:
1.首先構造一個連接器,傳入一個需要登陸的ip地址
Connection conn = new Connection(ipAddr);
conn.connect(); // 串連
2.類比登陸目的伺服器 傳入使用者名稱和密碼 ,
boolean isAuthenticated = conn.authenticateWithPassword(username, password);它會返回一個布爾值,true 代表成功登陸目的伺服器,否則登陸失敗
3.開啟一個session,有點象Hibernate的session ,執行你需要的linux 指令碼命令 。
Session sess = conn.openSession();
sess.execCommand("last");
4.接收目標伺服器上的控制台返回結果,讀取br中的內容
InputStream stdout = new StreamGobbler(sess.getStdout());
BufferedReader br = new BufferedReader(new InputStreamReader(stdout));
5.得到指令碼運行成功與否的標誌 :0-成功 非0-失敗
System.out.println("ExitCode: " + sess.getExitStatus());
6.關閉session和connection
sess.close();
conn.close();
需要說明的是:
1.通過第2步認證成功後,目前的目錄就位於/home/username/目錄之下,你可以指定指令檔所在的絕對路徑,或者通過cd導航到指令檔所在的目錄,然後傳遞執行指令碼所需要的參數,完成指令碼調用執行。
2.執行指令碼以後,可以擷取指令碼執行的結果文本,需要對這些文本進行正確編碼後返回給用戶端,避免亂碼產生。
3.如果你需要執行多個linux控制台指令碼,比如第一個指令碼的返回結果是第二個指令碼的入參,你必須開啟多個Session,也就是多次調用
Session sess = conn.openSession();,使用完畢記得關閉就可以了
=================================================================================================
摘錄部分源碼如下:
import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import org.apache.log4j.Logger;
import ch.ethz.ssh2.Connection;
import ch.ethz.ssh2.SCPClient;
import ch.ethz.ssh2.Session;
import ch.ethz.ssh2.StreamGobbler;
public class CommandRunner {
private static final Logger logger = Logger.getLogger(CommandRunner.class);
//從其他網路電腦中拿去檔案
public static void scpGet(String host, String username, String password,
String remoteFile, String localDir) throws IOException {
if (logger.isDebugEnabled()) {
logger.debug("spc [" + remoteFile + "] from " + host + " to "
+ localDir);
}
Connection conn = getOpenedConnection(host, username, password);
SCPClient client = new SCPClient(conn);
client.get(remoteFile, localDir);
conn.close();
}
//將檔案拷貝到其他電腦上
public static void scpPut(String host, String username, String password,
String localFile, String remoteDir) throws IOException {
if (logger.isDebugEnabled()) {
logger.debug("spc [" + localFile + "] to " + host + remoteDir);
}
Connection conn = getOpenedConnection(host, username, password);
SCPClient client = new SCPClient(conn);
client.put(localFile, remoteDir);
conn.close();
}
//執行SSH命令.
public static int runSSH(String host, String username, String password,
String cmd) throws IOException {
if (logger.isDebugEnabled()) {
logger.debug("running SSH cmd [" + cmd + "]");
}
Connection conn = getOpenedConnection(host, username, password);
Session sess = conn.openSession();
sess.execCommand(cmd);
InputStream stdout = new StreamGobbler(sess.getStdout());
BufferedReader br = new BufferedReader(new InputStreamReader(stdout));
while (true) {
String line = br.readLine();
if (line == null)
break;
if (logger.isDebugEnabled()) {
logger.debug(line);
}
}
sess.close();
conn.close();
return sess.getExitStatus().intValue();
}
//獲得串連
private static Connection getOpenedConnection(String host, String username,
String password) throws IOException {
if (logger.isDebugEnabled()) {
logger.debug("connecting to " + host + " with user " + username
+ " and pwd " + password);
}
Connection conn = new Connection(host);
conn.connect(); // make sure the connection is opened
boolean isAuthenticated = conn.authenticateWithPassword(username,
password);
if (isAuthenticated == false)
throw new IOException("Authentication failed.");
return conn;
}
//執行本地的cmd命令.(DOS命令)
public static int runLocal(String cmd) throws IOException {
if (logger.isDebugEnabled()) {
logger.debug("running local cmd [" + cmd + "]");
}
Runtime rt = Runtime.getRuntime();
Process p = rt.exec(cmd);
InputStream stdout = new StreamGobbler(p.getInputStream());
BufferedReader br = new BufferedReader(new InputStreamReader(stdout));
while (true) {
String line = br.readLine();
if (line == null)
break;
if (logger.isDebugEnabled()) {
logger.debug(line);
}
}
return p.exitValue();
}
}