ganymed-ssh2简介
Ganymed SSH-2 for Java是用纯Java实现SSH-2协议的一个包。可以利用它直接在Java程序中连接SSH服务器。
下载地址
使用方法
将 ganymed-ssh2-build210.jar 加入到项目的lib中即可
举例说明
获取linux服务器上某个目录的占用空间大小
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"));
}
}
版权声明:本文为博主原创文章,未经博主允许不得转载。
时间: 2024-10-10 09:37:10