Java 操作SSH2实现远程执行linux命令

1、引入依赖

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

2、SSH2Util 工具类封装

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

import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;

public class SSH2Util {

    //指定默认编码
    private static String DEFAULT_CHARSET = "UTF-8";

    /**
     * 建立SSH2连接
     * @param host 主机地址
     * @param username 用户名
     * @param password 密码
     * @return Connection
     */
    public static Connection openConnection(String host,String username,String password) {
        try {
            Connection connection = new Connection(host);
            //建立ssh2连接
            connection.connect();
            //检验用户名
            boolean login = connection.authenticateWithPassword(username,password);
            if (login){
                logger.info(host + " 连接成功");
                return connection;
            }else {
                throw new RuntimeException(host + " 用户名密码不正确");
            }
        } catch (Exception e) {
            throw new RuntimeException(host +" "+ e);
        }
    }

    /**
     * 执行命令
     * @param connection ssh2连接对象
     * @param command 命令语句
     * @return 执行结果, 封装执行状态和执行结果
     */
    public static ExecCmdResult execCommand(Connection connection,String command){
        ExecCmdResult execCmdResult = new ExecCmdResult();
        Session session = null;
        try{
            session = connection.openSession();
            //执行命令
            session.execCommand(command);
            //解析结果
            String result = parseResult(session.getStdout());
            //解析结果为空,则表示执行命令发生了错误,尝试解析错误出输出
            if (result == null||result.length()==0){
                result = parseResult(session.getStderr());

            }else {
                execCmdResult.setSuccess(true);
            }
            //设置响应结果
            execCmdResult.setResult(result);
            logger.info(command + " ==>> " +execCmdResult.getResult());
            return execCmdResult;

        }catch (Exception e){
            e.printStackTrace();
        }
        return null;
    }

    public static String parseResult(InputStream inputStream) throws IOException{
        //读取输出流内容
        BufferedReader br = new BufferedReader(new InputStreamReader(inputStream,DEFAULT_CHARSET));
        StringBuffer resultSB = new StringBuffer();
        String line;
        while((line = br.readLine()) != null){
            resultSB.append(line+"\n");
        }
        //替换换行符
        String result = resultSB.toString().replaceAll("[\\t\\n\\r]", "");
        return result;

    }
}

3、ExecCmdResult 定义返回结果类

public class ExecCmdResult {

    //命令执行是否成功
    private boolean success;
    //输出结果
    private String result;

    public void setSuccess(boolean success){
        this.success = success;
    }
    public String getResult(){
        return result;
    }
    public void setResult(String result){
        this.result = result;
    }

}

4、SSH2Demo 测试

import ch.ethz.ssh2.Connection;

public class SSH2Demo {

    public static void main(String[] args) {
        try {
            String host = "168.192.22.7";
            String username = "root";
            String password = "123456";
            Connection connection = SSH2Util.openConnection(host,username,password);
            String cpuInfo = "cat /proc/cpuinfo | grep \"cpu cores\" | uniq"; //服务器核数
            ExecCmdResult cup = SSH2Util.execCommand(connection,cpuInfo);
            connection.close();

        }
        catch (Exception a){
            a.printStackTrace();
        }
    }
}
  • 0
    点赞
  • 11
    收藏
    觉得还不错? 一键收藏
  • 打赏
    打赏
  • 0
    评论

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

JOSON.

你的鼓励是我创作最大的动力

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

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

余额充值