Problem executing Unix script from Java...

Hi there, I'm having trouble executing a unix script from a java program. The script receives multiple parameters and it seems that one of them ( or more ) is not well interpreted. When I run the script directly from a shell, the script executes without any errors. But, when I run the exact same script with the exact same parameters, it does not work.
Here is the command to execute the script with all the parameters that is executed from the shell ( with success ) and also from the java program ( with errors ):
/z/opus/dcap/intfu001.csh 'NODEBUG^NOTKPROF^NOSTACK' opus dcap JACQUES JACQUES '2625781' 'ORA$PIPE$001D00D70001' JOB^DEBUG^SINISIMU^STATPROD^DECTIDANC^81^503^4080^86^87^151^97^98^99 BUT^N^N^SPRI^0^13^24^3^J^05^N^19^19^19 >> /tmp/switcher8.999.null.pgm.test
And here is my portion of code that executes the script:
Runtime wShell = Runtime.getRuntime();
Process wProc = wShell.exec(cmd_unix_final);
wProc.waitFor();
return wProc.exitValue();
Please give me your thoughts on this!
Thanks in advance!

Ok.
Let's proceed surgically, else we'll never solve or overcome anything.
In the last your reply you wrote:
the normal output is what I get when the script runs successfully, the script first prints a few things
and then does stuff that takes at least 2 or 3 secondsWhat do you mean?
-Finally have you got your script correctly executed?
The stuffs you spoke of are really performed?
If this is the case I can't see the prob.
Is your concern only about exitValue() for it doesn't let you distinguish programmatically
the success or failure of the script execution?
Of course you surely already have a routine in your java code to handle
exceptional situations of errors from the script.
And the "normal output" is just what you must parse to detect those errors.
Then who cares about exitValue() in this case?
Don't invoke it, relay on the stdout and stderr of the script.
-Or you get only a deceiving standard output
that let you think the script execution went alright, while instead it didn't.
In this case we have to investigate some other thing.
I can't still exclude that the problem isn't related with the buffer size of the stdout
allocated by the environment to the subprocess. You spoke of few things printed out.
Be explicit. What's the size of the output you get?
And is the "normal output" complete till the very last char
or is it truncated from somewhere on?
Also it's important that you hit a ps command after the java main process terminates
(or simply when waitFor() returns) and see if the script subprocess hung up.
As an alternative approach directly call your pro*C code from Java through JNI, instead of translating it.
1. Exec.java
public class Exec{
     static{
          System.loadLibrary("Exec");
     public static native void proCFunct();
     public static void main( String[] args){
          proCFunct();
}2. javac Exec.java
3. javah Exec
4.Exec.c
#include "Exec.h"
JNIEXPORT void JNICALL Java_Exec_proCFunct(JNIEnv * a, jclass b){
     //here call the function that executes the script
5. cc -G -I$JAVA_HOME/include -I$JAVA_HOME/include/solaris -I$YOUR_INCLUDES Exec.c -o libExec.so
6. setenv LD_LIBRARY_PATH .
7. java Exec

Similar Messages

  • How execute Unix script from java?

    Can I execute Unix script from java?

    Yes. Using ProcessBuilder. And read [When Runtime.exec() wont|http://www.javaworld.com/javaworld/jw-12-2000/jw-1229-traps.html]. It's old, but pretty much all of it is still true.

  • Execute UNIX  script from java not working

    Hi
    I am having difficulty running my java program to execute UNIX script on a Windows box. Here is my code.
    public boolean executeScript() {
              try {
                   String testScript= "WEB-INF/scripts/test.sh";
                   File file = new File(copyToQaScript);
                   System.out.println(file.getAbsolutePath());
                   Process proc = Runtime.getRuntime().exec(file.getAbsolutePath());
              } catch (IOException ioe) {
                   ioe.printStackTrace();
                   logger.error(ioe);
              } catch (RuntimeException re) {
                   re.printStackTrace();
                   logger.error(re);
              } catch (Exception e) {
                   e.printStackTrace();
                   logger.error(e);
              return true;
         }When I execute this method, I am getting IOException as below.
    java.io.IOException: CreateProcess: C:\tomcat-5.0.28\webapps\myProject\WEB-INF\scripts\test.sh error=193
    Can anyone help me? Thanks.

    kminkeller wrote:
    Yes I have Cygwin installed. I am quite aware of that thanks Sabre.Then you need something like
          String[] command = {"bash","/home/sabre/bin/fred.sh"};
            Process p = Runtime.getRuntime().exec(command);
      if the executabe directory (/home/sabre/bin in my case) is not on the PATH or
          String[] command = {"bash","fred.sh"};
            Process p = Runtime.getRuntime().exec(command);
      if it is.

  • Executing unix scripts from java...

    Hi guys,
    I'm pretty new at this java stuff, but can someone tell me if it's possible to have a java object that connects to a specific unix box through a given IP and Port and execute a Unix shell command? The shell script creates a file that will be later ftp'ed from the UX box back to the PC I ran the java program from. Any ideas?
    Thanks in advance.

    Yes I thank it can be done. I have not done it but you prob can do it through tcp/ip useing ServerSocket and socket class.Make a server with the ServerSocket class on the linux box that is listening to the port and when it gets the right signal from your client on your pc/win the server will activate the sell script with the Runtime.getRuntime().exec(shellscript);
    Well just a thought GOOD LUCK

  • Excute unix script from java.

    Hi need to excute unix script from java application.
    My code is:
    public class Test
    public static void main(String args[])
         try{
         p = Runtime.getRuntime().exec("./qfe0"); //qfe0 is the name of the script.
    p.waitFor();
    catch(Exception e)
    e.printStackTrace();
    My problem is that using the waitFor() statement stuck the the script. if i don't use the waitFor() it works good but then i don't know when the script is finished.
    Any idea?

    The problem is likely to be that you script is either waiting for input or has filled the stdout buffer and you are not emptying it. Search this forum for this as its been answered many times before.

  • Run a UNIX Script from java

    Hi,
    how can i run a unix script from java application. This java application is on windows.
    How can i do this.
    thanks,

    Hi,
    how can i run a unix script from java application.
    This java application is on windows.
    So I think it's safe to assume that the target script is on a remote unix server.
    Take a look at http://sourceforge.net/projects/sshtools/

  • Is it possible to execute SAPGUI scripts from java program?

    Hi everyone..
         I need to develop an java applications that executes the SAPGUI script or any technique that execute set of transaction as client.
         Is it possible to execute SAPGUI scripts from java program? if so, how it can be achieved? is there any other technique to achieve above mention scenario?.
         it will be more helpful, if docs related to that are shared..
         Thanks in advance

    Oh, bummer. Would be much more convenient if I could just use iTunes for everything. Can't stand WMP. I wonder if WinAmp might be a good compromise?
    Thanks for this answer . . .
    Sharon

  • Executing unix script within java and getting the return value

    Hi
    I am executing a unix script from within java which will return me a value. Is there a way I get this value and use it inside my java code without doing this:
    BufferedReader in = new BufferedReader( new InputStreamReader( ls_proc.getInputStream() ));
    //readLine reads in one line of text
    int k = 1, i = 0;
    while (( ls_str = in.readLine()) != null)
    --kirk123                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                   

    I was hoping to get what I want in one or two line codes.
    --kirk123                                                                                                                                                                                           

  • Executing Unix scripts from a stored procedure

    From the sql*plus windows, I am able to execute the host command and '!sh' commands; but I need to ececute Unix scripts from a stored procedure. Hoe can I do this? Where can I get good documentation on this? Any help would be greatly appreciated!
    Thanks..

    Hi,
    U can use external procedure ( newly added feature in 8.0.3 onwards) and call any shared library. From shared library u can execute it.
    One sql command is there HOST(' '). U can run a OS command. But u can not use it in PL/SQL.
    U can call pls sql from shell !!!!!..
    Thanks...
    Boby Jose

  • Execute unix commands from Java

    Hi,
    I have a client application running on windows. This client should connect to a unix server and check for the existence of a file and display the result as "File found/File not found". In order to connect from windows to the unix server, I used the sockets and the connection is successfully established. The second part is to check for the presence of the file in unix server. I searched in google.com and the option I found to execute a unix command from java is the "Runtime.exec()". Runtime.exec is considered as the less effective (not a favorable) one.
    Is there any other option available (other than the Runtime) to execute the unix command from java? Can you please let me know.
    Thanks a lot
    Aishu

    So, please let me know how I can execute the above unix commands without Runtime.exec()You have a client and a server.
    You want something to run on the server, not the client.
    That means that something must in fact being running on the server before the client does anything at all.
    For example telnet. Or a J2EE server application.
    So is something like that running?
    If not then there absolutely no way to do what you want, even with Runtime.exec().
    If yes then what you do depends on what is running. So Runtime.exec() would be pointless if a J2EE server was running.

  • Execute Unix command from Java program running on windows

    Hello,
    I need to write a java program that fetches file count in a particular unix machine directory. But java program will be running on windows machine.
    The program should execute unix list command and fetch the output of that command.
    Can anyone help me on this?
    Thanks.

    Hi there,
    I had a similiar problem, though years ago. It was to have a java program execute any other. Lately, I've had to have a java program running on a unix machine execute a shell script. Entirely two different scenarios. I'm not sure what you will need for your app, but look into this:
    Java Native Interface for executing C/C++ code.
    C/C++ Code for launching the program you need to run.
    java.lang.Runtime(?).exec(....)
    With a combination of that stuff, you can make a launcher for any os that has Java running on it, and with Runtime, you can exec() pretty near any sort of unix shell or app command you'd like.
    Good luck.
    Tim

  • Executing Unix shell from Java Program

    Hi,
    I have written a java application using Maverick J2sshtools API which connects to a Unix box using SSH.The program authenticates with the remote box successfully,but It dosen't return the environment info or execute the test script.Have attached the complete code.
    package shellInteraction;
    import com.maverick.ssh.*;
    import com.maverick.ssh2.Ssh2Client;
    import com.maverick.ssh2.Ssh2Context;
    import com.maverick.ssh2.Ssh2PasswordAuthentication;
    import com.sshtools.net.*;
    import java.io.*;
    import java.util.Iterator;
    import java.util.Vector;
    public class JavaShell{
         public static void main(String[] args) {
              SshConnector con = null;
              SshClient ssh = null;
              ShellProcess process = null;
              Shell shell = null;     
              try{
                   // Create a session to remote host
                   con = SshConnector.getInstance();
                   ssh = connectionSetup(con);
                   System.out.println(ssh);
                   // Start a session and do basic IO
                   if (ssh.isAuthenticated()) {
                        shell = new Shell(ssh);
                        System.out.println("Authenticated");
                        if(shell.getEnvironment().hasEnvironmentVariable("hostname"))
                             System.out.println("We are connected to " + shell.getEnvironment().getEnvironmentVariable("hostname"));
                        //System.out.println("Remote operating system is " + shell.getEnvironment().getOperatingSystem());
                   //     boolean isWindows = shell.getEnvironment().getOSType()==ShellEnvironment.OS_WINDOWS;
                        //if(shell.getEnvironment().hasEnvironmentVariable("USERPROFILE")) {
                             //System.out.println("User home is " + shell.getEnvironment().getEnvironmentVariable("USERPROFILE"));
                        //} else if(shell.getEnvironment().hasEnvironmentVariable("HOME")) {
                             //System.out.println("User home is " + shell.getEnvironment().getEnvironmentVariable("HOME"));
                        // Commands only executed for Unix OS
                        //if(!isWindows) {
                             // Execute a script
                             traverseDirectory(shell);
                   shell.exit();
                   ssh.disconnect();
                   System.out.println("Shell has exited");
              } catch(Throwable t) {
                   t.printStackTrace();
         private static void traverseDirectory(Shell shell) throws Exception{
              System.out.println("\n\nTraverse Directory");
              // Execute a simple script than prints a directory tree
              ShellProcess process = shell.execute("bash test.sh ");
              try{
                   process.expect("Total directories", 1000, true);
                   System.out.print(process.toString());
              } catch (ShellTimeoutException ex1) {
                   System.out.println("TRAVERSE Expect operation timed out. Sending interrupt to kill the process");
                   process.interrupt();
              }finally {
                   process.close();
         static private Ssh2Client connectionSetup(SshConnector con)throws SshException{
              Ssh2Client ssh = null;
              final BufferedReader reader = new BufferedReader(new InputStreamReader(System.in));
              try {
                   System.out.print("Hostname: ");
                   String hostname = reader.readLine();
                   int idx = hostname.indexOf(':');
                   int port = 22;
                   if(idx > -1) {
                        port = Integer.parseInt(hostname.substring(idx+1));
                        hostname = hostname.substring(0, idx);
                   System.out.print("Username [Enter for " + System.getProperty("user.name") + "]: ");
                   String username = reader.readLine();
                   if(username==null || username.trim().equals(""))
                        username = System.getProperty("user.name");
                   System.out.println("Connecting to " + hostname);
                   * Create an SshConnector instance
                   con = SshConnector.getInstance();
                   // Lets do some host key verification
                   HostKeyVerification hkv = new PasswordHostKey();
                   con.setSupportedVersions(SshConnector.SSH2);
                   * Set our preferred public key type
                   con.getContext(SshConnector.SSH2).setHostKeyVerification(hkv);
                   ((Ssh2Context)con.getContext(SshConnector.SSH2)).setPreferredPublicKey(Ssh2Context.PUBLIC_KEY_SSHDSS);
                   * Connect to the host
                   ssh = (Ssh2Client)con.connect(new SocketTransport(hostname, port), username, true);
                   * Authenticate the user using password authentication
                   Ssh2PasswordAuthentication passwordAuthentication = new Ssh2PasswordAuthentication();
                   System.out.print("Password: ");
                   passwordAuthentication.setPassword(reader.readLine());
                   if(ssh.authenticate(passwordAuthentication)!=SshAuthentication.COMPLETE) {
                        System.out.println("Authentication failed!");
                        System.exit(0);
              }catch(Exception ex1) {
                   throw new SshException(ex1.getMessage(), ex1.getCause());
              return ssh;
    When I execute the program
    Hostname:****
    Username [Enter for thaya]: **
    Connecting to CATL
    The connected host's key (ssh-dss) is
    b6:85:91:6b:8b:ea:cb:40:b5:6f:01:2e:66:78:7f:62
    Password: *****
    SSH2 CATLMSXP62:22 [kex=diffie-hellman-group1-sha1 hostkey=ssh-dss client->server=aes128-cbc,hmac-sha1,none server->client=aes128-cbc,hmac-sha1,none]
    Authenticated
    Traverse Directory
    com.maverick.ssh.ShellTimeoutException: The shell did not return to the prompt in the given timeout period 10000ms
         at com.maverick.ssh.Shell.A(Unknown Source)
         at com.maverick.ssh.Shell.execute(Unknown Source)
         at shellInteraction.ShellInteraction.traverseDirectory(ShellInteraction.java:108)
         at shellInteraction.ShellInteraction.main(ShellInteraction.java:68)
    This is the error message what i get.

    use code tags if you want a response,
    ive done the same thing once using
    ssh2.ethz.ch ie:
    import ch.ethz.ssh2.Connection;
    import ch.ethz.ssh2.ServerHostKeyVerifier;
    import ch.ethz.ssh2.Session;
    the code looked something like this:
    try
                   conn.connect(new ServerHostKeyVerifier() {
                        public boolean verifyServerHostKey(String hostname, int port, String serverHostKeyAlgorithm, byte[] serverHostKey) throws Exception {
                             return true;
                  conn.authenticateWithPassword(username, password);
                  try {
                       sess = conn.openSession();
                   } catch (java.lang.IllegalStateException e) {
                        return;
    //                    JOptionPane.showMessageDialog(null, "Could not autheticate.\nCheck username and password.\nTerminating.", "Authentication Failed", JOptionPane.ERROR_MESSAGE);
    //                    System.exit(-1);
                   sess.requestPTY("dumb", 50, 50, 0, 0, null);
                   sess.startShell();
              }and after that sess has getStdIn() and getStdOut() that get the streams from which you read and write.

  • Error while executing UNIX script from BODS - exit code 127

    I am trying to execute a unix script by calling it in BODS job. It is giving an error saying Program terminated with exit code 127. The same script when i am executing in UNIX it is working fine. I am unable to trace the issue.

    Hi Sabre,
    As per the guidelines provided by the article, i had done below changes..
    InputStream is = null;
    InputStreamReader iStreamReader = null;
    BufferedReader bReader = null;
    String line = null;
    try{
    String fileName ="test.ksh";
    String argValue ="satish"; // value passed to the script
    String exeParam = "/usr/bin/ksh "+fileName+" "+argValue;
    Process proc = Runtime.getRuntime().exec(exeParam);
    is = proc.getErrorStream();
    iStreamReader = new InputStreamReader(is);
    bReader = new BufferedReader(iStreamReader);
    System.out.println("<ERROR>");
    while((line = bReader.readLine()) != null)
    System.out.println("Error is : "+line);
    System.out.println("</ERROR>");
    int exitValue = proc.waitFor();
    sop("Exit Value is : "+exitValue);
    catch(Exception e)
    e.printStackTrace();
    Now , it's showing something like..
    <ERROR>
    </ERROR>

  • Execute unix script from abap.

    Hi friends,
    I have a abap report which generate  a text file in<b> /usr/tmp/</b>  directory . Now i have a unix script   which encript the text file.  I want to this from abap report. How I can do this . and in which path  I should keep this unix script   Please help.
    Regards

    Hi,
    try the below code
    parameters : p_sfile(60) lower case
    "File to be moved
    "Eg : /home/in/SFILE1.txt
    p_dfile(60) lower case.
    "File's Destination
    "Eg: /home/archive/SFILE1.txt
    data : t_btcxpm
    like btcxpm occurs 0,
    p_addparam
    like sxpgcolist-parameters.
    concatenate
    '/home/ABAP/scripts/Archive_file.sh'
    p_sfile
    p_dfile
    into p_addparam separated by space.
    refresh t_btcxpm. clear t_btcxpm.
    call function 'SXPG_CALL_SYSTEM'
    exporting
    commandname = 'ZSHELL'
    additional_parameters = p_addparam
    tables
    exec_protocol = t_btcxpm
    exceptions
    no_permission = 1
    command_not_found = 2
    parameters_too_long = 3
    security_risk = 4
    wrong_check_call_interface = 5
    program_start_error = 6
    program_termination_error = 7
    x_error = 8
    parameter_expected = 9
    too_many_parameters = 10
    illegal_command = 11
    others = 12.
    if sy-subrc = 0.
    write : /
    'File',p_sfile,'moved to',p_dfile.
    else.
    write : / 'Error Occured'.
    endif.
    Reward points if found helpful……
    Cheers,
    Chandra Sekhar.

  • How to execute unix script in java program that is on unix .

    hi ,
    I want to call "sendfax" script that is for sending fax to Hylafax server.
    This sendfax script is called in client java program.

    I want to call "sendfax" script that is for sending
    fax to Hylafax server.
    This sendfax script is called in client java program.And what is your problem?

Maybe you are looking for