服务器ssh升级导致的java程序ssh连接失败

原本项目中使用的jar包为ganymed-ssh2-build210.jar,升级至ganymed-ssh2-261.jar,但是连接还是失败。
在这里插入图片描述
经过百度搜索后,将jar包改为:com.jcraft:jsch:0.1.54
由于两个jar包不同,所以需要重新编写工具类:
ganymed-ssh2的工具类为:

package com.dist.ty.approve.util;

import ch.ethz.ssh2.Connection;
import ch.ethz.ssh2.Session;
import com.dist.bdf.util.log.Loggers;

import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.nio.charset.StandardCharsets;
import java.text.DecimalFormat;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

/**
 * Created with IntelliJ IDEA.
 *
 * @author: lijt
 * @ClassName : ServerMessageUtil
 * @Date: 2020/12/18
 * @description TODO
 */
public class ServerMessageUtil {


    private String hostName;
    private String port;
    private String userName;
    private String passWord;
    private static String CPUMESSAGE =  "cat /proc/cpuinfo | grep name | cut -f2 -d: |uniq -c";
    private static String CPUCOMMAND = "vmstat|awk 'NR==3''{print $13, $14, $16, $15}'";
    private static String MEMCOMMAND = "cat /proc/meminfo |grep 'MemTotal\\|MemFree'|awk '{print $2}'";
    private static String DISKCOMMAND = "df -h|grep -v Filesystem";
    private static String ENCODESET = "export LC_CTYPE=zh_CN.UTF-8;";
    private static Map<String,String> CONMANDMAP = new HashMap<String, String>(){
        {
            put("CPUMESSAGE",CPUMESSAGE);
            put("CPUCOMMAND",CPUCOMMAND);
            put("MEMCOMMAND",MEMCOMMAND);
            put("DISKCOMMAND",DISKCOMMAND);
        }
    };

    public ServerMessageUtil(String hostName,String port, String userName, String passWord) {
        this.hostName = hostName;
        this.port = port;
        this.userName = userName;
        this.passWord = passWord;
    }


    /**
     * 服务器连接状态检查(1:正常  0:异常)
     * @return
     */
    public int serverCheck(){

        int status = 1;

        try{
            Connection conn = new Connection(hostName,Integer.valueOf(port));
            conn.connect();
        } catch (IOException e) {
            status = 0;
            Loggers.error(e.getMessage());
        }
        return status;

    }

    /**
     * session检测
     * @return
     */
    public Session getSession(){
        Connection conn = null;
        boolean isAuthenticated = false;
        Session session = null;
        try{
            conn = new Connection(hostName,Integer.valueOf(port));
            conn.connect();
            isAuthenticated = conn.authenticateWithPassword(userName, passWord);
            if (!isAuthenticated ){
                Loggers.error("SSH Login  Authentication failed.");
            }
            else {
                session = conn.openSession();
            }
        }catch (Exception e){
            e.printStackTrace();
        }

        return session;
    }

    public Connection getConnect(){
        Connection conn = null;
        boolean isAuthenticated = false;
        try{
            conn = new Connection(hostName,Integer.valueOf(port));
            conn.connect();
            isAuthenticated = conn.authenticateWithPassword(userName, passWord);
            if (!isAuthenticated ){
                Loggers.error("SSH Login  Authentication failed.");
            }
        }catch (Exception e){
            e.printStackTrace();
        }

        return conn;
    }


    /**
     * 获取CPU使用情况
     * @return
     */
    public  Map<String, String> getCpuUsage(){
        Map<String, String> map = new HashMap<>();
        List<String> result = executeCommand(CPUCOMMAND);
        if(result != null  && result.size() > 0){
            String[] cpuInfo = result.get(0).split(" ");
            map.put("用户CPU时间",cpuInfo[0]);
            map.put("系统CPU时间",cpuInfo[1]);
            map.put("等待IO CPU时间",cpuInfo[2]);
            map.put("空闲CPU时间",cpuInfo[3]);
            double others = 100.00-Double.parseDouble(cpuInfo[0])-Double.parseDouble(cpuInfo[1])-
                    Double.parseDouble(cpuInfo[2])-Double.parseDouble(cpuInfo[3]);
            DecimalFormat df = new DecimalFormat("0.0");
            map.put("其他时间",df.format(others));
        }else{
            map.put("用户CPU时间","0");
            map.put("系统CPU时间","0");
            map.put("等待IO CPU时间","0");
            map.put("空闲CPU时间","0");
            map.put("其他时间","0");
        }
        return map;
    }

    /**
     * 获取内存使用情况
     * @return
     */
    public  Map<String, String> getMemUsage(){
        Map<String, String> map = new HashMap<>();
        DecimalFormat df1 = new DecimalFormat("0.00");
        List<String> result = executeCommand(MEMCOMMAND);
        if(result != null  && result.size() > 0){
            double memTotal = Double.parseDouble(result.get(0))/1024/1024;
            double memFree = Double.parseDouble(result.get(1))/1024/1024;
            double memUsed = memTotal-memFree;
            map.put("总内存",df1.format(memTotal)+"G");
            map.put("已使用",df1.format(memUsed)+"G");
            map.put("空闲",df1.format(memFree)+"G");
        }else{
            map.put("总内存","0");
            map.put("已使用","0");
            map.put("空闲","0");
        }
        return map;
    }

    /**
     * 获取磁盘使用情况
     * @return
     */
    public List<String> getDiskUsage(){
        return executeCommand(DISKCOMMAND);
    }


    /**
     * 获取cpu型号
     * @return
     */
    public List<String> getCpuMessage(){
        return executeCommand(CPUMESSAGE);
    }




    /**
     * 执行linux命令并返回结果
     * @param command
     * @return
     */
    private List<String> executeCommand(String command){
        Session session = getSession();
        BufferedReader input = null;
        List<String> results = new ArrayList<>();
        try {
            session.execCommand(ENCODESET+command);
            input = new BufferedReader(new InputStreamReader(session.getStdout(), StandardCharsets.UTF_8));
            String line = null;
            while( (line = input.readLine()) != null){
                results.add(line);
            }
        } catch (IOException e) {
            e.printStackTrace();
        }finally {
            try {
                if(input != null){
                    input.close();
                }
            } catch (IOException e) {
                e.printStackTrace();
            }finally {
                if(session != null){
                    session.close();
                }
            }
        }
        return results;
    }

    /**
     * 根据输入参数执行命令并返回结果
     * @param commandMap
     * @return
     */
    public Map<String,Object> executeCommand(Map<String,String> commandMap){
        Connection conn = getConnect();
        Map<String,Object> commandResult = new HashMap<String, Object>();

        try {
            for(String key : commandMap.keySet()){
                String command = commandMap.get(key);
                Session session = conn.openSession();
                session.execCommand(ENCODESET+command);
                BufferedReader input = new BufferedReader(new InputStreamReader(session.getStdout(), StandardCharsets.UTF_8));
                String line = null;
                List<String> results = new ArrayList<String>();
                while( (line = input.readLine()) != null){
                    results.add(line);
                }
                commandResult.put(key,results);
                input.close();
                session.close();
            }

        } catch (IOException e) {
            e.printStackTrace();
        }finally {
            conn.close();
        }
        return commandResult;
    }

    /**
     * 根据配置执行命令并返回结果
     * @return
     */
    public Map<String,Object> executeCommand(){
        Connection conn = getConnect();
        Map<String,Object> commandResult = new HashMap<String, Object>();
        DecimalFormat df = new DecimalFormat("0.00");
        try {
            for(String key : CONMANDMAP.keySet()){
                String command = CONMANDMAP.get(key);
                Session session = conn.openSession();
                session.execCommand(ENCODESET+command);
                BufferedReader input = new BufferedReader(new InputStreamReader(session.getStdout(), StandardCharsets.UTF_8));
                String line = null;
                List<String> results = new ArrayList<String>();
                Map<String, String> temp = new HashMap<String, String>();
                while( (line = input.readLine()) != null){
                    results.add(line);
                }
                if("CPUCOMMAND".equals(key)){
                    if(results.size() > 0){
                        String[] cpuInfo = results.get(0).split(" ");
                        temp.put("用户CPU时间",cpuInfo[0]);
                        temp.put("系统CPU时间",cpuInfo[1]);
                        temp.put("等待IO CPU时间",cpuInfo[2]);
                        temp.put("空闲CPU时间",cpuInfo[3]);
                    }else{
                        temp.put("用户CPU时间","0");
                        temp.put("系统CPU时间","0");
                        temp.put("等待IO CPU时间","0");
                        temp.put("空闲CPU时间","0");
                    }
                    commandResult.put(key,temp);
                }else if("MEMCOMMAND".equals(key)){
                    if(results.size() > 0){
                        double memTotal = Double.parseDouble(results.get(0))/1024/1024;
                        double memFree = Double.parseDouble(results.get(1))/1024/1024;
                        double memUsed = memTotal-memFree;
                        temp.put("总内存",df.format(memTotal)+"G");
                        temp.put("已使用",df.format(memUsed)+"G");
                        temp.put("空闲",df.format(memFree)+"G");
                    }else{
                        temp.put("总内存","0");
                        temp.put("已使用","0");
                        temp.put("空闲","0");
                    }
                    commandResult.put(key,temp);
                }else {
                    commandResult.put(key,results);
                }
                input.close();
                session.close();
            }

        } catch (IOException e) {
            e.printStackTrace();
        }finally {
            conn.close();
        }
        return commandResult;
    }
}

jsch工具类为:

package com.dist.ty.approve.util;
import com.jcraft.jsch.*;

import java.io.*;
import java.text.DecimalFormat;
import java.util.*;

public class JSCHUtil {
    private String hostName;
    private String port;
    private String userName;
    private String passWord;
    private static String CPUMESSAGE =  "cat /proc/cpuinfo | grep name | cut -f2 -d: |uniq -c";
    private static String CPUCOMMAND = "vmstat|awk 'NR==3''{print $13, $14, $16, $15}'";
    private static String MEMCOMMAND = "cat /proc/meminfo |grep 'MemTotal\\|MemFree'|awk '{print $2}'";
    private static String DISKCOMMAND = "df -h|grep -v Filesystem";
    private static String ENCODESET = "export LC_CTYPE=zh_CN.UTF-8;";
    private static Map<String,String> CONMANDMAP = new HashMap<String, String>(){
        {
            put("CPUMESSAGE",CPUMESSAGE);
            put("CPUCOMMAND",CPUCOMMAND);
            put("MEMCOMMAND",MEMCOMMAND);
            put("DISKCOMMAND",DISKCOMMAND);
        }
    };

    public JSCHUtil(String hostName,String port, String userName, String passWord) {
        this.hostName = hostName;
        this.port = port;
        this.userName = userName;
        this.passWord = passWord;
    }

    /**
     * 服务器连接状态检查(1:正常  0:异常)
     * @return
     */
    public int serverCheck() {
        int status = 1;
        JSch jSch = new JSch();
        try{
            jSch.getSession(userName,hostName,Integer.parseInt(port));
        }catch (Exception e) {
            status = 0;
            e.printStackTrace();
        }
            return status;
    }

    /**
     * session检测
     * @return
     * @throws JSchException
     */
    public Session getSession() throws JSchException {
        JSch jSch = new JSch();
        Session session = jSch.getSession(userName, hostName, Integer.parseInt(port));
        session.setPassword(passWord);
        session.setConfig("StrictHostKeyChecking", "no");
        session.connect();
        return session;
    }
    /**
     * 获取CPU使用情况
     * @return
     */
    public  Map<String, String> getCpuUsage() throws JSchException {
        Map<String, String> map = new HashMap<>();
        List<String> result = executeCommand(CPUCOMMAND);
        if(result != null  && result.size() > 0){
            String[] cpuInfo = result.get(0).split(" ");
            map.put("用户CPU时间",cpuInfo[0]);
            map.put("系统CPU时间",cpuInfo[1]);
            map.put("等待IO CPU时间",cpuInfo[2]);
            map.put("空闲CPU时间",cpuInfo[3]);
            double others = 100.00-Double.parseDouble(cpuInfo[0])-Double.parseDouble(cpuInfo[1])-
                    Double.parseDouble(cpuInfo[2])-Double.parseDouble(cpuInfo[3]);
            DecimalFormat df = new DecimalFormat("0.0");
            map.put("其他时间",df.format(others));
        }else{
            map.put("用户CPU时间","0");
            map.put("系统CPU时间","0");
            map.put("等待IO CPU时间","0");
            map.put("空闲CPU时间","0");
            map.put("其他时间","0");
        }
        return map;
    }

    public List<String> executeCommand(String command) throws JSchException {
        Session session = getSession();
        ChannelExec channel = null;
        List<String> resultLines = new ArrayList<>();
        InputStream input = null;
        try {
            channel = (ChannelExec) session.openChannel("exec");
            channel.setCommand(ENCODESET+command);
            input = channel.getInputStream();
            channel.connect();
            BufferedReader inputReader = new BufferedReader(new InputStreamReader(input));
            String inputLine = null;
            while ((inputLine = inputReader.readLine()) != null) {
                System.out.println(inputLine);
                resultLines.add(inputLine);
            }
        } catch (IOException e) {
            e.printStackTrace();
        } finally {
            if (input != null) {
                try {
                    input.close();
                } catch (Exception e) {
                    e.printStackTrace();
                }
            }
            if (channel != null) {
                try {
                    channel.disconnect();
                } catch (Exception e) {
                    e.printStackTrace();
                }
            }
        }
        return resultLines;
    }

    /**
     * 根据配置执行命令并返回结果
     * @return
     */
    public Map<String,Object> executeCommand() throws JSchException {
        Session session = getSession();
        ChannelExec channel = null;
        Map<String,Object> commandResult = new HashMap<String, Object>();
        DecimalFormat df = new DecimalFormat("0.00");
        try {
            for (String key : CONMANDMAP.keySet()) {
                String command = CONMANDMAP.get(key);
                channel = (ChannelExec) session.openChannel("exec");
                channel.setCommand(ENCODESET+command);
                channel.connect();
                InputStream input = channel.getInputStream();
                BufferedReader inputReader = new BufferedReader(new InputStreamReader(input));
                String inputLine = null;
                List<String> results = new ArrayList<String>();
                Map<String, String> temp = new HashMap<String, String>();
                while ((inputLine = inputReader.readLine())!=null){
                    results.add(inputLine);
                }
                if("CPUCOMMAND".equals(key)){
                    if(results.size() > 0){
                        String[] cpuInfo = results.get(0).split(" ");
                        temp.put("用户CPU时间",cpuInfo[0]);
                        temp.put("系统CPU时间",cpuInfo[1]);
                        temp.put("等待IO CPU时间",cpuInfo[2]);
                        temp.put("空闲CPU时间",cpuInfo[3]);
                    }else{
                        temp.put("用户CPU时间","0");
                        temp.put("系统CPU时间","0");
                        temp.put("等待IO CPU时间","0");
                        temp.put("空闲CPU时间","0");
                    }
                    commandResult.put(key,temp);
                }else if("MEMCOMMAND".equals(key)){
                    if(results.size() > 0){
                        double memTotal = Double.parseDouble(results.get(0))/1024/1024;
                        double memFree = Double.parseDouble(results.get(1))/1024/1024;
                        double memUsed = memTotal-memFree;
                        temp.put("总内存",df.format(memTotal)+"G");
                        temp.put("已使用",df.format(memUsed)+"G");
                        temp.put("空闲",df.format(memFree)+"G");
                    }else{
                        temp.put("总内存","0");
                        temp.put("已使用","0");
                        temp.put("空闲","0");
                    }
                    commandResult.put(key,temp);
                }else {
                    commandResult.put(key,results);
                }
                input.close();
            }
        } catch (Exception e) {
            e.printStackTrace();
        } finally {
            if (channel != null) {
                try {
                    channel.disconnect();
                } catch (Exception e) {
                    e.printStackTrace();
                }
            }
        }

        return commandResult;
    }

}

ps:附上参考的csdn地址:
https://blog.csdn.net/junshao21/article/details/77579245?utm_source=blogxgwz6

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值