ganymed-ssh2简介
Ganymed SSH-2 for Java是用纯Java实现SSH-2协议的一个包。可以利用它直接在Java程序中连接SSH服务器。
使用方法
将 ganymed-ssh2-build210.jar 加入到项目的lib中即可
举例说明
获取linux服务器上某个目录的占用空间大小
java" style="padding: 0.3em; font-family: Monaco, Menlo, Consolas, 'Courier New', monospace; color: rgb(51, 51, 51); border-radius: 4px; margin-top: 0px; margin-bottom: 1.5em; line-height: 1.5em; word-break: break-all; word-wrap: break-word; white-space: pre-wrap; border: 1px solid rgba(0, 0, 0, 0.14902); overflow-y: auto; background-color: rgb(246, 246, 246);">
import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import ch.ethz.ssh2.Connection;
import ch.ethz.ssh2.Session;
import ch.ethz.ssh2.StreamGobbler;
public class SShUtil {
public static String getDirSize(String path){
String hostname = "linux服务器ip地址";
String username = "linux用户";
String password = "linux密码";
String size = "";
try {
/* Create a connection instance */
Connection conn = new Connection(hostname);
/* Now connect */
conn.connect();
/* * Authenticate. If you get an IOException saying something like * "Authentication method password not supported by the server at this stage." * then please check the FAQ. */
boolean isAuthenticated = conn.authenticateWithPassword(username,
password);
if (isAuthenticated == false)
throw new IOException("Authentication failed.");
/* Create a session */
Session sess = conn.openSession();
sess.execCommand("du -m --max-depth=0 "+path);
/* * This basic example does not handle stderr, which is sometimes * dangerous (please read the FAQ). */
InputStream stdout = new StreamGobbler(sess.getStdout());
BufferedReader br = new BufferedReader(new InputStreamReader(stdout));
String line = br.readLine();
String ss[] = line.split("\\s+");
size = ss[0];
/* Show exit status, if available (otherwise "null") */
// System.out.println("ExitCode: " + sess.getExitStatus());
/* Close this session */
sess.close();
/* Close the connection */
conn.close();
} catch (IOException e) {
e.printStackTrace(System.err);
System.exit(2);
}
return size;
}
public static void main(String[] args) {
System.out.println(getDirSize("/mnt/online/resource/media"));
}
}