Java gets server resources (memory, load, disk capacity)

1. Description

We often send shell commands through the SSH terminal for server operation and maintenance, so as to obtain various resources of the server. According to this idea, we can use Java to do a scheduled task to regularly collect server resource usage, thereby realizing dynamic presentation of server resources.

2. Encapsulate SSH operation method

First we define the SSH connection entity class.

/**
 * SSH连接
 * @author Mr.Li
 * @date 2023-01-01
 */
public class SshConnection {
    private String username;
    private String password;
    private String hostname;

    public SshConnection(String username, String password, String hostname) {
        this.username = username;
        this.password = password;
        this.hostname = hostname;
    }

    public String getUsername() {
        return username;
    }

    public String getPassword() {
        return password;
    }

    public String getHostname() {
        return hostname;
    }
}

Then encapsulate the SSH command operation method

Introduce Jar package

        <dependency>
            <groupId>org.apache.sshd</groupId>
            <artifactId>sshd-core</artifactId>
            <version>2.8.0</version>
        </dependency>

        <dependency>
            <groupId>net.i2p.crypto</groupId>
            <artifactId>eddsa</artifactId>
            <version>0.3.0</version>
        </dependency>
/**
 * SSH linux操作类
 * @author Mr.Li
 * @date 2023-01-06
 */
@Slf4j
public class SSHLinuxUtils {

    /**
     * 执行Shell命令并返回结果
     * @param conn
     * @param cmd
     * @param timeout
     * @return
     * @throws IOException
     */
    public static SshResponse runCommand(SshConnection conn, String cmd, long timeout) {
        SshClient client = SshClient.setUpDefaultClient();
        try {
            //Open the client
            client.start();
            //Connect to the server
            String hostIp="";
            Integer port=22;
            String [] hostArr=conn.getHostname().split(":");
            if(hostArr.length>1){
                hostIp=hostArr[0];
                port=Integer.parseInt(hostArr[1]);
            }else{
                hostIp=hostArr[0];
            }
            ConnectFuture cf = client.connect(conn.getUsername(), hostIp, port);
            ClientSession session = cf.verify().getSession();
            session.addPasswordIdentity(conn.getPassword());
            session.auth().verify(TimeUnit.SECONDS.toMillis(timeout));
            //Create the exec and channel its output/error streams
            ChannelExec ce = session.createExecChannel(cmd);
            ByteArrayOutputStream out = new ByteArrayOutputStream();
            ByteArrayOutputStream err = new ByteArrayOutputStream();
            ce.setOut(out);
            ce.setErr(err);
            //Execute and wait
            ce.open();
            Set<ClientChannelEvent> events =
                    ce.waitFor(EnumSet.of(ClientChannelEvent.CLOSED), TimeUnit.SECONDS.toMillis(timeout));
            session.close(false);
            //Check if timed out
            if (events.contains(ClientChannelEvent.TIMEOUT)) {
                log.error(conn.getHostname()+" 命令 "+cmd+ "执行超时 "+timeout);
            }
            return new SshResponse(out.toString(), err.toString(), ce.getExitStatus());
        }catch (Exception e){
            log.error("runCommand:cmd:{}",cmd,e);
            return null;
        } finally {
            client.stop();
        }
    }
}

3. Execute Shell command

connect to the server

SshConnection sshConnection = new SshConnection("远程登录服务器用户名","远程登录服务器密码","远程登录服务器的IP端口");

Take obtaining memory as an example:

//获取内存的命令
String cmd="sudo cat /proc/meminfo";
//执行获取当前内存的命令
SshResponse sshResponse = SSHLinuxUtils.runCommand(sshConnection,cmd,3);
//其中StdOutput为获取到的内存数据
String outPut=sshResponse.getStdOutput();

To obtain the load and disk, you only need to replace the command with the following command.

//负载
String cmd="sudo cat /proc/loadavg";
//磁盘
String cmd="sudo df -h";

4. Effect presentation

Combining our own business and the connection with the Supervisor monitoring service introduced before, we can complete a simple service operation and maintenance business.

Monitoring indicators

Process monitoring

Partners who have Internet of Things needs can add me on WeChat to communicate.

Guess you like

Origin blog.csdn.net/qq_17486399/article/details/133760499