Java如何实现连接Linux 执行Bash命令?

本文基于一个古老的工具库,多年前已停止维护。但市场上此类工具少之又少。

GitHub地址:GitHub - northern-bites/ganymed-ssh2: Ganymed Java SSH2 Protocol

引入依赖库

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

工具方法

import ch.ethz.ssh2.Connection;
import ch.ethz.ssh2.Session;
import ch.ethz.ssh2.StreamGobbler;
import lombok.extern.slf4j.Slf4j;
import xin.cosmos.basic.exception.RuntimeException;

import java.io.*;
import java.nio.charset.StandardCharsets;

/**
 * Linux ssh2 shell命令行执行工具类
 */
@Slf4j
public class Ssh2Utils {
    private String ip = "127.0.0.1";
    private int port = 22;
    private String username = "user1";
    private String password = "pwd1";

    /**
     * 初始化连接
     */
    private Connection init() {
        Connection connection = null;
        try {
            connection = new Connection(ip, port);
            // 建立连接
            connection.connect();
            // 进行认证
            connection.authenticateWithPassword(username, password);
        } catch (IOException e) {
            connection.close();
            throw new RuntimeException("主机认证失败" + e.getMessage());
        }
        return connection;
    }

    /**
     * 执行远程命令.
     *
     * @param command shell脚本命令
     */
    public String execute(String command) {
        String result;
        Connection connection = null;
        Session session = null;
        try {
            connection = init();
            //打开一个会话
            session = connection.openSession();
            //执行命令
            session.execCommand(command);
            // 得到标准输出结果
            result = processStdout(session.getStdout());
            //如果为得到标准输出为空,说明脚本执行出错了
            if (result == null) {
                result = processStdout(session.getStderr());
                log.error("执行命令[{}], 执行失败响应结果[{}]", command, result);
                throw new RuntimeException("执行命令[" + command + "]失败, error[" + result + "]");
            } else {
                log.info("执行命令{}, 执行成功响应结果{}", command, result);
                return result;
            }
        } catch (IOException e) {
            log.error("执行命令失败, 执行的命令{}出错", command, e);
        } finally {
            try {
                if (session != null) {
                    session.close();
                }
                if (connection != null) {
                    connection.close();
                }
            } catch (Exception e) {
                log.info("登录连接失败", e);
            }
        }
        return "执行失败";
    }

    /**
     * 执行命令返回集.
     */
    private String processStdout(InputStream in) {
        InputStream stdout = new StreamGobbler(in);
        StringBuilder buffer = new StringBuilder();
        try {
            BufferedReader br = new BufferedReader(new InputStreamReader(stdout, StandardCharsets.UTF_8));
            String line;
            while ((line = br.readLine()) != null) {
                buffer.append(line).append("\n");
            }
        } catch (IOException e) {
            log.error("解析脚本出错", e);
        }
        return buffer.toString();
    }

}

另外,也可基于另一个依赖库实现同样的功能

<!-- jsch的方式 远程连接的包-->
<dependency>
	<groupId>com.jcraft</groupId>
	<artifactId>jsch</artifactId>
	<version>0.1.55</version>
</dependency>

链接:GitHub - gengzhy/jsch: Mirror of JSch from JCraft.

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

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

打赏作者

流沙QS

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

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

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

打赏作者

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

抵扣说明:

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

余额充值