0

Execute Unix commands using Jsch maven

I'm trying use this code for performing the following steps, but it's not working.

  1. String command1 = "ls -ltr"
  2. String command2 = "cd /test/user/"
  3. String command3 = "./test.sh"

Reference Link.

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);
// From above command does work! It lists the files.
((ChannelExec)channel).setCommand(command2);

But the last line doesn't work--nothing happens.

1 Answer 1

1

You forgot to connect to the channel, e.g.

channel.connect();

Then you need to read the response. There is an example at http://www.jcraft.com/jsch/examples/Exec.java.html

InputStream in=channel.getInputStream();

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()){
    if(in.available()>0) continue; 
    System.out.println("exit-status: "+channel.getExitStatus());
    break;
  }
  try{Thread.sleep(1000);}catch(Exception ee){}
}

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Not the answer you're looking for? Browse other questions tagged or ask your own question.