Usually we amazon ec2 instance SSH tunnel with private key. You can access shell of EC2 instance using PUTTY. If you want to transfer files, then you can make use of FileZilla. These both tools works with SSH tunnel. There is jSch library for Java programmers to create SSH tunnel

Required Java Library

Here we need jSch jar file, download it from here

Java Program

Observe below program. It needs IP address and .pem file of your EC2 Instance. This program will make your console as linux shell. You can enter commands in your java console, those commands will be executed as shell commands in EC2 instance. Change below highlighted text with your EC2 info
import com.jcraft.jsch.*;

public class JConnectEC2shell{
  public static void main(String[] arg){
    
    try{
      JSch jsch=new JSch();

      String user = "ec2-user";
      String host = "Enter Ip address of your instance";
      int port = 22;
      String privateKey = "D:\\privateKeyFile.pem";

      jsch.addIdentity(privateKey);
      System.out.println("identity added ");

      Session session = jsch.getSession(user, host, port);
      System.out.println("session created.");

      // disabling StrictHostKeyChecking may help to make connection but makes it insecure
      // see http://stackoverflow.com/questions/30178936/jsch-sftp-security-with-session-setconfigstricthostkeychecking-no
      // 
         java.util.Properties config = new java.util.Properties();
         config.put("StrictHostKeyChecking", "no");
         session.setConfig(config);

      session.connect();

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

      // Enable agent-forwarding.
      //((ChannelShell)channel).setAgentForwarding(true);

      channel.setInputStream(System.in);
      /*
      // a hack for MS-DOS prompt on Windows.
      channel.setInputStream(new FilterInputStream(System.in){
          public int read(byte[] b, int off, int len)throws IOException{
            return in.read(b, off, (len>1024?1024:len));
          }
        });
       */

      channel.setOutputStream(System.out);

      /*
      // Choose the pty-type "vt102".
      ((ChannelShell)channel).setPtyType("vt102");
      */

      /*
      // Set environment variable "LANG" as "ja_JP.eucJP".
      ((ChannelShell)channel).setEnv("LANG", "ja_JP.eucJP");
      */

      //channel.connect();
      channel.connect(3*1000);
    }
    catch(Exception e){
      System.out.println(e);
    }
  }
}

Execute Multiple Commands from file

Save all shell commands in a file. Java program will read all commands from file and execute them in order. Instead of giving System.in as input stream, give new FileInputStream(text file path)
/*
 testCmd.txt file content ---

 sudo su
 cd /var/lib
 ls

*/
channel.setInputStream(new FileInputStream(new File("D://testCmd.txt")));

6 comments:

  1. while running code I am getting below error, Could you please help.

    identity added
    session created.
    com.jcraft.jsch.JSchException: channel is not opened.

    ReplyDelete
  2. not working giving connection error

    ReplyDelete
  3. Thanks for your post. I tried this but I have an exception.
    com.jcraft.jsch.JSchException: Auth fail
    this exception at session.connect();
    I looking solution for this exception. What can i do?

    ps) my .pem file is work. I have connect ssh on terminal.

    ReplyDelete
    Replies
    1. I found solution. It's wrong host.
      It works!!!

      Delete
  4. how can I connect to Ec2 instance using username/password, instead of .pem file?

    ReplyDelete

Blogroll

Popular Posts