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

JSCH Shell Channel多行响应无法拆分存入List问题排查

问题原因及解决方法

核心原因

你的代码生成的List只有一个元素,主要是因为远程Shell输出的换行符与Groovy eachLine() 默认识别的换行符不匹配:

  • 远程Shell通过JSCH Channel输出的换行常为\r\n(CRLF格式),而Groovy的eachLine()默认使用当前JVM运行环境的行分隔符(比如Linux环境下是\n),导致\r\n未被识别为换行标记,整个响应内容被当成一行处理。

另外代码存在潜在问题:每次循环迭代时未清空lines集合,若多次循环累积内容,会导致List混入重复或无效数据。

修复后的代码

static public List<String> waitForPrompt(ByteArrayOutputStream outputStream, String prompt) throws Exception {
    int retries = 700
    List<String> lines = new ArrayList<>()
    for (int x = 1; x < retries; x++) {
        TimeUnit.SECONDS.sleep(1)
        String responseString = outputStream.toString()
        // 显式兼容LF和CRLF两种换行格式
        responseString.eachLine(/\r?\n/) { line ->
            lines.add(line.replaceAll("(\x9B|\x1B\\[)[0-?]*[ -\\/]*[@-~]", ""))
        }
        if (lines.find { it.contains(prompt) }) {
            return lines
        }
        // 清空集合,避免残留上一次循环的内容
        lines.clear()
        outputStream.reset()
    }
    throw new Exception("Prompt failed to show after specified timeout")
}

关键修改点

  • 用eachLine(/\r?\n/)替代默认方法,同时兼容\n(LF)和\r\n(CRLF)两种换行格式;
  • 每次循环结束后调用lines.clear(),确保下一次循环的集合为空。

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.07.22 11:02:43