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.

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.

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

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

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

  • 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

  • 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

  • How to call gnuplot command from java

    Hi there,
    In our course, we are required to develop an GUI for gnuplot. In case you don't know about gnuplot, it's a plotting program and has lots of command. We want to use java and swing, but now we don't know how to call gnuplot command from java, or how to execute a shell command(script) from java.
    By the way, since we need read in files with several columns of data and allow user to select a column, we want to use JTable. Is that reasonable?
    Thanks a lot for any suggestions!
    Jack

    Hi, there:
    Will using JTable add much overhead? I may have to use several JTables and switch among them. I can add scroll bar to or edit JTables, right?
    BTW, do you have experience about gnuplot? Can I find the command tree of gnuplot somewhere? Or do you know a better place to post question about gnuplot? unix/linux group, maybe.
    Thanks,
    Jack
    P.S. Would you guys answer my question after I use up my duke dollars? :- )

  • Unix and dos commands from Java

    How can I issue a unix command from a java program eg: setenv
    help would be appreciated

    setenv is a C shell builtin command. And it wouldn't make any sense to execute setenv from Java anyway, because the environment variable changes would only apply to that shell and possibly (if the variable is exported) to subprocesses.
    But look at the java.lang.Runtime.exec() method and the Process class.
    (http://java.sun.com/j2se/1.4.2/docs/api/java/lang/Runtime.html)
    Be careful of input and output to the commands. If the command produces output and you don't read it from the getOutputStream(), your command will hang forever when the OS stdio buffer fills up. This can cause terrible random hangs. Search the forums for more on how to handle input and output. You'll probably need multiple threads to read/write the different streams. (stderr, stdout, stdin)

  • 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")

Maybe you are looking for

  • Mac Pro turns itself on every day at the same time

    My Mac Pro suddenly decided to start turning itself on every day at 6:00:12pm local time (12:00:12AM GMT). It turns on at exactly 12 seconds after 6:00pm every day. I recently upgraded to OSX 10.5 and installed the point update. It did it before the

  • SQL queries parser.

    Hello, I have quite strange question related to my research. Probabley within Oracle DB there is some dynamic library which is parsing SQL queries, for example. SELECT * FROM schema.table which is able to extract informations from SQL listed above th

  • How to change display language to myanmar language

    I have a problem of this new version. In old version, I can use myanmar language, with zawgyi font. But this new version cannot read myanmar zawgyi font. Please, reply me. Thanks.

  • Stucked in error

    Hi experts, workflow is stucked in error.what i need to do here.can i strart the workflow after the error.if yes how to do this... please help me on this..

  • Credit static check status B in vkm3

    Hello Experts, Need your help. I have an SO which has a credit status as Released in sales order. When checked at VKM3, it shows Status Check B/Not Approved, Overall Status as Released and is also showing a risk cat of RK2. Currently, the credit stat