Using Unix commands from Java Application

Hi,
I need to write an Java application such that could run Unix commands in a Unix box.
For example, my Java app needs to log in the Unix box, change directory (cd), create new folder (mkdir), list the current files in folder (ls), mount a new device (mount), etc.
Thank you very much.
Hung

you can use java.lang.Runtime.exec to invoke OS commands, but if you're going to be completing a sequence that complicated and need to manage error handleing well, it might be best to just invoke a native method or write a shell script that does all of that stuff and then invoke that script via Runtime.exec . The Runtime class has limitations when you start invoking processes that require user input (like 'su'). Search the forums for more extensive examples on how to use Runtime.

Similar Messages

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

  • Call an interactive UNIX command from java

    Hi,
    I want to call a UNIX command from java. When issue the command 'htpasswd -c filename username' on UNIX terminal, it asks for the new password and the then confirmation password again (yeah, unfortunately the htpasswd installed on our system does not allow you proivde the password on the command line. So have to work interactively ). Now, I have written a simple java program RunCommand.java. I am hardcoding the password for the htpasswd command in the file (in the real situation, password will be generated dynamically). I want to issue 'java RunCommand' on the UNIX command line and get back the command prompt without being asked for the password twice. The code is below, but the Outputstream does not work as expected. It always asks for inputs. Any idea? Many thanks.
    import java.io.*;
    public class RunCommand {
    public static void main(String args[]) throws Exception {
    String s = null;
    try {
    String cmd = "htpasswd -c filename username ";
    // run a Unix command
    Process p = Runtime.getRuntime().exec(cmd);
    BufferedReader stdInput = new BufferedReader(new InputStreamReader(p.getInputStream()));
    BufferedReader stdError = new BufferedReader(new InputStreamReader(p.getErrorStream()));
    OutputStream stdOut = p.getOutputStream();
    String pswd = "mypassword";
    while ((s = stdInput.readLine()) != null) {
         s = stdInput.readLine();
         stdOut.write(pswd.getBytes());          
         stdOut.flush();
    System.out.println("Here is the standard error of the command (if any):\n");
    while ((s = stdError.readLine()) != null) {
    System.out.println(s);
    stdOut.close();
    stdInput.close();
    stdError.close();
    System.exit(0);
    catch (IOException e) {
    System.out.println("exceptions caught: ");
    e.printStackTrace();
    System.exit(-1);

    There are only about 9 billion responses a day on how to do this. Use the search feature.

  • Can I execute MySql's command from java application?

    Can I execute MySql's command from java application? And how?
    For example :
    load data local infile 'D:\\myData.txt'
    into table myTable
    fields terminated by ';'
    lines terminated by '\n';

    1. get the jdbc driver for mysql from the mysql site at: http://dev.mysql.com/downloads/connector/j/5.0.html
    2. follow the installation instructiions... which you'll also find in your mysql manual...
    Happy travels. Keith.

  • Running Unix Command from WEB-APPLICATION

    Hi all,
    I want to run unix command from a java-based web application. the basic code part is this ---
    public class RunCommand
          public String runIt()
              String s = null, returnString = "";
              Process p=null;
              try
                       Runtime rt = Runtime.getRuntime();
                  p = rt.exec("sh testPOC.ksh");
                  p.waitFor();
                  BufferedReader stdInput = new BufferedReader(new
                       InputStreamReader(p.getInputStream()));
                  BufferedReader stdError = new BufferedReader(new
                       InputStreamReader(p.getErrorStream()));
                  // read the output from the command
                  returnString += "Here is the standard output of the command:<br>";
                  while ((s = stdInput.readLine()) != null) {
                      returnString += s;
                  // read any errors from the attempted command
                  returnString += "Here is the standard error of the command (if any): <br>";
                  while ((s = stdError.readLine()) != null) {
                      returnString += s;
              catch (IOException e)
                  returnString += "exception happened - here's what I know: ";
                  returnString += "error-> " + e.getMessage();
              catch(Exception e)
                returnString += "exception happened - here's what I know: ";
                  returnString += "error-> " + e.getMessage();
              return returnString;
      }this class is kept as an inner class. The control comes to its outer class, from servlet, from which the runit() is called. but the exception is occuring at line of p=rt.exec(.....). it tells "<command name> : not found transaction completed" [got this using getMessage() method].
    i am unable to show(and see, too) the stacktrace, because i don't have access to that test environment and its log. i can't run this in local because its windows one.
    now can anyone tell me, where is the problem. is there any limitation in web application server/container? this was successful when i used command prompt writing a .java file. Please help me. Thanks in advance...

    Friends, i've got, where the problem is.
    when we run a class file directly from a command prompt, we get an environment with that shell window. but for a servlet application running these kind of commands from a class creates kind of child processes. each and every command is executed as a child process of jvm and don't get those environment. we have 'PATH' variable in the environment. when a command (say, 'dir' or 'sh' or 'ls', etc.) is executed, the shell first search for that executable file (i.e. dir / sh / ls) in the given paths in the variable 'PATH'. this is not available for the child commands of jvm. hence the basic commands are searched in the current directory of the jvm and they are failed.
    i solved the problem giving full path of the commands. like :
    p = rt.exec("/bin/sh runningScript.ksh")

  • Issueing unix command from java

    I am using FTPConnection.java by Bret Taylor, for uploading files to remote linux portal. But i cannot issue any unix command from it . please anyone help me in this case?

    Read this:
    http://www.javaworld.com/javaworld/jw-12-2000/jw-1229-traps.html
    It'll explain it all. - MOD

  • How to execute any cmd command from java application?

    Hi all,
    How to execute or call any command of cmd from java application??
    Is there any method to do so??
    Or, is it possible to do it using Runtime.exec() ??? And if so, how to use it, please explain with ab example...
    I'll highly appreciate....
    Thank you.

    If google would be the best option, then I would not be on Sun's forums and I would not have asked experts like you, sir !! :-)
    Neway, I got the solution from PhHein !!
    Good link indeed..
    Cheers..

  • Execute DOS command from java application

    Hello,
    I want to execute a DOS command (MOVE, in order to move an image from a folder to an other) from a java application. How can I do this?
    Francesco

    Yes I have tested it and it is working but only when executing a bacth file. For instance:
    Runtime rt = Runtime.getRuntime();
    try{
         Process proc = rt.exec("move.bat");
    }catch(Exception ex){
         ex.printStackTrace();
    }and the command in move.bat is:
    move c:\\temp\\*.gif C:\\temp2
    You don't have to use double slashes in batch files, only in Java. But anyway it is working both ways.
    It is not working when you try to execute the command without the batch file:
    Process proc = rt.exec("move c:\\temp\\*.gif C:\\temp2"); -> this will not work.
    It should work. Try to execute another command to see what happens.

  • How can I use unix commands from oracle report

    I have to use the following command from oracle reports.
    In oracle forms we can use the HOST command but what about oracle reports2.5.
    I have to email the attached file 100245.pdf from oracle reports to the given email id
    uuencode 100245.pdf 100245.pdf | mailx -s "test" [email protected]

    Hi,
    It's because .bat (or .cmd) files are scripts and not executables and are interpreted using the command line executable - which is normally cmd.exe (although you can buy others).
    So you need to call cmd.exe passing the bat file name as a parameter, something like
    cmd.exe /c batchfilename
    Without the /c you will never get a response.
    However, this brings us to the bizarre conclusion that you are going to:
    call cmd.exe (a shell interpreter)
    to launch a batch file
    that calls cygwin (another shell interpreter)
    which then runs ls
    When shouldn't that just be:
    call cmd.exe to run the dir command
    Or better yet, If you are just after a file name listing and you seem to understand Java stored procs, why not just write a JSP to list the contents of a directory? No problems with OS dependant commands, scripts and 3rd party interpreters. Plenty of examples of that out on the internet as well.
    HTH
    Chris

  • 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();
    }

  • Error using DOS Command from Java

    Hi,
    I am using the following code to execute the DOS command to delete a file from Java.
    cmd = "del " + fileName;
    Runtime run = Runtime.getRuntime();
    Process proc = run.exec(cmd);
    Getting the following exception during runt time.
    Exception = java.io.IOException: CreateProcess: del D:\LAWDOCS\P50074\12\3\36857.3  error=2 --
    Can some body throw light on this?.
    Thanks,
    Jeyaraman R

    "del" is not an actual executable file, but instead a command in the command interpreter. So you can't just execute del like that, you have to run the command interpreter and tell it to execute the del command.
    If you are on windows NT, 2000 or XP, replace your command with "cmd /C del " + filename.
    If you are on Windows 95, 98 or ME, use "command /C del " + filename. (I am not quite sure if the switch for this is called /C on old windows version.)
    (But why not use File.delete()?)

  • Running a db2 command from Java Application ??

    Hi All,
    I have to write an application in JDBC that can retrieve a list of databases on a db2 server, the only way I know is the db2 command "list database directory", but I can not use it in a JAVA program, is there a solution for this?
    Can anyone help me in this regard ?
    Thanks in Advance.

    If your driver implement it you can list databases with DatabaseMetaData
    Connection conn = ...
    DatabaseMetaData meta = conn.getMetaData();
    ResultSet rs = meta.getCatalogs();
    while (rs.next())
        System.out.println(rs.getString("TABLE_CAT"));
    }

  • Calling a Unix Command from Java

    Hi all,
    I'm not a Java guy, I need a small help, I need a code which will call a Unix Command called from a Java code. For Example I need a Java code whereby I should be able to do a 'ls -lt' on my Unix box. Can anybody please help.
    Thanks,
    Shantanu

    See Runtime.exec()

  • CMD commands from Java applications

    I have been searching around and trying to see if it is possible to open a DOS window (via cmd) and run a command (ie: ping, tracert) from a Java GUI. I not found anything as of yet. I am familiar with Runtime.exec(); but it does not seem to like cmd. I can launch other applications, but it does not seem to launch a command window at all, and if I add any other arguements it will give me an IO error.
    Anyone have any ideas?

    Read this:
    http://www.javaworld.com/javaworld/jw-12-2000/jw-1229-traps.html
    It'll tell you how to use Runtime.exec() properly. MOD

  • Running UNIX command from Java

    import java.lang.* ;
    import java.io.*   ;
    public class TestRunTime
        public static void main(String args[])
            int rc = -1 ;
            String yard = "psnsy" ;
            String ifwList = "[email protected],[email protected]" ;
            String cmd = "/usr/bin/mailx -r oracle -s \"PMC - Missing Interface Files from " + yard +
                               "\" " + ifwList + " < /interface/nwps/missingfiles.txt" ;
            rc = RunThis(cmd) ;
            System.out.println(rc) ;
        private static int RunThis(String str)
             Runtime rt = Runtime.getRuntime();
             int        rc = -1;
             try
                Process p = rt.exec(str);
                p.waitFor() ;
                BufferedReader buf = new BufferedReader(new InputStreamReader(p.getInputStream()));
                String line = "";
                while ((line = buf.readLine()) != null)
                   System.out.println(line) ;
                rc = 0 ;
                return rc ;
             catch ( Throwable t  )
                  t.printStackTrace();
                  rc = -1 ;
                  throw new RuntimeException() ;
    }When I run java TestRunTime
    all it does is hangs and never completes.
    I can run the string cmd from the UNIX shell and it runs as expected - I receive an email.

    jschell wrote:
    sabre150 wrote:
    Whether the detail is as you say or as I say does not remove the need to process the exec()ed processes stdout and stderr each in their own thread. Since the OP is not writing to stdin he can handle one of stdout or stderr in the Thread that invokes the exec() but the other needs a separate thread.If the streams are stripped from the process then...
    1. They should not be stripped until they are in their own thread.
    2. Each requires their own thread.
    But since the OP isn't stripping either, no other threads are needed. Nor does the OP need to strip them.I have to disagree. The following code is based on the traps article and sends output to stdout and to stderr from the 'sh' program. Run as is it deadlocks. Run by changing the 'false' to 'true' in the 'if' statement it does not deadlock.
    If one changes the code to process only stdout or stderr but not both then it deadlocks.
    Running the same code on Windows XP and Windows 2000 but using 'cmd.exe' instead of 'sh' and using 'dir' instead of 'ls' produces the same result.
    Running similar code that just runs a perl script without any stdin but that writes to both stdout and stderr it deadlocks if one does not process both stdout and stderr in separate threads.
    If one processes the Process stdout and stderr streams then one does not get a deadlock.
    This is entirely consistent with what the 'traps' article says and I hope consistent with what I have written in this thread.
    import java.io.BufferedReader;
    import java.io.IOException;
    import java.io.InputStream;
    import java.io.InputStreamReader;
    import java.io.OutputStreamWriter;
    import java.io.Writer;
    class StreamGobbler extends Thread
        private int count = 0;
        private final InputStream is;
        private final String type;
        StreamGobbler(InputStream is, String type)
            this.is = is;
            this.type = type;
        public void run()
            try
                final InputStreamReader isr = new InputStreamReader(is);
                final BufferedReader br = new BufferedReader(isr);
                String line = null;
                while ((line = br.readLine()) != null)
                    System.out.println(++count + "\t " + type + "> " + line);
            } catch (IOException ioe)
                ioe.printStackTrace();
    public class Sabre20091015_2
        public static void main(String args[]) throws Exception
            final Process proc = Runtime.getRuntime().exec("sh");
            if (false)
                new StreamGobbler(proc.getErrorStream(), "ERROR").start();
                new StreamGobbler(proc.getInputStream(), "OUTPUT").start();
            final Writer writer = new OutputStreamWriter(proc.getOutputStream());
            for (int commandIndex = 0; commandIndex < 20000; commandIndex++)
                writer.write("echo Index " + commandIndex + "\n");
                writer.write("ls\n");
                writer.flush();
                writer.write("fnaskfdkdhflakjfljd\n");
                writer.flush();
            writer.close();
            final int exitValue = proc.waitFor();
            System.out.println("Exit value = " + exitValue);
    }

Maybe you are looking for

  • New FiOS Internet Customer Lied to By Sales Rep - EXTREMELY UNHAPPY

    I had FIOS Internet installed in my new apt about a month ago. Before moving, I conducted my due diligence among the providers in my area. In order to sell me on the product, I had a couple chats with Sales Reps, which was documented on some type of

  • The App store is not letting me use my gift card to purchase any apps...ideas?

    It is a $100 gift card and has already been redeemed and purchases have been made previously. There is a remaining balance on the card. When i sign into the app store, there used to be a balance that appeared beside the "account" tab, but now it is g

  • Multiple ALV GRID reports on a single page

    hi all I have an  urgent requirement where I need to show 2-3 alv grids on a single page. Please let me know if it is possible to do so. If yes how. Sample code would be very helpful. thanks in advance. <REMOVED BY MODERATOR> Edited by: Alvaro Tejada

  • FRM-92220: access to system clipboard is denied

    Hi, Within a customer's application Error FRM-92220 "access to system clipboard is denied" is returned when the customer switches between screens within the application. I have not been able to find a reference for this error nor am I experienced wit

  • Process order CLOSE:Message no. BS013

    Hi Gurus, I am trying to CLOSE some Process orders which are TECO status,(All are TECO status, and Settled) but when I execute those it gives error messages, and the Log says, System status CRTD is active (ACT 112033 0011 ) Message no. BS013 Diagnosi