Java がサーバー リソース (メモリ、負荷、ディスク容量) を取得します

1. 説明

サーバーの運用や保守のために、サーバーのさまざまなリソースを取得するために、SSH ターミナル経由でシェル コマンドを送信することがよくありますが、このアイデアに従って、Java を使用してスケジュールされたタスクを実行し、サーバーのリソース使用量を定期的に収集することで、動的なプレゼンテーションを実現できます。サーバーリソースの。

2. SSH操作方法のカプセル化

まず、SSH 接続エンティティ クラスを定義します。

/**
 * 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;
    }
}

次に、SSH コマンド操作メソッドをカプセル化します。

Jarパッケージの導入

        <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. シェルコマンドの実行

サーバーに接続する

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

メモリの取得を例に挙げます。

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

ロードとディスクを取得するには、コマンドを次のコマンドに置き換えるだけです。

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

4. 効果の演出

自社事業と先ほど紹介したSupervisor監視サービスとの連携を組み合わせることで、簡単なサービス運用保守業務が完成します。

モニタリング指標

プロセス監視

モノのインターネットを必要とするパートナーは、コミュニケーションのために WeChat に私を追加できます。

おすすめ

転載: blog.csdn.net/qq_17486399/article/details/133760499