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.

Similar Messages

  • 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/

  • 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.

  • 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

  • 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.

  • Unable to excute unix command from java program

    import java.io.File; // is java code
    public class RunSystemCommand {
    public static void main(String args[]) {
    String s = null;
    // system command to run
    String cmd = "ls ";
    // set the working directory for the OS command processor
    File workDir = new File("c:/cygwin/cygwin");
    Process p = Runtime.getRuntime().exec(cmd, null, workDir);
    p.waitFor();
    I am tryiing to excute above code to run unix command on cygwin but gave folllowing error...... but works well to open a note pad..
    Exception in thread "main" java.io.IOException: CreateProcess: C:/cygwin/bin err
    or=5
    at java.lang.Win32Process.create(Native Method)
    at java.lang.Win32Process.<init>(Unknown Source)
    at java.lang.Runtime.execInternal(Native Method)
    at java.lang.Runtime.exec(Unknown Source)
    at java.lang.Runtime.exec(Unknown Source)
    at java.lang.Runtime.exec(Unknown Source)
    at java.lang.Runtime.exec(Unknown Source)
    at d.main(d.java:19)
    It seems using this functionone cannot excute unix commands..please help to do so..

    Are you sure you want cygwin/cygwin?
    the following works fine for me, you may need change the workDir to your bin folder
    import java.io.File; // is java code
    import java.io.InputStream;
    public class RunSystemCommand {
        public static void main(String args[]) throws Throwable {
         String s = null;
         // system command to run
         String cmd = "ls ";
         // set the working directory for the OS command processor
         File workDir = new File("c:/cygwin/bin");
         Process p = Runtime.getRuntime().exec(cmd, null, workDir);
         InputStream pis = p.getInputStream();
         while( pis.read() != -1 ); // added, as otherwise the ls hangs.
         p.waitFor();
    }

  • 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

  • Example: Executing a shell script from java

    Hi. There are many other posts in the forums related to executing a unix script from java, but I wanted to post another example that I thought might be helpful...
    The key thing to executing the script is to include the -c switch for the sh command. This tells the sh command that you are passing a string to be interpreted as input. Without this switch, the script does not execute as you'd expect it to. Also, use a string array to pass each part of the sh command.
    Here is a working sample class, along with a test script to execute it:
    public class TestShellScript {
    public static void main(String[] args)
    String[] chmod = {"chmod","777","testscript1"};
    String[] runscript = {"sh","-c","./testscript1 > jdata.out"};
    Runtime rtime = Runtime.getRuntime();
    try
    rtime.exec(chmod); // Set the authorities for testing
    rtime.exec(runscript); // Run the script with redirection
    catch (IOException e)
    e.printStackTrace();
    rtime = null;
    Here is a test script to wrap the java call:
    #!/bin/sh
    cd /<your script dir>
    export -s CLASSPATH=/<your jar dir>/TestShellScript.jar
    export -s PATH=/<your script dir>:/usr/bin
    java TestShellScript
    - Hope this helps.

    I don't know exactly but the code written below is working fine try the same with your code .Even with your code instead running the code with
    " ./<filename> ",if you execute it with "sh <filename>" command without changing the mode of the file it is executing properly.
    import java.io.*;
    import java.util.*;
    public class ScriptBuilder
    public ScriptBuilder()
    public void writeScript() throws java.io.IOException
    FileWriter writer = new FileWriter(new File("test_script"));
    writer.write("#! /bin/sh\n");
    writer.write("ll>/home/faiyaz/javaprac/checkll");
    writer.flush();
    writer.close();
    Runtime rt= Runtime.getRuntime();
    rt.exec("chmod 777 test_script");
    rt.exec("./test_script");
    } public static void main (String[] args)throws java.io.IOException
    ScriptBuilder sb = new ScriptBuilder();
    sb.writeScript();
    }

  • How to execute unix shell script from Java ...

    Hi,
    Anyone know how to execute unix shell script from Java?
    Suppose I have several shell scripts written in perl or tcl or bash.
    I just want to catch the output of that script.
    Is there any ready to use module/object for this?
    Please let me know, this is quite urgent for my study assigment.
    Thanks in advance,
    Regards,
    me

    Look up Runtime.exec()

  • Running a Unix script from a Java class

    I am trying to use SCP (Secure copy) to copy an xml file from my J2EE application to a remote Unix server using a Unix script. How can I run the Unix script from my Java class? I could not find any resource for this on the internet. Can someone help me with this please.
    Thanks

    I am trying this below program ,but i am getting the error please help me
    import com.jcraft.jsch.*;
    import com.jcraft.jsch.Channel;
    import com.jcraft.jsch.JSch;
    //import com.jcraft.jsch.JSchException;
    import com.jcraft.jsch.Session;
    //import com.jcraft.jsch.UserInfo;
    import java.io.*;
    public class testrad {
    public static void main(String args[])
    String user="usertvr";
    String host="5.34.12.1";
    String cmd="ls -l";
    JSch jsch = new JSch();
    try{
    Session session=jsch.getSession(user,host,22);
    session.setPassword("$yhaj23");
    //UserInfo usrInfo=new MyUserInfo();
    //session.setUserInfo(usrInfo);
    session.connect();
    Channel channel=session.openChannel("exec");
    ((ChannelExec) channel).setCommand(cmd);
    channel.setXForwarding(true);
    channel.connect();
    //code
    channel.setInputStream(System.in);
    // channel.setOutputStream(System.out);
    //((ChannelExec) channel).setErrStream(System.err);
    InputStream in = channel.getInputStream();
    channel.connect();
    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())
    in.close();
    // System.out.println("JSCH: exit-status: " +
    //channel.getExitStatus());
    break;
    try
    Thread.sleep(1000);
    catch (Exception ee)
    channel.disconnect();
    session.disconnect();
    }catch(Exception e)
    {e.printStackTrace();
    System.out.println("Exception"+e);}
    /*public static class MyUserInfo implements UserInfo {
    public String getPassword()
    { return "password"; }
    public String getPassphrase()
    { return ""; }
    public boolean promptPassword(String arg0)
    { return true; }
    public boolean promptPassphrase(String arg0)
    { return true; }
    public boolean promptYesNo(String arg0)
    { return true; }
    public void showMessage(String arg0)
    Here is the error
    com.jcraft.jsch.JSchException: UnknownHostKey: 5.128.0.10. RSA key fingerprint is 02:a0:d6:c0:6f:69:2c:a9:a7:fa:7c:71:1c:60:ed:57
         at com.jcraft.jsch.Session.checkHost(Unknown Source)
         at com.jcraft.jsch.Session.connect(Unknown Source)
         at com.jcraft.jsch.Session.connect(Unknown Source)
         at testrad.main(testrad.java:23)
    Exceptioncom.jcraft.jsch.JSchException: UnknownHostKey: 5.128.0.10. RSA key fingerprint is 02:a0:d6:c0:6f:69:2c:a9:a7:fa:7c:71:1c:60:ed:57
    Can some one help me please.
    I running this program from Windows to connect to remote unix boxes.

  • Invoking unix shell scripts from java?

    Hi,
    could someone explain to me how one wuld invoke unix shell scripts from java.
    Also, could you invoke Visual Basic scripts from java.
    Finally, could you do this from an EJB?
    thanks for any help....
    sudu

    I just posted a snippet of this solution in the topic about widows commands chech it out it works just fine for unix shell scripts.
    --Ian                                                                                                                                                                                                                                                                                       

  • Calling Unix-Script from within Oracle and store stdout/stderr in table

    Hi,
    What I want to do is:
    1. Calling a UNIX script (e.g. hello.sh) (from inside the Database)
    hello.sh
    echo “Hello World!“
    2. and get the stdout/stderr output back in my Database in a table (e.g. temp_back)
    table temp_back
    ID     stdout          stderr
    1     Hello World!
    I think Number 1 isn’t a big problem, but how to get stdout back in DB?
    Any solution?
    I searched a bit in this Forum and found this Post.
    re:Calling Host Command Through Database  Procedures or Triggers
    This may be what I am searching for, but can’t access the Link
    Since I am not really fit with UNIX and packages/procedures in Oracle it would be nice if you could post a very detailed answer.
    (Please no java)
    -What packages do I need? (heard DBMS_OUTPUT would be useful)
    -example PL/SQL script
    Thanks a lot!
    Marcus
    Environment:
    Oracle 9.2.0 DB

    Marcus, if you opened the Java sandbox to access any o/s file, you can call any Unix command, shell script, or program, that the Oracle o/s user has exec privs on.
    Just remember that there's a very basic Unix environment when you make the call - the settings in the .profile does not apply. Thus PATH for example is not set. When making the call make sure that the complete path is given. As for the environment, that is a problem as you cannot set that and make the call at the same time.
    In that case it is much simpler to rather write a Unix shell script that does all for you. Set the environment. Run the command(s). Format output. Etc.
    Then you call that Unix script, via Java, from SQL or PL/SQL. Treat the Unix scripts like the Unix-version of stored procedures for your Oracle application.
    Some technical details. When you connect to Oracle, a Unix process services you. This can be either a dedicated server process (servicing only your Oracle session) or a shared server process (from the shared service pool of processes).
    In either case, it is a Unix process running as a background process (thus detached from any tty device). PL/SQL and SQL are executed by this process. The Oracle JVM created by your session also lives in this process. When you therefore make o/s calls, these calls are made by this process.
    Therefore you are limited to what this process can and can't do. E.g. it runs as the oracle o/s user and will fail on accessing paths and commands does the oracle user does not have privs on. Etc.

  • Calling UNix Script from portal Form

    Has anyone conquered this issue through jav or plsql. I need to call a unix script from the portal form when I select the insert button.

    I have several very convoluted ways which all work, but I have always thought there should be more straightfwd ways. Fundamentally the easiest way to call something from the Insert button is to add some PL/SQL code before (or after) the "doInsert();" call in the Insert Button event handler.
    What seems to be lacking is the ability to get from pl/sql to the o/s. So until we know how to do that you have to call a method in Java to execute o/s commands - specifically you can use Runtime.getRuntime().exec(cmd); where Runtime is a class in java.lang, and cmd is the actual o/s command (script or whatever).
    How to call this Java is then where you have several options:
    1. Compile this piece of Java into the Oracle DB as a SP.
    2. Deploy this piece of Java within a Java servlet on a 9iAS instance. Then have another SP call this servlet using the utl_http package (begin_request and other sp's within package).
    Which options would depend on several factors including your preference but most importantly whether you have a DB or a 9iAS instance on the machine where you want to execute the script. If you have neither you have a problem. In such cases I have used a standalone OC4J container which has a very small footprint.
    As I said these methods are all quite convoluted and if anyone else has anything better I would like to know (but they work quite reliably).
    Cheers.
    Anton.

  • 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                                                                                                                                                                                           

  • Invoking a bash shell script from Java code

    Hi All
    I am trying to invoke a Bash shell script using java code. The arguments required are "source wmGenPatch <source dir> <destination dir> no_reverse.
    in the code I have specified the arguments considering the cannonical paths of the files as the code may run on Unix or windows platform.
    I am getting a error while invoking Runtime.getRuntime().exec(args). The error is as follows :
    "The Error Occurred is: CreateProcess: source D:\Package4.0\workspace\DiffEngineScripts\v4a02\wmGenPatch D:\Package4.0\workspace\fromImageFilesDir\ D:\Package4.0\workspace\toImageFilesDir\ no_reverse error=2"
    It seems that error=2 indicates that the 'file not found' exception. But i can see the directories referred to in the error at place in the workspace.
    Kindly advice.
    Thanks in advance.

    Hi All
    I am pretty new to invoking bash shell scripts from java and not sure if i am progressing in right direction.
    The piece of code tried by me is as follows
    try {
                   currentDir = f.getCanonicalPath();
              } catch (IOException e) {
              if (currentDir.contains("/")) {
                   separator = "/";
              } else {
                   separator = "\\";
              String args[] = new String[7];
              args[0] = "/bin/sh";
              args[1] = "-c";
              args[2] = "source";
              args[3] = currentDir + separator + "DiffEngineScripts" + separator
                        + "v4a02" + separator + "wmGenPatch";
              args[4] = sourceFileAdd;
              args[5] = destFileAdd;
              if (isReverseDeltaRequired) {
                   args[6] = "reverse";
              } else {
                   args[6] = "no_reverse";
              try {
                   Process xyz = Runtime.getRuntime().exec(args);                              
                   InputStream result = xyz.getInputStream();
                   InputStreamReader isr = new InputStreamReader(result);
                   BufferedReader br = new BufferedReader(isr);
                   String line = null;
                   while ( (line = br.readLine()) != null)
                        System.out.println(line);
                   int exitVal = xyz.waitFor();
                   System.out.println("Leaving Testrun.java");
              } catch (Throwable t) {
                   t.printStackTrace();               
    and on running the same i am getting Java.io.IOException with the stack trace
    java.io.IOException: CreateProcess: \bin\sh -c source D:\Package4.0\workspace\DiffEngineScripts\v4a02\wmGenPatch D:\Package4.0\workspace\fromImageFilesDir\ D:\Package4.0\workspace\toImageFilesDir\ no_reverse error=3
    kindly advice
    Thanks in advance

Maybe you are looking for

  • FCP-- MOTION-- FCP WORKFLOW

    I've posted a variation of this question in the QT forum but I think that the MOTION experts might provide valuble input for this quandary. Here's what's happening (I've read the posts under long render times in the FCP forum but nobody has really sp

  • Wierd noise when Using the XP partition

    Hey guys, When I'm using the XP partition I would also plug in another monitor while working. I would get this weird sound (like a robot) followed by pauses or short freezes when in the middle of my work. It doesn't happen all the time but only when

  • Reloading of Dynamic Tiles

    I am new to Struts and Tiles framework in Struts. As the header and footer are same for all the JSP pages, will the header and footer tiles be reloaded each time a left navigatin link is clicked. Is there a method that we can have them load only once

  • OLE integration with Forms Server

    Can Forms 6 server running 3 tier, be used to call and integrate from an Oracle Form connecting to Microsoft Word or other local applications on a PC (+ local printing) ? We can do it 2 tier with OLE but need to migrate to 3 tier. How do we achieve t

  • HT3231 Need help using Migration Assistant

    Does migrating files and applications from one computer to another delete the files on the first computer?