java使用trilead库远程获取linux的内存和磁盘使用情况
时间: 2024-05-09 07:19:20 浏览: 13
以下是使用Trilead库远程获取Linux的内存和磁盘使用情况的示例代码:
```java
import com.trilead.ssh2.Connection;
import com.trilead.ssh2.Session;
import com.trilead.ssh2.StreamGobbler;
import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
public class RemoteHostInfo {
public static void main(String[] args) {
String hostname = "remote-hostname";
String username = "username";
String password = "password";
Connection conn = new Connection(hostname);
try {
// Connect to the remote host
conn.connect();
// Authenticate with the username and password
boolean isAuthenticated = conn.authenticateWithPassword(username, password);
if (isAuthenticated) {
// Create a new session
Session session = conn.openSession();
// Execute the memory usage command
session.execCommand("free -m");
// Read the output from the session
BufferedReader stdout = new BufferedReader(new InputStreamReader(new StreamGobbler(session.getStdout())));
String line;
while ((line = stdout.readLine()) != null) {
System.out.println(line);
}
// Execute the disk usage command
session.execCommand("df -h");
// Read the output from the session
stdout = new BufferedReader(new InputStreamReader(new StreamGobbler(session.getStdout())));
while ((line = stdout.readLine()) != null) {
System.out.println(line);
}
// Close the session
session.close();
} else {
System.out.println("Authentication failed.");
}
// Disconnect from the remote host
conn.close();
} catch (IOException e) {
System.out.println("Error: " + e.getMessage());
}
}
}
```
此代码使用Trilead SSH2库连接到远程主机,使用用户名和密码进行身份验证,然后执行“free -m”和“df -h”命令以获取内存和磁盘使用情况。输出结果将打印到控制台。