Getting unwanted characters when reading command output from SSH server using JSch

These are ANSI escape codes that are normally interpreted by a terminal client to pretty [color] print the output.

If the server is correctly configured, you get these only, when you use an interactive terminal. In other words, if you requested a pseudo terminal for the session (what you should not, if you are automating the session).

The JSch automatically requests the pseudo terminal, if you used a “shell” channel, as that is supposed to be used for implementing an interactive terminal.

  • If you automate an execution of remote commands, you better use an “exec” channel, as shown in JSch Exec.java example.

  • Alternatively, you can prevent JSch from requesting the pseudo terminal by calling setPty. But I do not recommend using “shell” channel. Though if you need to, for whatever reason, you should call setPty(false) in any case, as that will prevent many other similar troubles. I actually already recommended that to you in your previous question.


Note to others: While I see why OP uses ls command, in general, one should use use SFTP API to retrieve a directory listing, instead of executing ls and parsing its output. Parsing ls output is a pretty unreliable approach.


Related questions:

Leave a Comment