I am using SSHTools / J2SSH to connect to a server via SSH. Everything works fine, only problem is, that the output contains strange escape sequences / characters. I read somewhere, that these are color codes and that it is not an encoding issue.
Now my question is: How do I get rid of them? Seems like I need some sort of Terminal Emulation, which interprets or strips off these codes.
Here is the output of ls
:
[0m[01;34msketchbook[0m sketchbook.tar sketchbook.tar.tar [01;32msshsudo[0m [01;34mtmp[0m tmp.tar
(Note: There are other commands I need to call, so ls --color=never
won’t do the job.)
I tried the library Jsch before, there you can use ((ChannelShell)channel).setPty(false);
to get rid of these characters, but I did not find something similar for SSHTools.
Okay, just found out myself. Download Terminal Components library.
Then the following will work (based on this blogpost):
IOStreamConnector input = new IOStreamConnector();
IOStreamConnector error = new IOStreamConnector();
input.setCloseInput(false);
error.setCloseOutput(false);
input.connect(System.in, session.getOutputStream());
error.connect(session.getStderrInputStream(), System.out);
InputStream in = session.getInputStream();
TerminalEmulation emulation = new TerminalEmulation("vt320");
emulation.setRecordPrintableOnly(true);
emulation.startRecording(System.out);
byte[] buf = new byte[1024];
int r;
while ((r = in.read(buf)) != -1) {
emulation.putBytes(buf, 0, r);
}