1

I am trying to execute a remote query over SSH using pubic key/private key based authentication. Following command works fine and gives me the required output as a string on a bash shell after sharing the public keys between local host and the remote server.

echo 123456 12@13:14 ABCD abc1234 | ssh -T user@abc.xyz.com

How do I achieve the same with JAVA using JSCH or SSHJ or any other similar library

This is what I have tried so far using SSHJ but it did not work for me (Connection was successful but no results)

public static void main(String... args)throws IOException {
    final SSHClient ssh = new SSHClient();
    ssh.loadKnownHosts();

    ssh.connect("abc.xyz.com");
    try {
        ssh.authPublickey("user");
        final Session session = ssh.startSession();
        try {
            final Command cmd = session.exec("123456 12@13:14 ABCD abc1234");
            System.out.println(IOUtils.readFully(cmd.getInputStream()).toString());
            cmd.join(5, TimeUnit.SECONDS);
            System.out.println("\n** exit status: " + cmd.getExitStatus());
        } finally {
            session.close();
        }
    } finally {
        ssh.disconnect();
        ssh.close();
    }
}
Dileep
  • 29
  • 3
  • show some code... what issue are you facing?? – Abhishek Oct 29 '16 at 06:58
  • "_execute a remote query over SSH_". Remote query to _what service_? – Boris the Spider Oct 29 '16 at 07:00
  • I do not know what service is running on the server side and I do not have access to it. If I execute the above command on a shell, it gives me the required output. Is there a way to execute the same from java using JSCH or SSHJ so that I can convert it to a jar library file – Dileep Oct 29 '16 at 07:08

1 Answers1

0

Below code uses JSCH Library and is working on my end :-

        JSch jsch = new JSch();

        String path = "PATH TO PRIVATE KEY"; 

        jsch.addIdentity(path);

        jsch.setConfig("StrictHostKeyChecking", "no");

        Session session = jsch.getSession(userName, ipToConnect, portToConnect);
        session.connect();

        Channel channel = session.openChannel("exec");

        ((ChannelExec)channel).setCommand("COMMAND TO FIRE");

        channel.setInputStream(null);

        ((ChannelExec)channel).setErrStream(System.err);

        InputStream in = channel.getInputStream();

        channel.connect();

        //Read Response Here 

        channel.disconnect();
        session.disconnect();

Note : You can use password based authentication also instead of key bases with JSCH

Varun Sharma
  • 306
  • 3
  • 14