Search code examples
groovysoapuijsch

Parse JSCH response to list


I'm trying to parse the response from JSCH (it was a grep cmd with multiple lines as a response) and i'm trying to add each line to a list (for later processing). I'm using the shell channel if that means anything. Here's the function:

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()
        responseString.eachLine { line ->
            lines.add(line.replaceAll("(\\x9B|\\x1B\\[)[0-?]*[ -\\/]*[@-~]", ""))
        }
        if (lines.find { it.contains(prompt) }) {
            return lines
        }
        outputStream.reset()
    }
    throw new Exception("Prompt failed to show after specified timeout")
}

I do see both entries, but the list that's created only has one item (the entire response ;( ). Why?


Solution

  • Long story short, dont use the shell, use exec channel. I stopped using the prompt instead I'm doing this:

    private String getChannelOutput(Channel channel, InputStream in) throws IOException{
        byte[] buffer = new byte[1024]
        StringBuilder strBuilder = new StringBuilder();
        String line = ""
        while(!channel.isClosed()){
            while (in.available() > 0) {
                int i = in.read(buffer, 0, 1024)
                if (i < 0) {
                    log.info('found no response')
                    break;
                }
                strBuilder.append(new String(buffer, 0, i))
                Thread.sleep(100)
            }
        }
        return strBuilder.toString()        
    }