20 Ekim 2011 Perşembe

SSH client connection example with JCraft's Java Secure Channel (JSch)

One of the best libraries for SSH connection through Java is JSch. It is JCraft's utility.

Maven dependency for the latest version of Jsch is:

   com.jcraft
   jsch
   0.1.44-1


The main block of the code below is for connecting to the server through SSH, running "ls -la" command and printing the response to System.out

import com.jcraft.jsch.*;

import java.io.DataInputStream;
import java.io.DataOutputStream;
import java.io.IOException;

public class SSHClient {
    public static void main(String[] args) throws JSchException, IOException {
        String endLineStr = " # "; // it is dependant to the server
        String host = ""; // host IP
        String user = ""; // username for SSH connection
        String password = ""; // password for SSH connection
        int port = 22; // default SSH port

        JSch shell = new JSch();
        // get a new session  
        Session session = shell.getSession(user, host, port);

        // set user password and connect to a channel
        session.setUserInfo(new SSHUserInfo(password));
        session.connect();
        Channel channel = session.openChannel("shell");
        channel.connect();

        DataInputStream dataIn = new DataInputStream(channel.getInputStream());
        DataOutputStream dataOut = new DataOutputStream(channel.getOutputStream());

        // send ls command to the server
        dataOut.writeBytes("ls -la\r\n");
        dataOut.flush();

        // and print the response 
        String line = dataIn.readLine();
        System.out.println(line);
        while(!line.endsWith(endLineStr)) {
            System.out.println(line);
            line = dataIn.readLine();
        }
        dataIn.close();
        dataOut.close();
        channel.disconnect();
        session.disconnect();
    }

    // this class implements jsch UserInfo interface for passing password to the session
    static class SSHUserInfo implements UserInfo {
        private String password;

        SSHUserInfo(String password) {
            this.password = password;
        }

        public String getPassphrase() {
            return null;
        }

        public String getPassword() {
            return password;
        }

        public boolean promptPassword(String arg0) {
            return true;
        }

        public boolean promptPassphrase(String arg0) {
            return true;
        }

        public boolean promptYesNo(String arg0) {
            return true;
        }

        public void showMessage(String arg0) {
            System.out.println(arg0);
        }
    }

}

4 yorum:

  1. I am trying to do SSH over SSH. Means I connect to gateway using SSH and my server resides behind the gateway so I need to SSH to server. Is there any good solution for it?

    YanıtlaSil
  2. Hi ! While connecting to host Ip = "xx.xx.xx.xx".
    Getting error in below line
    session.connect();

    Error:
    Exception in thread "main" com.jcraft.jsch.JSchException: reject HostKey: xx.xx.xx.xx

    Running this code in eclipse in windows.
    Please help me what wrong I am doing.

    YanıtlaSil
  3. Problem statement - exceute shell script on remote server.

    Hi, Is it mandatory to take password using keyboard -interactive method. I am getting Auth Failure error when I hard code Password value for unit testing purpose. I tried even session.setpassword("PasswordSring".getBytes()) but it didnt worked out Is there any problem with setpassword method. Also none of the code example shows config.put("preferredAuthentication","Password"). If you dont give it it throws Auth cancel expception. My password is valid and I am using same password in putty and it works fine. Also I am able to execute shell script using putty. Is it related to my access on Server or something to do with setpassword method.

    YanıtlaSil