Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Jsch - Exit after Shell Script Execution

Tags:

java

unix

jsch

I'm trying to write a Java Program using Jsch where in I want to start the execution of a shell script using the program and exit the program once the execution of the shell script has been completed.

    String userName = "";
    String hostName = "";
    String password = "";

    JSch javaSecureChannel = new JSch();

    Session jschSession = null;
    Channel jschChannel = null;

    try {

        jschSession = javaSecureChannel.getSession(userName, hostName, 22);
        Properties configurationProperties = new Properties();
        configurationProperties.put("StrictHostKeyChecking", "no");
        jschSession.setConfig(configurationProperties);
        jschSession.setPassword(password);
        jschSession.connect();
        jschChannel = null;
        jschChannel = jschSession.openChannel("shell");
        jschChannel.setOutputStream(System.out);

        File shellScript = createShellScript();

        FileInputStream fin = new FileInputStream(shellScript);
        byte fileContent[] = new byte[(int) shellScript.length()];
        fin.read(fileContent);
        InputStream in = new ByteArrayInputStream(fileContent);
        jschChannel.setInputStream(in);         
        jschChannel.connect();

        while(true){                

            //if(jschChannel.isClosed)
            if(jschChannel.getExitStatus() == 0){
              System.out.println("exit-status: " + jschChannel.getExitStatus());
              break;
            }

            try{
                Thread.sleep(1000);
            }catch(Exception ee){
                ee.printStackTrace();
            }

          }

    } catch (Exception e) {
        e.printStackTrace();
    }

    jschChannel.disconnect();
    jschSession.disconnect();
    System.out.println("Done...!!!");

createShellScript method is as follows.

    String temporaryShellFileName = "shellscript.sh";
    File fileStream = new File(temporaryShellFileName);

    try {

        PrintStream outStream = new PrintStream(new FileOutputStream(fileStream));
        outStream.println("#!/bin/bash");
        outStream.println("cd /u01/app/java/gids4x/Test");
        outStream.println("Test_with_NULL.sh");
        outStream.close();

    } catch (Exception e) {

        System.err.println("Error: " + e.getMessage());

    }

Using the above code, I'm able to start the execution of the shell script. However, I'm not bale to terminate the program execution even after the execution of the program is completed i.e. after the execution of the Script completes.

Can you please suggest what needs to be done exactly?

like image 252
Shreyas Avatar asked Oct 14 '25 04:10

Shreyas


2 Answers

I also faced the same issue and resolved it by using below two steps : 1. Sending last command as "exit" 2. Putting my mail thread sleep until channel is open

Please find the code as below :

public static void main(String[] arg){

  Channel channel=null;
  Session session=null;
try{
  JSch.setLogger(new MyLogger());
  JSch jsch=new JSch();
  jsch.addIdentity("C:\\testLinuxKey.key");

  String host=null;
  if(arg.length>0){
    host=arg[0];
  }
  else{
    host=JOptionPane.showInputDialog("Enter username@hostname",
                                     System.getProperty("user.name")+
                                     "@localhost"); 
  }
  String user=host.substring(0, host.indexOf('@'));
  host=host.substring(host.indexOf('@')+1);

  session=jsch.getSession(user, host, 22);

  // username and password will be given via UserInfo interface.
  UserInfo ui=new MyUserInfo();
  session.setUserInfo(ui);

  session.connect();

  channel=session.openChannel("shell");

  //channel.setInputStream(System.in);
  channel.setOutputStream(System.out);

  String temporaryShellFileName = "shellscript.sh";
    File fileStream = new File(temporaryShellFileName);

    try {

        PrintStream outStream = new PrintStream(new FileOutputStream(fileStream));
        outStream.println("id");
        outStream.println("sudo bash");
        outStream.println("cd /tmp/");
        outStream.println("/tmp/wasinfo.sh");
        outStream.println("exit");
        outStream.println("exit");
        outStream.close();
        FileInputStream fin = new FileInputStream(fileStream);
        byte fileContent[] = new byte[(int) fileStream.length()];
        fin.read(fileContent);
        InputStream in = new ByteArrayInputStream(fileContent);
        channel.setInputStream(in);  

    } catch (Exception e) {

        System.err.println("Error: " + e.getMessage());

    }

  channel.connect();
  while(channel.isConnected())
  {
      System.out.println("----- Channel On ----");
      Thread.currentThread().sleep(5000);
  }
  channel.disconnect();
  session.disconnect();
}
catch(Exception e){
  System.out.println(e);
  channel.disconnect();
  session.disconnect();      
}

System.out.println("Main End");
}
like image 178
Abhijit Kayal Avatar answered Oct 16 '25 18:10

Abhijit Kayal


I had a similar problem. I was running a shell in a window but couldn't get Java to terminate when the window was closed. I solved it by closing the input stream.

like image 39
Sidney Marshall Avatar answered Oct 16 '25 17:10

Sidney Marshall



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!