Connect to ssh server with java

I often have to write a program to connect to a ssh server and manage tasks. Here is how I do. First you need to download the library. You will find it here, it’s called JSch.

This simple program will connect to a server and execute a command. The output of the command will be displayed in the console.


import java.io.IOException;
import java.io.InputStream;
import com.jcraft.jsch.Channel;
import com.jcraft.jsch.ChannelExec;
import com.jcraft.jsch.JSch;
import com.jcraft.jsch.JSchException;
import com.jcraft.jsch.Session;

public class ConnectToServerWithSSH {

    public static void main(String[] arg) throws JSchException, IOException {

        String host = "hostname";
        String login = "login";
        String password = "password";
        String command = "ls -lrt";

        // If you don't have already accept the public key or else
        // you will have the error <em>com.jcraft.jsch.JSchException: UnknownHostKey: hostname</em>
        java.util.Properties config = new java.util.Properties();
        config.put("StrictHostKeyChecking", "no");

        Sch jsch = new JSch();

        Session session = jsch.getSession(login, hostname, 22);
        session.setTimeout(1000);
        session.setPassword(password);
        session.setConfig(config);
        session.connect();

        Channel channel = session.openChannel("exec");
        ((ChannelExec) channel).setCommand(command);

        channel.connect();

        InputStream in= channel.getInputStream();
        int c;
        StringBuilder output = new StringBuilder();
        while ((c = in.read()) != -1) {
            output.append((char) c);
        }

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

        System.out.println(output.toString());

    }

}

Related links :

This entry was posted in java programming and tagged , , , . Bookmark the permalink.

1 Response to Connect to ssh server with java

  1. Nicole says:

    It’s actually a cool and useful ppiece oof info. I amm glad thst you
    jusst shzred this useful info with us. Please keep uus informed
    lik this. Thqnks forr sharing.

Leave a comment