Search code examples
javalinuxsshjsch

JSch Esc commands and encoding


I'm writing an application to connect to a server over SSH, open an application (it runs on shell) and use it. I'm using JSch and I've managed to connect, open the app and send commands to it. Now I'm facing 2 problems:

  1. On Windows I'm having encoding problems with the app (on Linux if I use the IDE console output to run it I have the same problem, it only shows right on bash). Here's a screehshot:with wrong encoding here's the screenshot of what it should show: with right encoding
  2. The app I'm running, makes use of the ESC key and I cannot use it in the app I've write. It just writes ^[ on the output And here are the code I've used to do this application:

    JSch shell = new JSch();
    Session session = shell.getSession("myUser", "myHost");
    session.setPassword("myPassword");
    session.setConfig("StrictHostKeyChecking", "no");
    session.connect();
    Channel channel = session.openChannel("shell");
    channel.setOutputStream(System.out);
    PipedInputStream in = new PipedInputStream();
    PipedOutputStream out = new PipedOutputStream(in);
    channel.setInputStream(in);
    channel.connect();
    out.write("my_application\n".getBytes());
    Thread.sleep(1000); //waiting for the app to load
    out.write("\n".getBytes());
    out.write("appUser\n".getBytes());
    out.write("appPassword\n".getBytes());
    channel.setInputStream(System.in);
    

PS: the server uses sh and not bash.


Solution

  • As for your first question, those are ANSI escape codes. When you create a Jsch shell session, by default a pseudo-terminal will be allocated - this causes those sequences to be send. You can disable the pseudo terminal:

    ((ChannelShell)channel).setPty(false);

    For more, see this discussion.

    With regard to your second question, the problem is that on Windows Java's System.in is buffered, and will not allow you to relay the escape key easily. You should be able to read lines of text and send them to the remote application. For anything more, you'll have to resort to native code to get the actual key presses. See this discussion for more details on how to do that on different operating systems.