1

I want to

  1. Login to remote host sever
  2. Change the directory to "/xxx/yyy/zz"
  3. Execute the abc.sh file kept at above location

have tried JSCH for which the code is specified below.

    package com.au.packageName;


import java.io.IOException;
import java.io.InputStream;
import com.jcraft.jsch.Channel;
import com.jcraft.jsch.ChannelExec;
import com.jcraft.jsch.JSch;
import com.jcraft.jsch.JSchException;
import com.jcraft.jsch.Session;

public class PuttyClass {

    public static void main(String[] args) throws JSchException, IOException 
    {


        Session session = new JSch().getSession("ID", "CorrectHostName", 22);        
        session.setPassword("PWD");
        java.util.Properties config = new java.util.Properties(); 
        config.put("StrictHostKeyChecking", "no");
        session.setConfig(config);
        session.connect();
        System.out.println(session.isConnected() );

        String commands[] = {"cd /scratch/bp_scripts/com.fc.cz.bp.batch/scripts/Script", "ls","sh exec_scenario.sh"};

        for (String command : commands) {

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

            channel.connect();
            channel.run();
            readInputStream(channel.getInputStream(), channel);
            channel.disconnect();
        }
        session.disconnect();       
    }

    public static String readInputStream(InputStream in, Channel channel) throws IOException, JSchException

    {

         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());
              return String.valueOf(channel.getExitStatus());

            }

          }
    }

}
  • 1st command gives no error but does not change the directory
  • 2nd command gives list of files from incorrect directory
  • 3rd command gives 127 unknown command

Please help where I am doing it wrong.

Mithilesh Indurkar
  • 481
  • 1
  • 5
  • 12

0 Answers0