JSch Client Exec Channel Example with flushing data — run command passwd

JSch is a pure Java library that implemens SSH2. However, it is poorly documented and finding a good example is difficult. I’ll demonstrate how we can use JSch in a more efficient manner, I chose the “passwd” command because it prompts you for a new password when you type it into the shell terminal. Let’s begin by implementing the “host” class:

Continue by implementing auth method classes:

Carry on with the implementation of the Authentication class, which has a user name and a corresponding authentication method:

Let’s implement an enumeration to keep track of different ssh channel types:

Carry on with the implementation of the Client Session Operator which takes host name, authentication and preferably the connection port as parameters to init and start session as well as create appropriate ssh channel. (Only the Exec channel will be implemented)

Lets create the most important class that will allow us to operate more efficiently:
ExecInteract is a class that takes an exec channel and a command string as parameters and runs it on that channel.

Let’s make StandardExecInteract class that takes a command and executes it on channel exec, then waits for a response.

At this stage, see an example of command running using the Standard Interact class:

This is the ide output:

When you perform the passwd command, the exec channel console prompts you for a new password and waits for interact; if no interact occurs after 2000 milliseconds, the channel is immediately closed.

Let’s make a class that runs the passwd command and flushes the new password (twice) (systematically) when the exec channel prompts for it.

Try it:

The ide result is:

Keep in mind that the Exec channel returns passwd output as an error, but the exit status is 0.

Best regards…

Java, Flutter — Dart Software Developer