0

using below code i can able to connect but i have another server where it doesn't require any un or pwd to access, i have to pass private key for that, so can anyone help me what modifications do i need to do for below code.

import java.io.InputStream;

import com.jcraft.jsch.Channel;
import com.jcraft.jsch.ChannelExec;
import com.jcraft.jsch.JSch;
import com.jcraft.jsch.Session;


public class ConnectionPutty {

    /**
     * JSch Example Tutorial
     * Java SSH Connection Program
     */
    public static void main(String[] args) {
        String host="xxxx";
        String user="xxxx";
        String password="xxxx";
        String command1="xxxx";
        try{

            java.util.Properties config = new java.util.Properties(); 
            config.put("StrictHostKeyChecking", "no");
            JSch jsch = new JSch();
            Session session=jsch.getSession(user, host, 22);
            session.setPassword(password);
            session.setConfig(config);
            session.connect();
            System.out.println("Connected");

            Channel channel=session.openChannel("exec");
            ((ChannelExec)channel).setCommand(command1);
            channel.setInputStream(null);
            ((ChannelExec)channel).setErrStream(System.err);

            InputStream in=channel.getInputStream();
            channel.connect();
            byte[] tmp=new byte[1024];
            while(true){
              while(in.available()>0){
                int i=in.read(tmp, 0, 1024);
                if(i<0)break;
                System.out.print(new String(tmp, 0, i));
              }
              if(channel.isClosed()){
                System.out.println("exit-status: "+channel.getExitStatus());
                break;
              }
              try{Thread.sleep(1000);}catch(Exception ee){}
            }
            channel.disconnect();
            session.disconnect();
            System.out.println("DONE");
        }catch(Exception e){
            e.printStackTrace();
        }

    }

} 

so please help me here, also please share any video links available for jsch learnings

  • You might be best using a private key, similar to how you would using SSH on the command line. That will save you having to store passwords securely. Check the library documentation for doing this. – Phil Dec 06 '17 at 17:26
  • A username is required, the private key only eliminates the password. – Jim Garrison Dec 06 '17 at 17:27

0 Answers0