1

I tried to do the following steps in java.
1. ssh to remote machine(done using jsch) as below .

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 JSchExampleSSHConnection {
public static void main(String[] args) {
    String host="hostname";
    String user="sshuser";
    String password="sshpwd";
    String command1="ls";
    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();
    }

}
}
  1. Entering sudo su and password. Done using the below command . ((ChannelExec) channel).setCommand("echo 'password' | sudo -S docker ps -a");

unable to proceed with the next steps

  1. Enter docker exec -it dockername bash .
  2. Enter python manage.py cronName .

    I tried the below steps to achieve step 3 and 4. Tried with Runtime.getRuntime().exec("docker exec >-it dockername bash"). Is there any other way to run these commands. Any suggestions on this.

maksimov
  • 5,792
  • 1
  • 30
  • 38
  • Can you execute other commands remotely using the code above, e.g. 'ls'? – maksimov Apr 02 '18 at 17:43
  • Could this be relevant to what you are trying to do? https://stackoverflow.com/questions/7611183/how-do-i-run-multiple-commands-in-ssh-through-java – maksimov Apr 02 '18 at 17:45
  • 'ls' works fine. I'll refer to the given link and give a try. Thanks :) – automationguy Apr 02 '18 at 18:42
  • You'll save yourself a lot of pain if you set up an ssh key that lets you log in as "docker" without having to use su or sudo. – Kenster Apr 02 '18 at 20:33

1 Answers1

1

Allocate a Pseudo-Terminal by:

channel.setPty(true);

For executing commands inside a docker running container, like:

docker exec -it <container-name> <command>
Manoj Shekhawat
  • 429
  • 1
  • 3
  • 11