How do I convert linux pseudo terminal output in Java?

722 views Asked by At

I want to connect to an Amazon EC2 terminal via JAVA API and perform sudo operations. I ended up using SSHJ library because I found its interface very simple and easy to use. The nice thing is that I can even execute sudo operations via this library. Here is some sample code:

// Start a new session session = sshClient.startSession(); session.allocatePTY("vt220", 80,24,0,0,Collections.emptyMap());

Command cmd = null;
String response = null;
// your allocating a new session there
try (Session session = sshClient.startSession()) {

     cmd = session.exec("sudo service riak start");
     response = IOUtils.readFully(cmd.getInputStream()).toString();
     cmd.join(timeout, timeUnit);
} finally {
    if (cmd != null) 
        cmd.close();
}

However, the response, I received back had control characters and wanted to convert them into plain text.

  Starting riak: [60G[[0;32m OK [0;39
1

There are 1 answers

0
systemboot On

After lot of research, I solved the problem using "jansi" java library(http://jansi.fusesource.org/)

So now my updated code looks something like this:

    Command cmd = null;
    try (Session session = sshClient.startSession()) {
        session.allocateDefaultPTY();
        cmd = session.exec(command);
        new StreamCopier(cmd.getInputStream(), AnsiConsole.out()).keepFlushing(true).copy();
        cmd.join(timeout, timeUnit);
    }finally{
        if(cmd != null){
            cmd.close();
        }
    }

And, this works beautifully.