Linux to AWS EC2 connection with jsch with private key

Java program for Linux server to EC2 instance with ppk file,

 import com.jcraft.jsch.Channel;
 import com.jcraft.jsch.ChannelSftp;
 import com.jcraft.jsch.JSch;
 import com.jcraft.jsch.JSchException;
 import com.jcraft.jsch.Session;   
public class Linux2Ec2 {
     static Session session =null;
     static Channel channel = null;
      static ChannelSftp channelSftp = (ChannelSftp) channel;
     public static void main(String[] args) {
         try{
         String aws_user="ec2-user";
         String aws_port="22";
         String aws_host="000.00.000.00";
         String aws_privateKey="//C://private_key.ppk";
         JSch jsch = new JSch();

    session = jsch.getSession(aws_user, aws_host, 22);
    jsch.addIdentity(aws_privateKey);
    try {
        session = jsch.getSession(user, host);
    } catch (JSchException e) {

        e.printStackTrace();
    }


    java.util.Properties config = new java.util.Properties();
    config.put("StrictHostKeyChecking", "no");
    config.put("PreferredAuthentications",
            "publickey,keyboard-interactive,password");


    session.setConfig(config);
    try {
        session.connect();
    } catch (JSchException e) {

        e.printStackTrace();
    }

    try {
        channel = session.openChannel("sftp");
    } catch (JSchException e) {

        e.printStackTrace();
    }
    try {
        channel.connect();
    } catch (JSchException e) {

        e.printStackTrace();
    }

    System.out.println("sftp channel opened and connected.");
}

finally
{
    session.disconnect();
    channel.disconnect();

    System.out.println("Finished");

} 
}
 }

Leave a Reply

Your email address will not be published. Required fields are marked *