16 Jan 2013

Exec unix command with Java

Written by massi

To develop Unix connector of ConnId framework, I needed a good java library to execute unix command on remote server.

After several tests, I choose vngx-jsch, a library that, according to its developers, improves jsch library.

This is my first approach to this kind of development, so I could wrong my analysis, but... :)


I don't found a library only to connect with ssh2 protocol on remote server (my requisite). All the ssh2 library emulate a complete ssh2 protocol, so thay offer, for examples, also a X11 tunnel or shell emulation.

Having to use also personal computer as provisioning resource of Syncope, during test phase I found a library that its authenticate process fails on Appla machine (eg: sshtools)

Exec unix command with vngx-jsch

The methods shown below are the methods to execute a unix command and reads it result.

The method getChannelExec open an ssh session and return a channel to execute unix command:

private Channel getChannelExec() throws JSchException { session = sshClient.createSession(username, unixConfiguration.getHostname(), unixConfiguration.getPort()); session.connect(DefaultProperties.SSH_SOCKET_TIMEOUT, password.getBytes()); LOG.info("Connected to host " + unixConfiguration.getHostname()); return session.openChannel("exec"); }

The method exec takes a string (unix command) and return a InputStream that represents, as a stream, the output of unix command:

private InputStream exec(final String command) throws JSchException, IOException { LOG.info("Executing command: " + command); final Channel channel = getChannelExec(); ((ChannelExec) channel).setCommand(command); channel.setInputStream(null); ((ChannelExec) channel).setErrStream(System.err); final InputStream in = channel.getInputStream(); channel.connect(DefaultProperties.SSH_SOCKET_TIMEOUT); channel.disconnect(); return in; }

Finally the method printOutput takes the InputStream generated by exec convert it into a String human readable:

private String printOutput(final InputStream inputStream) throws IOException { String line; BufferedReader br = new BufferedReader( new InputStreamReader(inputStream)); StringBuilder buffer = new StringBuilder(); while ((line = br.readLine()) != null) { buffer.append(line).append("\n"); } session.disconnect(); return buffer.toString(); }


« Return