Running system command

I am new to JAVA Programming and I need help in coding. I need to run a system command using Java code. For example running a unix command like "service httpd status" and display it's result. Can anyone help?

Have a look at Runtime.exec()
http://java.sun.com/j2se/1.4/docs/api/java/lang/Runtime.html

Similar Messages

  • Urgent!! running system command in java

    i am trying to run system command(windows) in java. I am getting
    exception as java.io.IOException: CreateProcess: c:\dir
    Please Help.
    Here is the code
    import java.io.*;
    public class RunCommand {
    public static void main(String[] args) {
    try
    //run dir command
    Process p = Runtime.getRuntime().exec("c:\\dir");
    BufferedReader stdInput=new BufferedReader(new
    InputStreamReader(p.getInputStream()));
    BufferedReader stdError =new BufferedReader(new
    InputStreamReader(p.getErrorStream()));
    //read the output
    System.out.println("here is the output:\n");
    while((s=stdInput.readLine())!=null){
    System.out.println(s);
    System.out.println("here is the error if any");
    while((s=stdError.readLine())!=null){
    System.out.println(s);
    System.exit(0);
    }//end try
    catch (IOException e)
    System.out.println("exception Happened" );
    e.printStackTrace();
    System.exit(-1);

    It works fine if you replaceProcess p = Runtime.getRuntime().exec("c:\\dir");withProcess p = Runtime.getRuntime().exec("cmd /c dir");And don't forget to define your s variable.

  • How to run system command

    Hi
    Is that possible to run system command in indesign javascript?
    Becase i need to run a command in run prompt while script running in .indd file.
    Any idea please let me know

    Hi Maciej,
    For time being i m already using the execute() only for generating pdf from ps.
    In this case i cant able set job option in distiller.
    The problem y i m trying to run system command is i need pass some parameters (ie., job option, mypsFile) through my script.
    Is there any other sollutions?
    Thank and Regards
    Christy

  • Running System Commands using Java

    HI,
    I am developing an application using java which requires some system commands to be run.For example i have to write a java function which can program the windows scheduler to run a particular executable at some time & another one to initiate an ftp.I however do not know how to execute the corresponding commands from java.Is there any way or some specific api(similar to the system command in c) that i can use to perform these operations.I am using j2sdk 1.4.0_01 on a win 98 machine to develop the application.

    See [url http://java.sun.com/j2se/1.4.2/docs/api/java/lang/Runtime.html]java.lang.Runtime

  • Please help how to run System commands and batch files thru java program

    Sir,
    I want execute OS commands like dir,cls..etc and batch files,.exe filesthru java program.
    I have tried it sofar thru Runtime.getRuntime().exec("execute.bat");
    but it is not working.anybody knows about how to run the system commands thru java please give me the code.
    thank you,
    regards,
    j.mouli

    I've seen other posts with this questions, and answers. Unfortunately I didn't pay much attention. But the basic idea is to exec command.com and pass the specifc batch or command as an argument.

  • Running System commands using Runtime.exec()

    I'm trying to run an example from "The Java Programming Language" book by Arnold, Gosling and Holmes. I'm trying to run a system level command and get the results. The code looks like:
    public static String[] runCommand(String cmd) {
    String[] outputData= null;
    String[] cmdArray = {"/usr/bin/ls", "-l", "/tmp"};
    try {
    Process child = Runtime.getRuntime().exec(cmdArray);
    InputStream in = child.getInputStream();
    InputStreamReader reader = new InputStreamReader(output);
    BufferedReader = new BufferedReader(reader);
    // read the commands output
    int counter = 0;
    String line;
    while ((line = input.readLine()) != null)
    outputData[counter++]= line;
    if (child.waitFor() != 0){  // error when it's not 0       
    System.out.println("Couldn't run the command.");
    System.out.println("It produced the following error message : " + child.exitValue());
    outputData = null;
    } catch (Exception e){
    System.out.println("It got here!");
    System.out.println("It produced the following error message : " + e.getMessage());
    outputData = null;
    return outputData;
    It gets to the while line, trys to run the input.readLine() and kicks out the exception that looks like:
    It got here!
    It produced the following error message : null
    I know it gets to the input.readLine() because I had a whole lot more try blocks in there, but for simplicity left it out (so it look like the code in the book, which I tried originally). When I run the same command from the command line (on our Sun Solaris 2.8 system) I get results back. I'm not sure what I'm doing wrong. Any help would be greatly appreciated. Thanks.

    Hi, duffymo, hope you can help me. Consider this servlet code:
    String theCommand = "csh /export/home/gls03/sasstuff/runsas.csh /export/home/g
    ls03/sasstuff/gary2.sas";
    //Create a parent Process for the sas program subprocess:
    Process p = rt.exec(theCommand);
    System.out.println("after call to rt.exec(theCommand)");
    Here is the runsas.csh script:
    #!/bin/csh
    setenv LD_LIBRARY_PATH /opt/sybase/lib:/usr/lib:/usr/openwin/lib:/opt/SUNWspro/S
    C2.0.1
    setenv SASROOT /usr/local/CDC/SAS_8.2
    setenv XKEYSYMDB /usr/local/CDC/SAS_8.2/X11/resource_files/XKeysymDB
    $SASROOT/sas -sasuser /hpnpages/cgi-bin/applinks/hospcap/tmp $1
    The execution never gets to the println statment, here is the error:
    class java.io.IOException Exception. Message: CreateProcess: csh /export/home/g
    ls03/sasstuff/runsas.csh /export/home/gls03/sasstuff/gary2.sas error=2
    java.io.IOException: CreateProcess: csh /export/home/gls03/sasstuff/runsas.csh /
    export/home/gls03/sasstuff/gary2.sas error=2
    at java.lang.Win32Process.create(Native Method)
    at java.lang.Win32Process.<init>(Win32Process.java:66)
    at java.lang.Runtime.execInternal(Native Method)
    at java.lang.Runtime.exec(Runtime.java:551)
    at java.lang.Runtime.exec(Runtime.java:477)
    at java.lang.Runtime.exec(Runtime.java:443)
    at sasRunnerNew.doPost(sasRunnerNew.java:103)
    at javax.servlet.http.HttpServlet.service(HttpServlet.java:760)
    at javax.servlet.http.HttpServlet.service(HttpServlet.java:853)
    at weblogic.servlet.internal.ServletStubImpl.invokeServlet(ServletStubIm
    pl.java:262)
    at weblogic.servlet.internal.TailFilter.doFilter(TailFilter.java:21)
    at weblogic.servlet.internal.FilterChainImpl.doFilter(FilterChainImpl.ja
    va:27)
    at us.ny.state.health.hin.hinutil.HinFilter.doFilter(HinFilter.java:124)
    at weblogic.servlet.internal.FilterChainImpl.doFilter(FilterChainImpl.ja
    va:27)
    at weblogic.servlet.internal.WebAppServletContext.invokeServlet(WebAppSe
    rvletContext.java:2643)
    at weblogic.servlet.internal.ServletRequestImpl.execute(ServletRequestIm
    pl.java:2359)
    at weblogic.kernel.ExecuteThread.execute(ExecuteThread.java:139)
    at weblogic.kernel.ExecuteThread.run(ExecuteThread.java:120)
    The command runs fine in unix.
    I've also tried using these as arguments to exec:
    String theCommand = "/bin/csh /export/home/gls03/sasstuff/runsas.csh /export/home/gls03/sasstuff/gary2.sas";
    String[] theCommand = {"csh", "/export/home/gls03/sasstuff/runsas.csh", "/export/home/gls03/sasstuff/gary2.sas"};
    These generate the same error. I'm thinking this is a sas-specific problem.
    Thanks for any help. Gary

  • How to run system commands from JAVA

    Hi Friends,
    How to run windows system commands from JAVA
    Runtime r=Runtime.getRuntime();
    r.exec("dir");
    Throwing following Exception
    CreateProcess :dir error=2
    Thanks in advance
    Hamsa

    Hi ,
    in Windows NT this is not possible, you can use the following :
    Runtime r=Runtime.getRuntime();
    StringBuffer sbuf = new StringBuffer();
    String dir = new String();
    java.lang.Process proc = r.exec("cmd /c dir");
    InputStream is = proc.getInputStream();
    int ch ;
    while((ch=is.read() ) != -1)
    sbuf.append((char)ch);
    is.close();
    dir = sbuf.toString();
    System.out.println(dir );

  • Running system command in java

    hi, i am new to this forum.but i think that definately some body is going to help me.
    my problem is like this.
    i have written a java code like this...
    import java.lang.*;
    import java.io.*;
    * @author administrator
    public class dos {
    public static void main(String args[])
    //String command ="PATH";
    try{
    Runtime rt=Runtime.getRuntime();
    Process p=rt.exec("cmd /c dir");
    }catch (Exception e){
    System.out.println(e);
    can anybody help me out to silve this problem..
    naushad alam
    [email protected]

    to make sure the process doesn't block on error, u need to read both the output and error streams
    import java.io.*;
    public class LaunchProcess
         public static void main(String [] arg) throws Exception
              class Threader implements Runnable
                   BufferedReader br;
                   String ss;
                   Threader(InputStream is, String s)
                        ss=s;
                        br = new BufferedReader(new InputStreamReader(is));
                   public void run()
                        try{
                        String line;
                        while((line=br.readLine())!=null)
                             System.out.println(ss+"\t"+line);
                   }catch(Exception e){e.printStackTrace();}
              long start = System.currentTimeMillis();
              Process p = Runtime.getRuntime().exec(arg);
              Thread out = new Thread(new Threader(p.getInputStream(),"o"));
              Thread err = new Thread(new Threader(p.getErrorStream(),"e"));
              System.out.println("Process says");
              out.start();
              err.start();
              p.waitFor();
              System.out.println("Took "+(System.currentTimeMillis()-start));
    }

  • Problem in running system commands using Runtime()

    hi,
    i am trying to run the "dir" command in windows OS using Runtime(). But while
    executing the program i am getting
    java.io.IOException: CreateProcess: dir error=2 error. But if i replace the "dir" command by "notepad" command its working fine. below is the source code.
    class testing
    public static void main(String args[])
         try{
    Runtime rt=Runtime.getRuntime();
    Process p=rt.exec("dir"); //Generating Errors
    //Process p=rt.exec("notepad"); //Working Fine
         }catch(Exception e){System.out.println(e);}
    }plzz help me out.
    thanx

    thats fine its working. i made two changes. First i used an array to send the
    arguments. if we directly use "cmd.exe /c dir" then its converting "/C" to "\C" thus
    producing the error. so i used
    Runtime rt=Runtime.getRuntime();
    String args1[]={"cmd.exe","/C","dir"};
    Process p=rt.exec(args1);But then i got no error no output. From other forums i came to know about capturing the data using input streams and i included the following code.
    BufferedReader Resultset = new BufferedReader
         (new InputStreamReader(p.getInputStream()));
    String line;
    while ((line = Resultset.readLine()) != null)
         {          System.out.println(line);          }Now its working fine. Thanx for ur help.

  • VB ID3 How to run system command?

    I'm looking for help of some mighty VBS guru.
    I'd like to have my script run the following command:
    php D:\Desktop\01.php
    and return whatever it prints as a string.
    I realise this may seem little off topic in this forum, so here's
    the InDesign background:
    In mac version of my script I'm executing a shell command from javascript by 'app.doScript'
    this runs a line of AppleScript which executes the shell command. Then the outcome
    of it travels the same way to javascript and lets InDesign to process it.
    Something of this sort:
    shScript = "./ ~/Desktop/01.php";
    asScript = "do shell script \"" + shScript + "\"";
    myResult = app.doScript (asScript, 1095978087);
    It's probably not a clever way of running mySQL query and retrieving the results
    but I couldnt think of anything better.
    Now I need to do the same on Windows. This is rather difficult for me, because
    I know very little about VBS. All google searches on the subject led to some
    kind of Windows Scripting Host solution which doesn't seem to be supported by
    InDesign VBS interpreter.
    Can you help me please?
    Thanks
    Weller

    The following snippet is from a larger script. I hope I got the quoting straight, no PC running here to verify.
    app.doScript(
    "CreateObject(\"WScript.Shell\").Run \"echo yo!\"",
    ScriptLanguage.visualBasic);
    Dirk

  • System command from within PL/SQL on server ?

    Hi
    I know its a bit weird thought of executing an NT system command from within PL/SQL on server (UNIX).
    Has anyone done something (silly me!) like it or knows any work-around to try something like it?
    Thanks in advance.
    Regards
    Pravesh

    Can you be more specific?
    Generally to run system commands you utilize DBMS_PIPE to communicate with a listener on the platform that you're accessing. That listener picks up the pipe request and might either:
    1. spawn a process to run the command
    2. fork a process to run the command
    3. run the command within its own application.
    It sounds complex, but if review the DBMS_PIPE documentation and it's not too difficult -- presuming you know a language like C.
    I believe there are other features in 8.1.5 and higher versions that enable you to run stored programs or COM objects...
    Bill

  • System command execution from stored procedure

    Hello World,
    How to run System command from stored procedure ?
    For example :
    Delete a file
    running a programm,
    Is it possible ?
    H.M

    Years ago I did this by writing an output file with commands into a directory and had a cron job looking for this file. At the end of the run the file was removed.
    Never checked if there are other possibilities nowadays.
    cu
    Andreas

  • Permission problems when trying to execute simple system command

    Hi, I am quite new to JSP so please forgive me if I ask really simple things... I am trying to run system commands on the server and display the output on a webpage. This is what I've got:
    <%@ page import="java.io.*" %>
    <HTML>
    <BODY>
    <%
        Runtime rt = Runtime.getRuntime();
    Process p = rt.exec("/bin/ls");
    // for reading the output of the program
    // (out of the program is in for us)
    BufferedReader sOut = new BufferedReader(new
            InputStreamReader(p.getInputStream()));
    // read the output
    String line;
    while ((line = sOut.readLine()) != null)
            out.println("line<BR/>");
    %>
    </BODY>
    </HTML>However, when I run this, I get the following:
    description The server encountered an internal error () that prevented it from fulfilling this request.
    exception
    org.apache.jasper.JasperException: Exception in JSP: /research/test.jsp:7
    4: <%
    5: Runtime rt = Runtime.getRuntime();
    6:
    7: Process p = rt.exec("/bin/ls");
    8:
    9: // for reading the output of the program
    10: // (out of the program is in for us)
    Stacktrace:
    org.apache.jasper.servlet.JspServletWrapper.handleJspException(JspServletWrapper.java:451)
    org.apache.jasper.servlet.JspServletWrapper.service(JspServletWrapper.java:373)
    org.apache.jasper.servlet.JspServlet.serviceJspFile(JspServlet.java:329)
    org.apache.jasper.servlet.JspServlet.service(JspServlet.java:265)
    javax.servlet.http.HttpServlet.service(HttpServlet.java:802)
    sun.reflect.GeneratedMethodAccessor63.invoke(Unknown Source)
    sun.reflect.DelegatingMethodAccessorImpl.invoke(DelegatingMethodAccessorImpl.java:25)
    java.lang.reflect.Method.invoke(Method.java:597)
    org.apache.catalina.security.SecurityUtil$1.run(SecurityUtil.java:244)
    java.security.AccessController.doPrivileged(Native Method)
    javax.security.auth.Subject.doAsPrivileged(Subject.java:517)
    org.apache.catalina.security.SecurityUtil.execute(SecurityUtil.java:276)
    org.apache.catalina.security.SecurityUtil.doAsPrivilege(SecurityUtil.java:162)
    root cause
    java.security.AccessControlException: access denied (java.io.FilePermission /bin/ls execute)
    java.security.AccessControlContext.checkPermission(AccessControlContext.java:323)
    java.security.AccessController.checkPermission(AccessController.java:546)
    java.lang.SecurityManager.checkPermission(SecurityManager.java:532)
    java.lang.SecurityManager.checkExec(SecurityManager.java:779)
    java.lang.ProcessBuilder.start(ProcessBuilder.java:447)
    java.lang.Runtime.exec(Runtime.java:593)
    java.lang.Runtime.exec(Runtime.java:431)
    java.lang.Runtime.exec(Runtime.java:328)
    org.apache.jsp.research.test_jsp._jspService(test_jsp.java:49)
    org.apache.jasper.runtime.HttpJspBase.service(HttpJspBase.java:98)
    javax.servlet.http.HttpServlet.service(HttpServlet.java:802)
    org.apache.jasper.servlet.JspServletWrapper.service(JspServletWrapper.java:331)
    org.apache.jasper.servlet.JspServlet.serviceJspFile(JspServlet.java:329)
    org.apache.jasper.servlet.JspServlet.service(JspServlet.java:265)
    javax.servlet.http.HttpServlet.service(HttpServlet.java:802)
    sun.reflect.GeneratedMethodAccessor63.invoke(Unknown Source)
    sun.reflect.DelegatingMethodAccessorImpl.invoke(DelegatingMethodAccessorImpl.java:25)
    java.lang.reflect.Method.invoke(Method.java:597)
    org.apache.catalina.security.SecurityUtil$1.run(SecurityUtil.java:244)
    java.security.AccessController.doPrivileged(Native Method)
    javax.security.auth.Subject.doAsPrivileged(Subject.java:517)
    org.apache.catalina.security.SecurityUtil.execute(SecurityUtil.java:276)
    org.apache.catalina.security.SecurityUtil.doAsPrivilege(SecurityUtil.java:162)
    Seems like it has something to do with the permissions granted to the JVM? I have googled high and low and still haven't found a way to solve it. I've also tried adding grant { permission java.io.FilePermission "file:/bin/ls", "execute"; } to my java.policy file but to no avail. Could somebody point out how to solve this? Thanks!

    I would think it is an OS permission thing rather than java permission
    What user is apache running as on this system?
    Does the user apache is running as have permissions to run these commands, in the directory where you are running them? Try executing them yourself when logged in as that user.
    I would also recommend you read the article [when runtime.exec() won't|http://www.javaworld.com/javaworld/jw-12-2000/jw-1229-traps.html].
    Cheers,
    evnafets

  • How to Run Operating System Command Before/After Message Processing SAP PI

    Hi,
    We are trying to execute multiple commands via "Operating System Command Before/After Message Processing".
    When we use single command say for example cp or mv (copy or move) the commands get executed fine.
    eg: cp %F /var/opt/data/outbound/Test/Dummy.txt 
    /this works fine/
    when we club commands together or try to redirect the outputs of commands, none of the commands get executed.
    eg:
    cp %F /var/opt/data/outbound/Test/Dummy.txt ; rm %F
    or
    wc -l %F > /var/opt/data/outbound/Test/Dummy.txt
    Is it possible to execute multiple commands or redirect the output  of commands without using a shell script? The PI server we are working on iis hosted on UNIX environment.

    Hi Harleen,
    try like this
    cp %F /var/opt/data/outbound/Test/Dummy.txt ; rm %F
    instead of semicolon try this
    (1) &
    command1 & command2
    Execute Command1 and then execute Command2
    (2) &&
    command1 && command2
    Runs the command2 only when command1 doesn't Complete successfully
    (3) ||
    command1 || command2
    Runs the second command if the first command had an error
    (4) ()
    (command1 || command2) || (command3 & command4)
    Defines the order in which commands are to be executed
    Regards
    Suraj

  • Is there a way to run dos commands on onther system?

    Hi I have connected to a port of another system where windows is the operating system. So can I run dos commands on the other system through that network connection from my computer?

    I'm not sure what you mean by "connected to a port of another system" . Which port using what software to which server?

Maybe you are looking for

  • Can i buy items from the American ITunes store?

    I live in Australia and would like to buy an item from the American ITunes store. Is this possible without needing an account for that country?

  • What is the point of interfaces??? Confused!!!!

    I have obviously missed something big out because I know that interfaces are very important but I don't get the point of them. I underdstand an interface as a class which declared methods but does not implement them i.e.: public void hello(int num);.

  • Order of execution and variable access

    Hello frnds, This prog shows the order of its execution: public class Sequence { int j=10; public Sequence() { System.out.println(" constructor initializer : "+i); // line x System.out.println(" instance initializer :"+this.i); static System.out.prin

  • Big ANE causes java.lang.OutOfMemoryError when packaging Air application

    Hi, I'm working on an Air mobile game that uses ANE on iOS and Android. I'm in the process of creating a new ANE and face a problem on the Android side. My ANE requires an external framework (Burstly, http://burstly.com). If I just link the Android p

  • Updated Statement of Direction now available...

    Hello, Please read the updated SOD for new information on Oracle Workflow including Oracle Workflow for Java(OW4J) posted on the workflow web site. http://www.oracle.com/technology/products/ias/workflow/index.html Cheers, Raja