springboot远程执行服务器指令

本例是java远程连接到服务器,去抓取查询kubesphere中的etcd日志,并返回。
步骤拆分:

  • 连接到服务器
  • 执行指令获取pod信息:kubectl get po -n kubesphere-system
  • 将pod信息分割,只返回pod名称
  • 根据pod名称,执行指令获取pod日志:kubectl logs -n kubesphere-system "+podName + "
    –tail=500

1、在工程中引入下方依赖

		<dependency>
			<groupId>ch.ethz.ganymed</groupId>
			<artifactId>ganymed-ssh2</artifactId>
			<version>build210</version>
		</dependency>

2、编写连接命令工具类KubeSphereSSHUtils

import ch.ethz.ssh2.Connection;
import ch.ethz.ssh2.Session;
import ch.ethz.ssh2.StreamGobbler;
import org.apache.commons.lang3.StringUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.stereotype.Component;

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

@Component
public class KubeSphereSSHUtils {

    private String hostname;

    private String username;

    private String password;

    public void setHostname(String hostname) {
        this.hostname = hostname;
    }

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

    public void setPassword(String password) {
        this.password = password;
    }

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

    public Connection sshConnection() {
        Connection sshConn = null;
        try {
            sshConn = new Connection(hostname);
            sshConn.connect();
            boolean isAuthenticate = sshConn.authenticateWithPassword(username, password);
            if(isAuthenticate == false) {
                throw new IOException("连接到指定环境失败");
            }
        } catch (IOException e) {
            e.printStackTrace();
        }
        return sshConn;
    }

    //获取发布的日志的容器名
    public List<String> getReleasePod(String nameSpaceName, String containName) {
        Connection conn = this.sshConnection();
        Session sess = null;
        InputStream is = null;
        InputStreamReader inputStreamReader = null;
        BufferedReader reader = null;
        try {
            sess = conn.openSession();
            String str = " kubectl get po  -n "+nameSpaceName;
            log.info("执行指令:"+str);
            sess.execCommand(str);
            is = new StreamGobbler(sess.getStdout());
            inputStreamReader = new InputStreamReader(is);
            reader = new BufferedReader(inputStreamReader);
            boolean flg = true;
            List<String> names = new ArrayList<String>();
            while(flg) {
                String line = reader.readLine();
                if(StringUtils.isEmpty(line)) {
                    break;
                }
                if(line.startsWith(containName)){
                    names.add(line.split("\\s+")[0]);
                }
            }
            return names;
        } catch (IOException e) {
            e.printStackTrace();
        } finally {
            try {
                conn.close();
                sess.close();
                reader.close();
                inputStreamReader.close();
                is.close();
            } catch (IOException e) {
                e.printStackTrace();
            }
        }
        return null;
    }

    //获取pod内部日志
    public  List<String> getReleaseLogs(String nameSpaceName,String podName, String deploymentName){
        Connection conn = this.sshConnection();
        Session sess = null;
        InputStream is = null;
        InputStreamReader inputStreamReader = null;
        BufferedReader reader = null;
        try {
            sess = conn.openSession();
            String execCommand = "kubectl logs -n "+nameSpaceName+" "+podName + " --tail=500";
//            String execCommand = "kubectl logs -n "+nameSpaceName+" "+podName + " --tailssss=500";
            log.info("执行指令:"+execCommand);
            sess.execCommand(execCommand);
            is = new StreamGobbler(sess.getStdout());
            inputStreamReader = new InputStreamReader(is);
            reader = new BufferedReader(inputStreamReader);
            boolean flg = true;
            List<String> logs = new ArrayList<String>();
            while(flg) {
                String line = reader.readLine();
                if(line == null) {
                    break;
                }
                logs.add(line);

            }
            return logs;
        } catch (IOException e) {
            e.printStackTrace();
        } finally {
            try {
                reader.close();
                inputStreamReader.close();
                is.close();
                conn.close();
                sess.close();
            } catch (IOException e) {
                e.printStackTrace();
            }
        }
        return null;
    }

    //获取pod内部日志
    public  List<String> getKubeletLogs(){
        Connection conn = this.sshConnection();
        Session sess = null;
        InputStream is = null;
        InputStreamReader inputStreamReader = null;
        BufferedReader reader = null;
        try {
            sess = conn.openSession();
            String execCommand = "systemctl status kubelet";
            log.info("执行指令:"+execCommand);
            sess.execCommand(execCommand);
            is = new StreamGobbler(sess.getStdout());
            inputStreamReader = new InputStreamReader(is);
            reader = new BufferedReader(inputStreamReader);
            boolean flg = true;
            List<String> logs = new ArrayList<String>();
            while(flg) {
                String line = reader.readLine();
                if(line == null) {
                    break;
                }
                logs.add(line);

            }
            return logs;
        } catch (IOException e) {
            e.printStackTrace();
        } finally {
            try {
                reader.close();
                inputStreamReader.close();
                is.close();
                conn.close();
                sess.close();
            } catch (IOException e) {
                e.printStackTrace();
            }
        }
        return null;
    }

    public List<String> getNodesStatus() {
        Connection conn = this.sshConnection();
        Session sess = null;
        InputStream is = null;
        InputStreamReader inputStreamReader = null;
        BufferedReader reader = null;
        try {
            sess = conn.openSession();
            String execCommand = "kubectl get nodes";
            log.info("执行指令:"+execCommand);
            sess.execCommand(execCommand);
            is = new StreamGobbler(sess.getStdout());
            inputStreamReader = new InputStreamReader(is);
            reader = new BufferedReader(inputStreamReader);
            boolean flg = true;
            List<String> logs = new ArrayList<String>();
            while(flg) {
                String line = reader.readLine();
                if(line == null) {
                    break;
                }
                logs.add(line);

            }
            return logs;
        } catch (IOException e) {
            e.printStackTrace();
        } finally {
            try {
                reader.close();
                inputStreamReader.close();
                is.close();
                conn.close();
                sess.close();
            } catch (IOException e) {
                e.printStackTrace();
            }
        }
        return null;
    }


    public List<String> getNoReadyNodeMessage() {
        Connection conn = this.sshConnection();
        Session sess = null;
        InputStream is = null;
        InputStreamReader inputStreamReader = null;
        BufferedReader reader = null;
        try {
            sess = conn.openSession();
//            String execCommand = "kubectl get nodes | grep NotReady | awk '{print$1}'";
            String execCommand = "kubectl get nodes | grep Ready | awk '{print$1}'";
            log.info("执行指令:"+execCommand);
            sess.execCommand(execCommand);
            is = new StreamGobbler(sess.getStdout());
            inputStreamReader = new InputStreamReader(is);
            reader = new BufferedReader(inputStreamReader);
            boolean flg = true;
            List<String> logs = new ArrayList<String>();
            while(flg) {
                String line = reader.readLine();
                if(line == null) {
                    break;
                }
                logs.add(line);

            }
            return logs;
        } catch (IOException e) {
            e.printStackTrace();
        } finally {
            try {
                reader.close();
                inputStreamReader.close();
                is.close();
                conn.close();
                sess.close();
            } catch (IOException e) {
                e.printStackTrace();
            }
        }
        return null;
    }


    public List<String> restartKubelet() {
        Connection conn = this.sshConnection();
        Session sess = null;
        InputStream is = null;
        InputStreamReader inputStreamReader = null;
        BufferedReader reader = null;
        try {
            sess = conn.openSession();
            String execCommand = "systemctl restart kubelet.service";
            log.info("执行指令:"+execCommand);
            sess.execCommand(execCommand);
            is = new StreamGobbler(sess.getStdout());
            inputStreamReader = new InputStreamReader(is);
            reader = new BufferedReader(inputStreamReader);
            boolean flg = true;
            List<String> logs = new ArrayList<String>();
            while(flg) {
                String line = reader.readLine();
                if(line == null) {
                    break;
                }
                logs.add(line);

            }
            return logs;
        } catch (IOException e) {
            e.printStackTrace();
        } finally {
            try {
                reader.close();
                inputStreamReader.close();
                is.close();
                conn.close();
                sess.close();
            } catch (IOException e) {
                e.printStackTrace();
            }
        }
        return null;
    }


    public List<String> getNodeIPMessage() {
        Connection conn = this.sshConnection();
        Session sess = null;
        InputStream is = null;
        InputStreamReader inputStreamReader = null;
        BufferedReader reader = null;
        try {
            sess = conn.openSession();
            String execCommand = "hostname -i";
            sess.execCommand(execCommand);
            is = new StreamGobbler(sess.getStdout());
            inputStreamReader = new InputStreamReader(is);
            reader = new BufferedReader(inputStreamReader);
            boolean flg = true;
            List<String> logs = new ArrayList<String>();
            while(flg) {
                String line = reader.readLine();
                if(line == null) {
                    break;
                }
                logs.add(line);

            }
            return logs;
        } catch (IOException e) {
            e.printStackTrace();
        } finally {
            try {
                reader.close();
                inputStreamReader.close();
                is.close();
                conn.close();
                sess.close();
            } catch (IOException e) {
                e.printStackTrace();
            }
        }
        return null;
    }


    //重启node机器,慎用!!!!!!
    public List<String> rebootNode() {
        Connection conn = this.sshConnection();
        Session sess = null;
        InputStream is = null;
        InputStreamReader inputStreamReader = null;
        BufferedReader reader = null;
        try {
            sess = conn.openSession();
            String execCommand = "systemctl reboot";
            sess.execCommand(execCommand);
            is = new StreamGobbler(sess.getStdout());
            inputStreamReader = new InputStreamReader(is);
            reader = new BufferedReader(inputStreamReader);
            boolean flg = true;
            List<String> logs = new ArrayList<String>();
            while(flg) {
                String line = reader.readLine();
                if(line == null) {
                    break;
                }
                logs.add(line);

            }
            return logs;
        } catch (IOException e) {
            e.printStackTrace();
        } finally {
            try {
                reader.close();
                inputStreamReader.close();
                is.close();
                conn.close();
                sess.close();
            } catch (IOException e) {
                e.printStackTrace();
            }
        }
        return null;
    }
}

3、编写配置连接类

@Component
public class DeployUtil {

    private KubeSphereSSHUtils sshUtilsDev;
    private KubeSphereSSHUtils sshUtilsRelease;
    private KubeSphereSSHUtils sshUtilsProd;

    private KubeSphereSSHUtils sshUtilsDev_node1;
    private KubeSphereSSHUtils sshUtilsDev_node2;
    private KubeSphereSSHUtils sshUtilsDev_node3;
    private KubeSphereSSHUtils sshUtilsDev_node4;

    private KubeSphereSSHUtils sshUtilsRelease_node1;
    private KubeSphereSSHUtils sshUtilsRelease_node2;
    private KubeSphereSSHUtils sshUtilsRelease_node3;
    private KubeSphereSSHUtils sshUtilsRelease_node4;
    private KubeSphereSSHUtils sshUtilsRelease_node5;
    private KubeSphereSSHUtils sshUtilsRelease_node6;

    @Autowired
    K8sEnvConfigBean k8sEnvConfigBean;

    @PostConstruct
    public void init() {

        this.createK8sSSHUtils("dev");
        this.createK8sSSHUtils("release");
        this.createK8sSSHUtils("prod");

        this.createK8sSSHNodeUtils_Dev("dev-node1");
        this.createK8sSSHNodeUtils_Dev("dev-node2");
        this.createK8sSSHNodeUtils_Dev("dev-node3");
        this.createK8sSSHNodeUtils_Dev("dev-node4");

        this.createK8sSSHNodeUtils_Release("release-node1");
        this.createK8sSSHNodeUtils_Release("release-node2");
        this.createK8sSSHNodeUtils_Release("release-node3");
        this.createK8sSSHNodeUtils_Release("release-node4");
        this.createK8sSSHNodeUtils_Release("release-node5");
        this.createK8sSSHNodeUtils_Release("release-node6");


    }


    //创建三套环境主节点的连接
    public void createK8sSSHUtils(String env) {
        if(env.equals("dev")) {
            sshUtilsDev = new KubeSphereSSHUtils();
            sshUtilsDev.setPassword(k8sEnvConfigBean.getDevPassword());
            sshUtilsDev.setUsername(k8sEnvConfigBean.getDevUsername());
            sshUtilsDev.setHostname(k8sEnvConfigBean.getDevHost());
        }else if(env.equals("release")) {
            sshUtilsRelease = new KubeSphereSSHUtils();
            sshUtilsRelease.setPassword(k8sEnvConfigBean.getReleasePassword());
            sshUtilsRelease.setUsername(k8sEnvConfigBean.getReleaseUsername());
            sshUtilsRelease.setHostname(k8sEnvConfigBean.getReleaseHost());
        }else if(env.equals("prod")) {
            sshUtilsProd = new KubeSphereSSHUtils();
            sshUtilsProd.setPassword(k8sEnvConfigBean.getProdPassword());
            sshUtilsProd.setUsername(k8sEnvConfigBean.getProdUsername());
            sshUtilsProd.setHostname(k8sEnvConfigBean.getProdHost());
        }
    }

    //创建dev环境子节点的连接
    public void createK8sSSHNodeUtils_Dev(String env) {
        switch (env) {
            case "dev-node1":
                sshUtilsDev_node1 = new KubeSphereSSHUtils();
                sshUtilsDev_node1.setPassword(k8sEnvConfigBean.getDev_node1_password());
                sshUtilsDev_node1.setUsername(k8sEnvConfigBean.getDev_node1_username());
                sshUtilsDev_node1.setHostname(k8sEnvConfigBean.getDev_node1_host());
                break;
            case "dev-node2":
                sshUtilsDev_node2 = new KubeSphereSSHUtils();
                sshUtilsDev_node2.setPassword(k8sEnvConfigBean.getDev_node2_password());
                sshUtilsDev_node2.setUsername(k8sEnvConfigBean.getDev_node2_username());
                sshUtilsDev_node2.setHostname(k8sEnvConfigBean.getDev_node2_host());
                break;
            case "dev-node3":
                sshUtilsDev_node3 = new KubeSphereSSHUtils();
                sshUtilsDev_node3.setPassword(k8sEnvConfigBean.getDev_node3_password());
                sshUtilsDev_node3.setUsername(k8sEnvConfigBean.getDev_node3_username());
                sshUtilsDev_node3.setHostname(k8sEnvConfigBean.getDev_node3_host());
                break;
            case "dev-node4":
                sshUtilsDev_node4 = new KubeSphereSSHUtils();
                sshUtilsDev_node4.setPassword(k8sEnvConfigBean.getDev_node4_password());
                sshUtilsDev_node4.setUsername(k8sEnvConfigBean.getDev_node4_username());
                sshUtilsDev_node4.setHostname(k8sEnvConfigBean.getDev_node4_host());
        }
    }

    //创建release环境子节点连接
    public void createK8sSSHNodeUtils_Release(String env) {
        switch (env) {
            case "release-node1":
                sshUtilsRelease_node1 = new KubeSphereSSHUtils();
                sshUtilsRelease_node1.setPassword(k8sEnvConfigBean.getRelease_node1_password());
                sshUtilsRelease_node1.setUsername(k8sEnvConfigBean.getRelease_node1_username());
                sshUtilsRelease_node1.setHostname(k8sEnvConfigBean.getRelease_node1_host());
                break;
            case "release-node2":
                sshUtilsRelease_node2 = new KubeSphereSSHUtils();
                sshUtilsRelease_node2.setPassword(k8sEnvConfigBean.getRelease_node2_password());
                sshUtilsRelease_node2.setUsername(k8sEnvConfigBean.getRelease_node2_username());
                sshUtilsRelease_node2.setHostname(k8sEnvConfigBean.getRelease_node2_host());
                break;
            case "release-node3":
                sshUtilsRelease_node3 = new KubeSphereSSHUtils();
                sshUtilsRelease_node3.setPassword(k8sEnvConfigBean.getRelease_node3_password());
                sshUtilsRelease_node3.setUsername(k8sEnvConfigBean.getRelease_node3_username());
                sshUtilsRelease_node3.setHostname(k8sEnvConfigBean.getRelease_node3_host());
                break;
            case "release-node4":
                sshUtilsRelease_node4 = new KubeSphereSSHUtils();
                sshUtilsRelease_node4.setPassword(k8sEnvConfigBean.getRelease_node4_password());
                sshUtilsRelease_node4.setUsername(k8sEnvConfigBean.getRelease_node4_username());
                sshUtilsRelease_node4.setHostname(k8sEnvConfigBean.getRelease_node4_host());
                break;
            case "release-node5":
                sshUtilsRelease_node5 = new KubeSphereSSHUtils();
                sshUtilsRelease_node5.setPassword(k8sEnvConfigBean.getRelease_node5_password());
                sshUtilsRelease_node5.setUsername(k8sEnvConfigBean.getRelease_node5_username());
                sshUtilsRelease_node5.setHostname(k8sEnvConfigBean.getRelease_node5_host());
            case "release-node6":
                sshUtilsRelease_node6 = new KubeSphereSSHUtils();
                sshUtilsRelease_node6.setPassword(k8sEnvConfigBean.getRelease_node6_password());
                sshUtilsRelease_node6.setUsername(k8sEnvConfigBean.getRelease_node6_username());
                sshUtilsRelease_node6.setHostname(k8sEnvConfigBean.getRelease_node6_host());
        }
    }

    //获取相应环境的某台机器的连接
    public KubeSphereSSHUtils getK8sSSHUtils(String env) {
        KubeSphereSSHUtils result = null;
        if(env.equals("dev")) {
            if (this.sshUtilsDev == null) {
                this.createK8sSSHUtils(env);
            }
            result = sshUtilsDev;
        }else if(env.equals("release")) {
            if (this.sshUtilsRelease == null) {
                this.createK8sSSHUtils(env);
            }
            result = sshUtilsRelease;
        }else if(env.equals("prod")) {
            if (this.sshUtilsProd == null) {
                this.createK8sSSHUtils(env);
            }
            result = sshUtilsProd;
        }
        //新增操作dev节点的逻辑
        else if(env.equals("dev-node1")) {
            if (this.sshUtilsDev_node1 == null) {
                this.createK8sSSHNodeUtils_Dev(env);
            }
            result = sshUtilsDev_node1;
        }else if(env.equals("dev-node2")) {
            if (this.sshUtilsDev_node2 == null) {
                this.createK8sSSHNodeUtils_Dev(env);
            }
            result = sshUtilsDev_node2;
        }else if(env.equals("dev-node3")) {
            if (this.sshUtilsDev_node3 == null) {
                this.createK8sSSHNodeUtils_Dev(env);
            }
            result = sshUtilsDev_node3;
        }else if(env.equals("dev-node4")) {
            if (this.sshUtilsDev_node4 == null) {
                this.createK8sSSHNodeUtils_Dev(env);
            }
            result = sshUtilsDev_node4;
        }
        //新增操作release节点的逻辑
        else if(env.equals("release-node1")) {
            if (this.sshUtilsRelease_node1 == null) {
                this.createK8sSSHNodeUtils_Release(env);
            }
            result = sshUtilsRelease_node1;
        }else if(env.equals("release-node2")) {
            if (this.sshUtilsRelease_node2 == null) {
                this.createK8sSSHNodeUtils_Release(env);
            }
            result = sshUtilsRelease_node2;
        }else if(env.equals("release-node3")) {
            if (this.sshUtilsRelease_node3 == null) {
                this.createK8sSSHNodeUtils_Release(env);
            }
            result = sshUtilsRelease_node3;
        }else if(env.equals("release-node4")) {
            if (this.sshUtilsRelease_node4 == null) {
                this.createK8sSSHNodeUtils_Release(env);
            }
            result = sshUtilsRelease_node4;
        }else if(env.equals("release-node5")) {
            if (this.sshUtilsRelease_node5 == null) {
                this.createK8sSSHNodeUtils_Release(env);
            }
            result = sshUtilsRelease_node5;
        }else if(env.equals("release-node6")) {
            if (this.sshUtilsRelease_node6 == null) {
                this.createK8sSSHNodeUtils_Release(env);
            }
            result = sshUtilsRelease_node6;
        }
        return result;
    }

    //寻找环境下的某一个子节点物理机,便于重启该机器
    public String getNodeEnvType(String nodeName,String env) {
        String k8sEnv = null;
        if(Objects.equals(env,"dev")){ //dev环境机器匹配,不匹配主节点
            switch (nodeName) {
                case "node1":
                    k8sEnv = "dev-node1";
                    break;
                case "node2":
                    k8sEnv = "dev-node2";
                    break;
                case "node3":
                    k8sEnv = "dev-node3";
                    break;
                case "node4":
                    k8sEnv = "dev-node4";
                    break;
            }
        } else if(Objects.equals(env,"release")) { //release环境机器匹配,不匹配主节点
            switch (nodeName) {
                case "node1":
                    k8sEnv = "release-node1";
                    break;
                case "node2":
                    k8sEnv = "release-node2";
                    break;
                case "node3":
                    k8sEnv = "release-node3";
                    break;
                case "node4":
                    k8sEnv = "release-node4";
                    break;
                case "node5":
                    k8sEnv = "release-node5";
                    break;
                case "node6":
                    k8sEnv = "release-node6";
                    break;
            }
        }
        //prod环境机器暂时不开启自动重启功能
        return k8sEnv;
    }
}

4、调用时的代码如下:

KubeSphereSSHUtils sshUtils = deployUtils.getK8sSSHUtils(env);//连接到指令环境
List<String> podNames = sshUtils.getReleasePod(KUBESPHERE_NAMESPACE, KUBESPHERE_ETCD_CONTAINNAME); //获取pod名称
List<String> logs = sshUtils.getReleaseLogs(KUBESPHERE_NAMESPACE, podName, KUBESPHERE_ETCD_CONTAINNAME);//获取日志

你可能感兴趣的:(java,spring,boot,服务器,后端)