jdk1.8 通过IP、用户名、密码获取其他Linux服务器的CPU、内存、硬盘等详细信息(如要新增依赖,给出Maven坐标)
时间: 2023-07-10 18:21:58 浏览: 53
可以使用SSH协议连接到Linux服务器,然后执行命令获取服务器的CPU、内存、硬盘等详细信息。可以使用JSch库来实现SSH连接,它可以通过Maven依赖引入:
```xml
<dependency>
<groupId>com.jcraft</groupId>
<artifactId>jsch</artifactId>
<version>0.1.55</version>
</dependency>
```
以下是示例代码,可以根据需要修改:
```java
import com.jcraft.jsch.*;
public class ServerInfo {
public static void main(String[] args) {
String host = "192.168.1.100"; // 服务器IP地址
String user = "username"; // 登录用户名
String password = "password"; // 登录密码
try {
JSch jsch = new JSch();
Session session = jsch.getSession(user, host, 22);
session.setPassword(password);
session.setConfig("StrictHostKeyChecking", "no");
session.connect();
// 获取CPU信息
ChannelExec channelExec = (ChannelExec) session.openChannel("exec");
channelExec.setCommand("cat /proc/cpuinfo");
channelExec.connect();
System.out.println("CPU信息:\n" + readChannelOutput(channelExec));
// 获取内存信息
channelExec.setCommand("cat /proc/meminfo");
channelExec.connect();
System.out.println("内存信息:\n" + readChannelOutput(channelExec));
// 获取硬盘信息
channelExec.setCommand("df -h");
channelExec.connect();
System.out.println("硬盘信息:\n" + readChannelOutput(channelExec));
channelExec.disconnect();
session.disconnect();
} catch (Exception e) {
e.printStackTrace();
}
}
private static String readChannelOutput(ChannelExec channelExec) throws Exception {
byte[] buffer = new byte[1024];
StringBuilder stringBuilder = new StringBuilder();
try (var inputStream = channelExec.getInputStream()) {
while (true) {
while (inputStream.available() > 0) {
int i = inputStream.read(buffer, 0, 1024);
if (i < 0)
break;
stringBuilder.append(new String(buffer, 0, i));
}
if (channelExec.isClosed()) {
if (inputStream.available() > 0)
continue;
System.out.println("exit-status: " + channelExec.getExitStatus());
break;
}
Thread.sleep(1000);
}
}
return stringBuilder.toString();
}
}
```
请注意,此代码仅用于演示目的,实际应用中需要进行安全性、异常处理等方面的补充。
相关推荐
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)