java 获取5台远程linux主机的磁盘容量和内存容量
时间: 2024-02-27 15:52:54 浏览: 16
要获取5台远程 Linux 主机的磁盘容量和内存容量,可以通过在上面提到的 Java 远程执行 Shell 命令的代码中加入循环遍历的功能,具体实现可以参考以下代码:
```java
import com.jcraft.jsch.*;
public class RemoteShellExecutor {
public static void main(String[] args) {
String[] hosts = {"host1", "host2", "host3", "host4", "host5"};
String user = "remote_user";
String password = "remote_password";
String command1 = "df -h"; // 获取磁盘容量
String command2 = "free -m"; // 获取内存容量
try {
JSch jsch = new JSch();
for (String host : hosts) {
Session session = jsch.getSession(user, host, 22);
session.setPassword(password);
session.setConfig("StrictHostKeyChecking", "no");
session.connect();
Channel channel = session.openChannel("exec");
((ChannelExec) channel).setCommand(command1);
channel.setInputStream(null);
((ChannelExec) channel).setErrStream(System.err);
InputStream in = channel.getInputStream();
channel.connect();
byte[] tmp = new byte[1024];
while (true) {
while (in.available() > 0) {
int i = in.read(tmp, 0, 1024);
if (i < 0) break;
System.out.print("Host: " + host + ", " + new String(tmp, 0, i));
}
if (channel.isClosed()) {
System.out.println("exit-status: " + channel.getExitStatus());
break;
}
try {
Thread.sleep(1000);
} catch (Exception ee) {
}
}
channel.disconnect();
session.disconnect();
}
} catch (Exception e) {
e.printStackTrace();
}
}
}
```
以上代码中,hosts 数组中存储了5台远程主机的主机名,通过循环遍历 hosts 数组来获取所有远程主机的磁盘容量和内存容量信息。在输出信息时,通过添加 Host: host 字符串来标识是哪台主机的信息。