Java 链接 Linux 的静态类以及 Linux 系统的 UUID

Java 链接 Linux 的静态类以及 Linux 系统的 UUID

1. 静态类

所需要的包

<ganymed-ssh2.version>262</ganymed-ssh2.version>
<!-- 链接 Liunx 软件 -->
<dependency>
	<groupId>ch.ethz.ganymed</groupId>
	<artifactId>ganymed-ssh2</artifactId>
	<version>${ganymed-ssh2.version}</version>
</dependency>

静态类如下:
有代码可知返回值是以 Linux 控制台输出的内容且一行为一个 add(), 最后形成 List;

1.1 简化版

package com.YKenan.YKenan.util;

import ch.ethz.ssh2.Connection;
import ch.ethz.ssh2.Session;
import ch.ethz.ssh2.StreamGobbler;

import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.util.ArrayList;
import java.util.List;

public class Linux {

    /**
     * 链接 Liunx 的参数
     * ip: ip地址
     * port: 端口号
     * username: 用户名
     * pwd: 密码
     */
    private String ip = "10.100.10.100";
    private int port = 22;
    private String userName = "root";
    private String pwd = "YKenanYKenan";

    private Connection connection = new Connection(ip, port);

    public List<String> getExecCommand(String string) throws IOException {
        List<String> result = new ArrayList<>();
        connection.connect();// 连接
        boolean authenticateWithPassword = connection.authenticateWithPassword(userName, pwd);// 认证
        if (!authenticateWithPassword || !login()) {
            throw new IOException("Authentication failed.");
        } else {
            Session session = connection.openSession();
            session.execCommand(string, "utf-8");
            StreamGobbler stdout = new StreamGobbler(session.getStdout());
            StreamGobbler stderr = new StreamGobbler(session.getStderr());
            BufferedReader stdoutBuffere = new BufferedReader(new InputStreamReader(stdout));
            BufferedReader stderrstdoutBuffere = new BufferedReader(new InputStreamReader(stderr));
            for (String line = stdoutBuffere.readLine(); line != null; line = stdoutBuffere.readLine()) {
                result.add(line + "\n");
            }
            for (String line = stderrstdoutBuffere.readLine(); line != null; line = stderrstdoutBuffere.readLine()) {
                result.add(line);
            }
            stdoutBuffere.close();
            stderrstdoutBuffere.close();
            session.close();
        }
        connection.close();
        return result;
    }

    private Boolean login() {
        boolean flg = false;
        try {
            connection = new Connection(ip);
            connection.connect();// 连接 //判断身份是否已经认证
            if (!connection.isAuthenticationComplete()) {
                // 加锁,防止多线程调用时线程间判断不一致,导致出现重复认证
                synchronized (this) {
                    if (!connection.isAuthenticationComplete()) { // 进行身份认证
                        flg = connection.authenticateWithPassword(userName, pwd);
                    }
                }
            }
        } catch (IOException e) {
            e.printStackTrace();
        }
        return flg;
    }

}

1.2 配置版

ExecLinux 类
在配置文件中填写服务器链接内容:
此处运用 @ConfigurationProperties(prefix = "")

package com.ykenan.ykenan.util;

import ch.ethz.ssh2.Connection;
import ch.ethz.ssh2.Session;
import ch.ethz.ssh2.StreamGobbler;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.boot.context.properties.ConfigurationProperties;

import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.util.ArrayList;
import java.util.List;

/**
 * 执行 Linux 命令并返回结果 (可以远程操作)
 *
 * @author YKenan
 */
@ConfigurationProperties(prefix = "com.linux")
public class ExecLinux {

    private static final Logger log = LoggerFactory.getLogger(ExecLinux.class);

    /**
     * 链接 Linux 的参数
     * ip: ip地址
     * port: 端口号
     * username: 用户名
     * pwd: 密码
     */
    private String ip;
    private int port;
    private String username;
    private String pwd;

    public String getIp() {
        return ip;
    }

    public void setIp(String ip) {
        this.ip = ip;
    }

    public int getPort() {
        return port;
    }

    public void setPort(int port) {
        this.port = port;
    }

    public String getUsername() {
        return username;
    }

    public void setUsername(String username) {
        this.username = username;
    }

    public String getPwd() {
        return pwd;
    }

    public void setPwd(String pwd) {
        this.pwd = pwd;
    }

    /**
     * @param execLinux 本类, 传入时得到配置内容.
     * @param string    执行的命令
     * @return List<String>
     * @throws IOException IOException
     */
    public List<String> getExecCommand(ExecLinux execLinux, String string) throws IOException {
        // 创建连接
        Connection connection = new Connection(execLinux.getIp(), execLinux.getPort());
        class Authenticate {
            private Boolean login(ExecLinux execLinux) {
                boolean flg = false;
                try {
                    Connection connection = new Connection(execLinux.getIp());
                    connection.connect();// 连接 //判断身份是否已经认证
                    if (!connection.isAuthenticationComplete()) {
                        // 加锁,防止多线程调用时线程间判断不一致,导致出现重复认证
                        synchronized (this) {
                            if (!connection.isAuthenticationComplete()) { // 进行身份认证
                                flg = connection.authenticateWithPassword(execLinux.getUsername(), execLinux.getPwd());
                            }
                        }
                    }
                } catch (IOException e) {
                    e.printStackTrace();
                }
                return flg;
            }

        }

        // 创建返回的容器
        List<String> result = new ArrayList<>();
        // 连接
        connection.connect();
        // 认证
        boolean authenticateWithPassword = connection.authenticateWithPassword(execLinux.getUsername(), execLinux.getPwd());
        Authenticate authenticate = new Authenticate();
        if (!authenticateWithPassword || !authenticate.login(execLinux)) {
            throw new IOException("Authentication failed.");
        } else {
            Session session = connection.openSession();
            session.execCommand(string, "utf-8");
            StreamGobbler stdout = new StreamGobbler(session.getStdout());
            StreamGobbler stderr = new StreamGobbler(session.getStderr());
            BufferedReader stdoutBuffer = new BufferedReader(new InputStreamReader(stdout));
            BufferedReader solderersBuffers = new BufferedReader(new InputStreamReader(stderr));
            for (String line = stdoutBuffer.readLine(); line != null; line = stdoutBuffer.readLine()) {
                log.info("连接 Linux >>>> " + line);
                result.add(line + "\n");
            }
            for (String line = solderersBuffers.readLine(); line != null; line = solderersBuffers.readLine()) {
                log.error("连接 Linux >>>> " + line);
                result.add(line);
            }
            stdoutBuffer.close();
            solderersBuffers.close();
            session.close();
        }
        connection.close();
        return result;
    }

    @Override
    public String toString() {
        return "ExecLinux{" +
                "ip='" + ip + '\'' +
                ", port=" + port +
                ", username='" + username + '\'' +
                ", pwd='" + pwd + '\'' +
                '}';
    }
}


CoreProperties 将 ExecLinux 配置到 Bean 中, 使 ExecLinux 中注解生效.

package com.ykenan.monitor.config.properties;

import com.ykenan.monitor.util.ExecLinux;
import org.springframework.boot.context.properties.EnableConfigurationProperties;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;

@Configuration
@EnableConfigurationProperties(ExecLinux.class)
public class CoreProperties {

    @Bean
    public ExecLinux execLinux() {
        return new ExecLinux();
    }

}

在配置文件中添加:

在这里插入图片描述

测试

package com.ykenan.monitor;

import com.ykenan.monitor.util.ExecLinux;
import org.junit.jupiter.api.Test;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.test.context.SpringBootTest;
import org.springframework.context.annotation.PropertySource;

import java.io.IOException;
import java.util.List;

@PropertySource(value = "classpath:application.properties")
@SpringBootTest(classes = {MonitorPlusApplication.class}, webEnvironment = SpringBootTest.WebEnvironment.NONE)
class MonitorPlusApplicationTests {

    @Autowired
    private ExecLinux execLinux;

    @Test
    void contextLoads() {
        try {
            System.out.println(execLinux.toString());
            List<String> execCommand = execLinux.getExecCommand(execLinux, "dmidecode -s system-uuid | tr 'A-Z' 'a-z'");
            System.out.println(execCommand.get(0).replaceAll("[ \r\n\t]*", ""));
        } catch (IOException e) {
            e.printStackTrace();
        }
    }

}

在这里插入图片描述

2. UUID

Linux 内核提供有 UUID 生成接口:

cat /proc/sys/kernel/random/uuid

获取系统 UUID: 可作为 Linux 的唯一标识符

dmidecode -s system-uuid | tr 'A-Z' 'a-z'
  • 1
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值