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()

Similar Messages

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

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

  • Calling an unix command from a java program which runs on windows

    Hello All
    I have an Java Application which is run on windows server (I)
    I have another Sun Server (II)
    I want to call an unix command on server(II) from java application which is on server(I)
    I am using Samba Server in order to share files between Windows Server and Unix Server
    Can I use samba in order to call command
    or is there any way to open an telnet session within java application
    I will be grateful if you give me some suggestion on this issue
    Regards
    BEKIR BALCIK
    J2EE Application Developer
    Argela Technologies ...

    cross post
    http://forum.java.sun.com/thread.jspa?threadID=624601&messageID=3553626#3553626

  • 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

  • Calling OAM WLST Commands from java class

    Hi all,
    is there any idea how to call OAM related WLST commands from java class ?.
    what are the required jar files ?
    thanks

    Hi,
    As per my understanding in OAM you will have only two major .py file startscript.py and stopscript.py file which will start nodemanger connect and start Admin and managed server similarly in stop it will stop managed server Admin server and then last nodemanager.
    these all done through wlst command using nmConnect(), nmStart (), nmKill() and shutdown etc.
    What exactly you are looking to get from java code.
    Regards,
    kal

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

  • Cannot call the execute command from java code

    Hello,
    I like to add a new user via a java web service.
    Establishing a connection to the OC4J MBean server is no problem. I also can execute the commands 'listAllCommands' and 'help' on the MBean. But if i try to call the execute command, i always get an NoSuchMethodException. Looking at the MBeanInfos 'execute' is listed there as an operation.
    Can anyone explain this to me?

    Hi,
    I basically used the code described at http://download.oracle.com/docs/cd/B32110_01/web.1013/b28952/mbeans.htm#CIHFDJBJ to connect to the MBeanServer.
    To invoke 'execute' i used
    MBeanServerConnection con= jmxCon.getMBeanServerConnection();
    con.invoke(new ObjectName(MBEAN_NAME), "execute", new Object[] { COMMAND }, new String[] {});
    where MBEAN_NAME is the ObjectName of the CommandService MBean and COMMAND is a String like "identity add ..."

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

  • 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

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

  • Listening to unix commands from java in background?

    How do i set up a java app in the background to listen to standard-in without hogging standard-in from the OS.

    Hi ,
    this is an example code to check the OS before running the command :
    try{
    int ch;
    Process proc ;
    Runtime r=Runtime.getRuntime();
    StringBuffer sbuf = new StringBuffer();
    String dir = new String();
    String osname = System.getProperty("os.name");
    if(osname.equals("Windows NT") )
    proc = r.exec("cmd /c dir");
    if(osname.startsWith("Linux") )
    proc = r.exec("df -k");
    InputStream is = proc.getInputStream();
    while((ch=is.read() ) != -1)
    sbuf.append((char)ch);
    is.close();
    dir = sbuf.toString();
    System.out.println(dir );
    }catch(Exception e){ System.out.println(e.getMessage());}
    bye
    Taha

  • UNIX "export" Command from Java

    Hi,
    Am facing a problem while exeuting UNIX command from java. Am attaching the code which I am trying to execute.
    import java.io.*;
    public class RunCommandExample {
        public static void main(String args[]) {
            String s = null;
            try
                Runtime.getRuntime().exec("password=midware1");
                   //p = Runtime.getRuntime().exec("export password");
                   System.exit(0);
              catch (IOException e)
                System.out.println("[IOException]. Printing Stack Trace");
                e.printStackTrace();
                System.exit(-1);
    }This gives me the following error.
    [IOException]. Printing Stack Trace
    java.io.IOException: password=midware1: not found
    at java.lang.UNIXProcess.forkAndExec(Native Method)
    at java.lang.UNIXProcess.<init>(UNIXProcess.java:52)
    at java.lang.Runtime.execInternal(Native Method)
    at java.lang.Runtime.exec(Runtime.java:566)
    at java.lang.Runtime.exec(Runtime.java:428)
    at java.lang.Runtime.exec(Runtime.java:364)
    at java.lang.Runtime.exec(Runtime.java:326)
    at RunCommandExample.main(RunCommandExample.java:24)
    Please let me know the solution for this problem.
    Waiting for your valuable replay..
    Thanks in advance,
    Ashly.

    Assigning and exporting variables are not commands that you can execute from Java. You can only execute programs--binary executables. Assigning and exporting shell or environment variables is part of the shell.
    Why are you trying to do this? Even if you could, it wouldn't affect the running VM, and it wouldn't affect anything outside that exec() invocation.
    If you need to set them for something else you're going to run, then you should set them in a shell script and run that script.

  • Call Unix Command From Reports Using Java

    Hi,
    Could somebody please show me a sample coding to call Unix command from 10g report using java?
    In metalink doc id 361857.1 does not show much.
    Thanks,
    neemin

    Hi,
    I have a problem with synchronization of the java commands.
    In the Before Parammeter Form trigger, I have:
    function BeforePForm return boolean is
    rt ORA_JAVA.JOBJECT;
    proc ORA_JAVA.JOBJECT;
    v_txt varchar2(32000);
    i integer := 0;
    v_cd_modulo int;
    v_arqlog text_io.file_type;
    cursor c_evento is
    select codigo,
    nome
    from
    (select e.cd_evento || e.cd_edicao codigo
    ,nm_evento nome
    from grh_ev_evento e
    where e.CD_GRUPO in (select cd_grupo
    from grh_ev_adm
    where cd_usuario = (select cd_usuario
    from usuario
    where login_usuario = :AUTHID)))
    order by substr(nome, 11);
    begin
    -- Create the context for logged user
    if instr(upper(nvl(:AUTHID,'RWCLIENT')),'RWCLIENT') > 0 then
    :AUTHID := :SSO_USUARIO;
    end if ;
    TCEENV.SET_TCEENV(:AUTHID);
    if PK_SCA.SCA_GET_USER_RIGHTS(:sca_module_name, :AUTHID) IS NULL then
    srw.message(100, 'Access denided!');
    return (FALSE);
    end if;
    -- Create file in Report Server (UNIX)
    v_txt := '<BR>' || htf.formSelectOpen('P_EV_EDICAO', 'Evento: ');
    :p_file := '/u03/SCAWEB/repout/' || :sca_module_name || '_' ||
    pk_sca.sca_encrypt(:AUTHID || to_char(systimestamp, 'ss.ff'));
    v_arqlog := text_io.fopen (:p_file, 'A');
    text_io.put_line (v_arqlog, v_txt);
    for reg in c_evento loop
    i := i + 1;
    if i = 1 then
    v_txt := '<OPTION SELECTED VALUE="' || reg.codigo || '">' || reg.nome;
    else
    v_txt := '<OPTION VALUE="' || reg.codigo || '">' || reg.nome;
    end if;
    text_io.put_line (v_arqlog, v_txt);
    end loop;
    v_txt := '</SELECT></CENTER></form></BODY> </HTML>';
    text_io.put_line (v_arqlog, v_txt);
    text_io.fclose (v_arqlog);
    SRW.SET_AFTER_FORM_HTML(SRW.FILE_ESCAPE, :p_file);
    rt := RUNTIME.GetRuntime();
    proc := RUNTIME.exec(rt,'rm ' || :p_file);
    return (TRUE);
    end;
    The problem is that there isn't a "synchronize" command, and the
    RUNTIME.exec(rt,'rm ' || :p_file) don't works (it does nothing) because
    the SRW.SET_AFTER_FORM_HTML has a large delay and the following
    command is ignored.
    How can I solve it?
    thanks,
    lmprestes

  • Calling an Unix command on Remote sun Server in a Java Code

    Hello All
    I have an Java Application which is run on windows server (I)
    I have another Sun Server (II)
    I want to call an unix command on server(II) from java application which is on server(I)
    I am using Samba Server in order to share files between Windows Server and Unix Server
    Can I use samba in order to call command
    or is there any way to open an telnet session within java application
    I will be grateful if you give me some suggestion on this issue
    Regards
    BEKIR BALCIK
    Argela Technologies ...

    Can I use samba in order to call commandYes, smaba supports "magic" files that cause a program to be executed when they are accessed. Note, this does not provide for arguments but you can put these in a file which you command reads.
    or is there any way to open an telnet session within java applicationYes. just use a Socket connection.

Maybe you are looking for

  • Help on performance with dynamic query

    Hi All,   We are using SQL Server 2008R2. In our one of report we are using Dynamic query and it is taking more time to retrieve the data. to retrieve 32 records it is taking 13-15 secs. In my observation in a table variable, created more than 60 col

  • How to disable html for whole swing application.

    Hi, As we can disable html for individual swing components , for example JLabel label.putClientProperty("html.disable",Boolean.TRUE); BasicHTML.updateRenderer(label,"html.disable"); is there any way to disable html rendering in swing components for s

  • Activating technical content in BW7.0

    Hi,     We are in the process of upgrading BW 3.5 to NW 2004s. We followed OSS note 965386 to activate technical content. We assigned all the required authorization to the user and followed the following path to activate the content:- SPRO>SAP NW>Bus

  • Problem with weblogic.Deployer in 8.1

    I have a problem with weblogic.Deployer. My application deploys and works fine if I manually copy the ear or the exploded form into weblogic's applications\ directory (hot deployment). But, if I use the weblogic.Deployer tool, it fails with the follo

  • Problème installé CS3 même si licence et réinstallation

    Bonjour, j'ai acheté La suite adobe creative suite 3 design premium, il y a environ 3 ans et soudainement ce message m'est apparu et je n'avais plus accès a mes programmes: You cannot use this product at this time. You must repair the problem by unst