问题:我在使用 ChannelShell 时发送的命令中收到“有趣”的字符输出。我想知道如何获取您在 PuTTY session 中看到的常规输出。
我所说的“有趣”是指我应该看到这个:
testfile.txt
我看到了这个:
[01;32mtestfile.txt[00m
这与this question中的问题类似。但答案不能满足我的需要。答案是在 ChannelShell 上调用 setPty(false) ,这会完全删除“伪终端”,但我需要实时获取 ChannelShell 的输出。这是我正在做的事情的一个例子:
ChannelShell channel = (ChannelShell) session.openChannel("shell");
channel.setOutputStream(new PrintStream(
new ByteArrayOutputStream(), true, "UTF-8") {
@Override
public void write(byte[] b, int off, int len) {
super.write(b, off, len);
String output = new String(b, off, len);
System.out.print(output);
sendNextCommand(output); //Execution of the next command depends on the output here, this is why I need it to not have the funny characters.
}
});
PipedInputStream in = new PipedInputStream();
channelInput = new PipedOutputStream(in);
channel.setInputStream(in);
channel.connect();
while(!channel.isClosed() && channelWaitRetries++ < MAX_CHANNEL_WAIT_RETRIES) {
//Wait for additional output... Sort of a timeout deal. Kind of a hack...
sleep(2500); //Calls Thread.sleep. I just don't want the try/catch here.
System.out.println("Channel not yet closed. Retried " + channelWaitRetries + " of " + MAX_CHANNEL_WAIT_RETRIES);
}
sendNextCommand 方法用于检查输出是否与下一个要执行的命令需要显示的内容相匹配。所以基本上,当我看到这样的东西时: [user@server ~]$
然后执行这个: ls
应该返回这个: testfile.txt
但相反它返回的是:[01;32mtestfile.txt[00m
](注意:我无法复制并粘贴第一个字符,但它是一个带有字符代码 27,我认为是转义字符)。
现在我通常会逃避这种事情,但我宁愿把它做好,而且似乎还有很多奇怪的变体。所以我在这里。我希望你能帮忙:)
注意:我正在 Windows 机器上通过 IDE 运行这个程序(一个 Eclipse 盗版),但我尝试过调试,变量 output
实际上显示了“有趣”的字符。我还尝试在 JOptionPane.messageDialog
中显示它,只是为了确保它不仅仅是 IDE 并且仍然具有字符。谢谢!
最佳答案
是的,这些是 ANSI 转义序列,在 ls
的情况下,用于控制颜色。
ls
有一个 --color=never
选项,可以解决特定的 ls
问题。
所有命令都会发生这种情况,还是仅部分命令会发生这种情况?
调用ChannelShell.setPtyType("dumb")
也可能有帮助(未经测试)。您可能需要四处寻找禁用转义序列的终端类型。
您对 ls
进行脱壳而不是使用内置 Java 方法来检查目录内容有什么特殊原因吗?
关于java - 有趣的 Shell 输出 : [01;32mtestfile. txt[00m 而不是 testfile.txt,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/17221127/