user778900
user778900

Reputation: 301

Java code to execute a .sh file

I have a .sh file stored in some Linux system. The full path of the file is:

/comviva/CPP/Kokila/TransactionHandler/scripts/stopTH.sh

I am tring to execute it by

Runtime.getRuntime().exec(`/comviva/CPP/Kokila/TransactionHandler/scripts/stopTH.sh`)

but it is throwing some exception.

I want to execute that file from my java program in an MS-Windows environment; is it possible?

Upvotes: 0

Views: 21327

Answers (5)

Mokhtar Ashour
Mokhtar Ashour

Reputation: 600

you may make a .bat file(batch file), that can run on windows. put the content of the .sh file in the .bat file start a process from your application like :

Process.Start("myFile.bat");

Upvotes: 0

user778900
user778900

Reputation: 301

Thanks everybody for your responses. I found a solution to the problem. For this kind of situation we need to bind my Windows machine to Linux system. Here is the code that worked:

public String executeSHFile(String Username, String Password,String  Hostname)
    {
        String hostname = Hostname;
        String username = Username;
        String password = Password;
        try{
            Connection conn = new Connection(hostname);
               conn.connect();
               boolean isAuthenticated = conn.authenticateWithPassword(username, password);
               if (isAuthenticated == false)
                throw new IOException("Authentication failed.");
               Session sess = conn.openSession();
              sess.execCommand("sh //full path/file name.sh");

               System.out.println("Here is some information about the remote host:");
               InputStream stdout = new StreamGobbler(sess.getStdout());
               BufferedReader br = new BufferedReader(new InputStreamReader(stdout));
               while (true)
                {
                    String line = br.readLine();
                    if (line == null)
                        break;
                    current_time=line;
                    System.out.println(line);
                }

               System.out.println("ExitCode: " + sess.getExitStatus());
               /* Close this session */

                sess.close();

                /* Close the connection */

                conn.close();
        }catch(IOException e)
        {
            e.printStackTrace(System.err);
            System.exit(2);
        }finally{

        }
}

Thank you.

Upvotes: 3

ewan.chalmers
ewan.chalmers

Reputation: 16255

To execute a .sh script on Windows, you would have to have a suitable command interpreter installed. For example, you could install the Cygwin environment on your Windows box and use it's bash interpreter.

However, Windows is not Linux even with Cygwin. Some scripts will not port from one environment to the other without alterations. If I had a problem executing a script via Java in Linux environment, I would prefer to debug the issue in that environment.

Remember, you could start your Java process on Linux in debug mode and attach your IDE debugger in Windows to that remote process.

Upvotes: 3

rompetroll
rompetroll

Reputation: 4799

I did a quick test here, the following works assuming you have /bin/bash on your machine:

my /tmp/test.sh:

#!/bin/bash
echo `ls`

my java code:

try {
    InputStream is = Runtime.getRuntime().exec("/bin/bash /tmp/test.sh").getInputStream();
    int i = is.read();
    while(i > 0) {
        System.out.print((char)i);
        i = is.read();
    }
} catch (IOException e) {
    e.printStackTrace();
}

output: all files in current directory

edit: i kinda overlooked that "execute from windows" comment. I don't know what you mean with that.

Upvotes: 1

Andy Canfield
Andy Canfield

Reputation:

Here is my code. As the comment says, works on Linux, fails on Windows (XP). AFAIK the problem with Windows is that cmd.exe is weird regarding it's parameters. For your specific sub-task you probably can get it to work by playing with quotes and maybe embedding the sub-task parameters in the subtask itself.

/** Execute an abritrary shell command.
  * returns the output as a String.
  * Works on Linux, fails on Windows,
  * not yet sure about OS X.
  */
public static String ExecuteCommand( final String Cmd ) {
    boolean DB = false ;
    if ( DB ) {
        Debug.Log( "*** Misc.ExecuteCommand() ***" );
        Debug.Log( "--- Cmd", Cmd );
    }
String Output = "";
String ELabel = "";
    String[] Command = new String[3];
    if ( Misc.OSName().equals( "WINDOWS" ) ) {
        Command[0] = System.getenv( "ComSPec" );
        Command[1] = "/C";
    } else {
        Command[0] = "/bin/bash";
        Command[1] = "-c";
    }
Command[2] = Cmd;
    if (DB ) {
        Debug.Log( "--- Command", Command );
    }
    if ( Misc.OSName().equals( "WINDOWS" ) ) {
        Debug.Log( "This is WINDOWS; I give up" );
        return "";
    }
try {
        ELabel = "new ProcessBuilder()";
        ProcessBuilder pb = new ProcessBuilder( Command );
        ELabel = "redirectErrorStream()";
        pb.redirectErrorStream( true );
        ELabel = "pb.start()";
        Process p = pb.start();
        ELabel = "p.getInputStream()";
        InputStream pout = p.getInputStream();
        ELabel = "p.waitFor()";
        int ExitCode = p.waitFor();
        int Avail;
        while ( true ) {
            ELabel = "pout.available()";
            if ( pout.available() <= 0 ) {
                break;
            }
            ELabel = "pout.read()";
            char inch = (char) pout.read();
            Output = Output + inch;
        }
        ELabel = "pout.close()";
        pout.close();
    } catch ( Exception e ) {
        Debug.Log( ELabel, e );
    }

    if ( DB ) {
        Debug.Log( "--- Misc.ExecuteCommand() finished" );
    }
    return Output;
}

}

Upvotes: 2

Related Questions