You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

如何通过Java SSH客户端获取ls命令的执行结果?

修改方案:捕获命令输出流获取执行结果

你可以通过将ChannelExec的标准输出/错误输出定向到内存流,从而获取命令的执行结果,具体修改后的代码如下:

import org.apache.sshd.client.SshClient;
import org.apache.sshd.client.channel.ChannelExec;
import org.apache.sshd.client.channel.ClientChannelEvent;
import org.apache.sshd.client.session.ClientSession;
import org.apache.sshd.common.file.FilePasswordProvider;
import org.apache.sshd.common.keyprovider.KeyIdentityProvider;
import org.apache.sshd.common.security.SecurityUtils;
import org.apache.sshd.common.security.keypair.KeyPairResourceLoader;

import java.io.ByteArrayOutputStream;
import java.nio.file.Paths;
import java.security.KeyPair;
import java.util.Collection;
import java.util.EnumSet;

public class SshCommandExecutor {
    public static void main(String[] args) throws Exception {
        KeyPairResourceLoader loader = SecurityUtils.getKeyPairResourceParser();
        Collection<KeyPair> keys = loader.loadKeyPairs(null, Paths.get("~/.ssh/id_rsa"), FilePasswordProvider.EMPTY);
        SshClient client = SshClient.setUpDefaultClient();
        client.setKeyIdentityProvider(KeyIdentityProvider.wrapKeyPairs(keys));
        client.start();

        ClientSession session = null;
        ChannelExec channel = null;
        // 用于存储标准输出和错误输出的内存流
        ByteArrayOutputStream stdout = new ByteArrayOutputStream();
        ByteArrayOutputStream stderr = new ByteArrayOutputStream();

        try {
            session = client.connect("hudson", "xxx.xxx.xxx.xxx", 22).verify().getSession();
            session.auth().verify();

            channel = session.createExecChannel("ls");
            // 将通道的输出定向到内存流
            channel.setOut(stdout);
            channel.setErr(stderr);

            channel.open().verify();
            // 等待命令执行完成
            channel.waitFor(EnumSet.of(ClientChannelEvent.CLOSED), 0L);

            // 将字节流转换为字符串(指定UTF-8编码避免乱码)
            String commandOutput = stdout.toString("UTF-8");
            String errorOutput = stderr.toString("UTF-8");

            // 使用变量接收并处理结果
            System.out.println("命令执行结果:");
            System.out.println(commandOutput);
            if (!errorOutput.isEmpty()) {
                System.err.println("错误输出:");
                System.err.println(errorOutput);
            }
            System.err.println("退出状态:" + channel.getExitStatus());
        } finally {
            // 关闭资源,避免泄漏
            if (channel != null) channel.close(false);
            if (session != null) session.close(false);
            client.stop();
        }
    }
}

关键修改说明:

  • 新增ByteArrayOutputStream类型的stdout和stderr,用于在内存中捕获命令的输出内容
  • 通过channel.setOut(stdout)和channel.setErr(stderr),将SSH通道的输出定向到这两个内存流
  • 命令执行完成后,调用toString("UTF-8")将字节流转换为字符串,即可用变量接收完整的执行结果
  • 添加finally块统一关闭资源,避免SSH连接和通道资源泄漏

内容的提问来源于stack exchange,提问作者xiaoaiaxss

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.07.12 14:28:23