Executing multiple UNIX commands

Hello
I would like to execute from a Java application the UNIX command :
ls -l | grep ob
I first execute the command "ls -l" and write the output stream in the input stream of the command "grep ob"
My problem is that the second command is waiting for the EOT character and i don't know how to send it. I tried to write the char 4 but it doesn't work
Any idea to run commands with pipes ?
Chris

I reply to myself in case someone else wants to do that job :
    private static byte[] execUNIXcmd(String commande, byte[] outputData, boolean closeStream) {
     Runtime runtime = Runtime.getRuntime();
     Process process = null;
     InputStream inputStream = null;
     OutputStream outputStream = null;
     byte[] bBuf = null;
     try {
         process = runtime.exec(commande);
         outputStream = process.getOutputStream();
         inputStream = process.getInputStream();
         if (outputData != null) {
          outputStream.write(outputData);
         if (closeStream) {
          outputStream.close();
         inputStream = process.getInputStream();
         process.waitFor();
         bBuf = new byte[inputStream.available()];
         inputStream.read(bBuf, 0, inputStream.available());
         return bBuf;
     } catch (InterruptedException e) {
         System.err.println("ERROR : Enable to wait the process");
         return null;
     } catch (IOException e) {
         System.err.println("ERROR : Enable to read input lines");
         return null;
    // Fonction principale
    public static void main(String s[]) {
     byte[] result = null;
     result = execUNIXcmd("ls -l", null, false);
     result = execUNIXcmd("grep java", result,true);
     result = execUNIXcmd("grep ~", result,true);
     System.out.println(new String(result));
    }I missed to close the outputStream of the command waiting for it.
Chris

Similar Messages

  • How to execute a Unix Command in java

    Hi, Iam trying to execute a unix command on Sun Solaris by passing that command to a java program. How can I achieve this?
    Thanks in advance.

    Have a look at the javadoc around the Runtime.exec() method. If the command is a shell command then you might have to execute a shell as well as the command.
    For example, if you wanted to run a unix command 'ls -l > output.txt' the you might have to pass the following string into the exec() method,
    "/bin/sh ls -l > output.txt'

  • Permission denied when I execute a unix command from within my java applet.

    Hi Gang,
    Forgive me if this is not the appropriate forum for this problem. I'm posting this problem on this forum since I got no answers on the other forum I posted on.
    I've written a simple java applet that runs a unix command and then displays some information. The applet compiles fine, and runs perfectly from the command line on my unix system.
    However, when I point a browser at the applet from my desktop PC I get the following error as taken from the java console:
    Exception in thread "AWT-EventQueue-2" java.security.AccessControlException: access denied (java.io.FilePermission <<ALL FILES>> execute)
    This is of course the first line in a long line of error messages. It appears that I am not able to execute a command on the unix system through my applet. I know the problem is with trying to execute a unix command since commenting it causes no error in the web browser. This is the command I'm using in java to execute the unix command:
    p = Runtime.getRuntime().exec("ps");
    Here's the html file on the unix system:
    <html>
    <head></head>
    <body>
    <appletcode=G.class height="250" width="400">
    Your browser does not support the applet tag.
    </applet>
    </body>
    </html>
    I won't list the java code since it is compiling and working on the command line. But, if you want to see it I'll provide it.
    I've done quite a bit of research on this and it seems that a great number of people have similar problems reading or executing files through java. I have yet to find a solution to this problem.
    Here are some details about my setup:
    Server:
    HP9000 running HP/UX 11.23
    Apache Web Server 2.0.35
    Java 1.5
    Desktop PC:
    Win2K Pro
    Internet Explorer 6
    Java 1.6
    If you have a solution I would be very grateful! This problem is keeping me from writing my application!
    thanks!
    kev

    Multi-posted.
    Already answered here http://forum.java.sun.com/thread.jspa?threadID=5225314&messageID=9916327#9916327

  • Permission denied when I execute a unix command from inside my Java applet.

    Hi Gang,
    Forgive me if I'm posting this to the wrong forum! I didn't get any answers on the previous forum that I posted this to.
    I've written a simple java applet that runs a unix command and then displays some information. The applet compiles fine, and runs perfectly from the command line on my unix system.
    However, when I point a browser at the applet from my desktop PC I get the following error as taken from the java console:
    Exception in thread "AWT-EventQueue-2" java.security.AccessControlException: access denied (java.io.FilePermission <<ALL FILES>> execute)
    This is of course the first line in a long line of error messages. It appears that I am not able to execute a command on the unix system through my applet. I know the problem is with trying to execute a unix command since commenting it causes no error in the web browser. This is the command I'm using in java to execute the unix command:
    p = Runtime.getRuntime().exec("ps");
    Here's the html file on the unix system:
    <html>
    <head></head>
    <body>
    <appletcode=G.class height="250" width="400">
    Your browser does not support the applet tag.
    </applet>
    </body>
    </html>
    I won't list the java code since it is compiling and working on the command line. But, if you want to see it I'll provide it.
    I've done quite a bit of research on this and it seems that a great number of people have similar problems reading or executing files through java. I have yet to find a solution to this problem.
    Here are some details about my setup:
    Server:
    HP9000 running HP/UX 11.23
    Apache Web Server 2.0.35
    Java 1.5
    Desktop PC:
    Win2K Pro
    Internet Explorer 6
    Java 1.6
    If you have a solution I would be very grateful! This problem is keeping me from writing my application!
    thanks!
    kev

    Multi-posted.
    Already answered here http://forum.java.sun.com/thread.jspa?threadID=5225314&messageID=9916327#9916327

  • Execute an Unix command with pipe

    Hi,
    How do I execute a unix command with pipe from JAVA runTime.exec(cmd)? for example: "ls -l |wc -l"
    should return number of files. However, there is no output result. If I use "ls -l" as command argument, it gives file list.
    Here is my program:
    public static void main(String[] args) {
    try {
    Runtime runCmd = Runtime.getRuntime();
    System.out.println("sys testing");
    Process retProc = runCmd.exec(args[0]);
    BufferedReader bread = new BufferedReader
    (new InputStreamReader(retProc.getInputStream()) );
    String out = bread.readLine();
    while ( out != null ) {
    System.out.println(out);
    out = bread.readLine();
    DataOutputStream outSt = new DataOutputStream(retProc.getOutputStream() );
    outSt.writeChars(args[1]);
    outSt.flush();
    } catch (Exception ie) {
    ie.printStackTrace();
    Thanks in advance,
    Jeff

    I got my answer !
    No need to reply

  • Problem in executing a unix command through java

    hi
    i'm trying to execute unix command through java
    simple shell command like "ls -l >test " but i'm not able to see the result.
    there are no error messages.
    Code is:
    import java.lang.Runtime.*;
    class ExecDemo
         public static void main(String[] args)
              Runtime r=Runtime.getRuntime();
              Process p=null;
              try
                   p=r.exec("ls -l > test");
              catch (Exception e)
                   System.out.println("Error executing nedit.");
    }can anyone help please.

    get the the inputStream of the runtime object after executing the command.
    now use the readLine() function until it becomes null.
    egs: with reference to ur code.
    InputStream is=p.getInputStream()
    while(is!=null)
    String s=is.readLine();
    if the command don't execute try giving the full path also like /sbin/ls -l

  • Execute a unix command

    How is a unix command executed in Java? What is the syntax?

    Hi,
    The best way to use a UNIX command (or another command from another operating system) is to use java.lang.Runtime class ( one of the exec method)
    It will return you a Process class which represents your UNIX command being executed.
    Once you finish with your process, you just have to destroy it using the destroy method of the Process class.
    Hope you get the picture and good luck.
    touco
    Javaholic & love Duke dollars.

  • Run multiple unix commands from ODI procedure

    I want to run a series of unix commands from ODI procedure. I dont want to use Unix shell scripts. (I know that works).I am just trying to place the contents of the shell scripts in ODI procedure with Operating system as technology. But I am unable to execute the proecedure.
    For example below is a very small 3 line commands I would execute
    filename="/var/test.txt"
    ls -l $filename > /var/anotherfile.txt
    chmod 777 $filename
    I am not sure if there is any specific syntax that I have to follow for executing unix commands. Also I dont want to write a Jython and use os.system command as well.
    Appreciate any help on this

    First your original question... You can put more than one DOS command on a single line, simply separate each command with an ampersand (&). For example:
    mkdir c:\abc & cd abc & dir*
    Regarding your concerns about performance, well that would depend on exactly what you mean. Using CLIENT_HOST (or HOST on the server) simply opens a shell (DOS in this case) then passes your command to it. The performance of performing this action really isn't measurable. Basically you are just pressing a button and you should get a near immediate action. As for the performance of executing each command, that has nothing to do with Forms. Once the command is passed to the shell, the rest is a function of the shell and whatever command you passed.
    Having said that, if you were to write something sloppy like a loop (in pl/sql) which called CLIENT_HOST lots of times repeatedly, then yes there would be a performance problem because the pushing of the button will cause an exchange to and from the server and each cycle in the loop will do the same.
    So the answer to how performance is impacted will depend on what exactly you need to accomplish. If it is a single call to CLIENT_HOST, this should be fine.

  • How to execute multiple SSH commands using Ganymed

    I try to use Ganymed SSH to send and receive commands to/from the SSH server.
    However Ganymed example shows only sending one single SSH command to the SSH server.
    Does anybody know how to send and receive multiple commands to/from SSH server?

    I tried many times and it did not work. Please help.
    The output is this :
    Last login: Tue Oct  6 23:05:10 2009 from 192.168.1.4
    /bin/ls -aldf -k[root@linux ~]# /bin/ls -aldf -kExit status : nullI enclose the
    import ch.ethz.ssh2.ChannelCondition;
    import ch.ethz.ssh2.Connection;
    import ch.ethz.ssh2.KnownHosts;
    import ch.ethz.ssh2.Session;
    import java.io.IOException;
    import java.io.InputStream;
    import java.io.OutputStream;
    import java.io.OutputStreamWriter;
    public class TestClient01 implements Runnable {
        static final String knownHostPath = "~/.ssh/known_hosts";
        static final String idDSAPath = "~/.ssh/id_dsa";
        static final String idRSAPath = "~/.ssh/id_rsa";
        private String host = "192.168.1.2";
        private String username = "root";
        private String password = "1234567";
        private KnownHosts database = new KnownHosts();
        private OutputStreamWriter writer = null;
        private Connection conn = null;
        private Session sess = null;
        public void writeCommand(String s) {
            try {
                writer.write(s);
                writer.flush();
            } catch(Exception ex) {}
        public void close() {
            if (writer==null) return;
            try {
                writer.close();
                sess.close();
                conn.close();
            } catch(Exception ex) {}
            if (writer!=null) writer = null;
        public void run() {
            try {
                conn = new Connection(host);
                conn.connect();
                boolean isAuthenticated = conn.authenticateWithPassword(username, password);
                if (!isAuthenticated) throw new IOException("Authentication failed.");
                sess = conn.openSession();
                new Thread(new SyncPipe(sess.getStderr(), System.err)).start();
                new Thread(new SyncPipe(sess.getStdout(), System.out)).start();
                sess.requestPTY("bash");
                sess.startShell();
                writer = new OutputStreamWriter(sess.getStdin(), "utf-8");
                writeCommand("/bin/ls -al");
                writeCommand("df -k");
                sess.waitForCondition(ChannelCondition.CLOSED | ChannelCondition.EOF |
                        ChannelCondition.EXIT_STATUS, 10000);
                System.out.println("Exit status : " + sess.getExitStatus());
            } catch (Exception e) {
                e.printStackTrace(System.err);
                System.exit(2);
        public static void main(String[] args) throws Exception { new TestClient01().run();}
        class SyncPipe implements Runnable {
            String CVS_VERSION = "$Revision: 1.1 $ $Id: SyncPipe.java,v 1.1 2008-09-30 03:47:56 sabre Exp $ ";
            private final byte[] buffer_;
            private final OutputStream ostrm_;
            private final InputStream istrm_;
            private boolean closeAfterCopy_ = false;
            public SyncPipe(InputStream istrm, OutputStream ostrm) { this(istrm, ostrm, 4096);}
            public SyncPipe(InputStream istrm, OutputStream ostrm, int bufferSize) {
                if (istrm == null) throw new IllegalArgumentException("'istrm' cannot be null");
                if (ostrm == null) throw new IllegalArgumentException("'ostrm' cannot be null");
                if (bufferSize < 1024) throw new IllegalArgumentException("a buffer size less than 1024 makes little sense");
                istrm_ = istrm;
                ostrm_ = ostrm;
                buffer_ = new byte[bufferSize];
            public void handleException(IOException e) { e.printStackTrace();}
            public SyncPipe setCloseAfterCopy(boolean closeAfterCopy) {
                closeAfterCopy_ = closeAfterCopy;
                return this;
            public void run() {
                try {
                    for (int bytesRead = 0; (bytesRead = istrm_.read(buffer_)) != -1;)
                        ostrm_.write(buffer_, 0, bytesRead);
                    ostrm_.flush();
                    if (closeAfterCopy_) ostrm_.close();
                } catch (IOException e) { handleException(e);}
    }

  • Executing multiple IOS commands one after the other with a delay

    Hi -
    As part of my monitoring solution, I have scheduled scripts running on my routers to do various tasks, now I am trying to do trace route to about 10 routers from a seed router to track the path of the trace and if it changes i would be alerted.
    What I am having difficulty is doing one trace commands from a text file. Example follows:
    Trace 10.10.10.1
    Trace 10.20.10.1
    Trace 10.30.10.1
    The command will stop right after the first line, is there a way in IOS to do a “wait” statement between each command to get this going?
    Regards
    Daya Rajaratnam

    Correct, you need 12.3(2)T or higher (for router IOS).  Tcl is also available in many other non-router platforms.  Yes, you do need to be enabled. for tclsh.  For EEM, though, you do not need to be enabled.  You can register an EEM policy, then anyone on the box can execute it.  EEM is also built around Tcl, so the same code could be added to such a policy.  For example:
    ::cisco::eem::event_register_nonenamespace import ::cisco::eem::*namespace import ::cisco::lib::*array set cliarr [cli_open]set output {}foreach host [list x.x.x.x y.y.y.y z.z.z.z] {    append output [cli_exec $cliarr(fd) "traceroute $host"]    after 3000}cli_close $cliarr(fd) $cliarr(tty_id)puts $output
    EEM Tcl policies require 12.3(14)T or higher for router IOS.

  • Running multiple unix commands form java

    hi i have a probelm when i am trying to run more than one command from java:
    i want to run it by using bin/ksh -c (this will take the first arg so i have probelm with runnig commad like" less abc.txt)
    commands to be run:
    1- ll -tr
    2-mkdir x
    3-less abc.txt
    Runtime rt = Runtime.getRuntime();
    Process pr = rt.exec("/bin/ksh -c ll;pwd;less abc.txt");
    which commands i am allowing to run form the java and how can i make it
    best regrdas
    Thanks in advance.

    eddie100 wrote:
    hi i have a probelm when i am trying to run more than one command from java:
    i want to run it by using bin/ksh -c (this will take the first arg so i have probelm with runnig commad like" less abc.txt)
    commands to be run:
    1- ll -tr
    2-mkdir x
    3-less abc.txt
    Runtime rt = Runtime.getRuntime();
    Process pr = rt.exec("/bin/ksh -c ll;pwd;less abc.txt");
    which commands i am allowing to run form the java and how can i make it
    best regrdas
    Thanks in advance.put your commands in a shell script and then call the script from java ...
    import java.io.*;
    class Runner {
            public static void main(String[] argv) throws Throwable {
                    Process p = Runtime.getRuntime().exec("/export/home/caleb/c_code/t.sh");
                    BufferedReader br = new BufferedReader(new InputStreamReader(p.getInputStream()));
                    String line;
                    while( (line=br.readLine()) != null ) System.out.println(line);
    }

  • Execute Unix command on login

    Hello, is it possible to execute a unix command on user login?
    I want that every time a user login on a mac at my company, a unix command be executed.
    Is this case, this is the command: defaults write com.apple.mail NSPreferredMailCharset "UTF-8"
    thks in advance

    {quote}Loginwindow Scripts
    Another way to run applications at login time is to launch them using a custom shell script. Mac OS X provides two options for launching scripts when the user logs in. When creating your script file, keep the following in mind:
    * The permissions for your script file should include execute privileges for the appropriate users.
    * Scripts launched by loginwindow are run as root. Therefore, you should thoroughly test your scripts before deploying them to make sure they do not adversely affect the user's system.
    *In your script, the variable $1 returns the short name of the user who is logging in.
    * Other login actions wait until your hook finishes executing. Therefore, have your script do what it needs to do quickly and then exit. {quote}
    I want the script to be run as the current user that does the login, and not as the root. I think that if its run as root, it changes nothing in the user. Does this root issue apllies to the Zerwas method?
    It depends on how Zerwas was thinking you'd implement it. If you added it to each user's login items, it should run as the user. If you create a startup item to run it, it will run as root. I'm assuming Zerwas was suggesting the former because there would be no point in wrapping the shell script in an AppleScript if you are going to turn it into a startup item.
    What you might be able to do - at least with the loginwindow script - would be to explicitly run the command as the user by making use of the fact that the user name is passed to the loginwindow script as $1. I've never used loginwindow scripts but it seems as though it should work.
    Another possibility would be to use a LaunchAgent. These are really intended to manage background processes, though, and it seems an unnecessary use of resources to load one which will only ever be run at startup.
    Can I ask why you wish to run the script every time a user logs in? Is the concern that the default will get set to something else and needs to be reset regularly?
    - cfr

  • How to execute unix command in java  or jsp

    have a peace day,
    please send some sample code for
    "execute the unix command in java or jsp"
    thank you
    regards
    rex

    i execute this coding
    its compiling. while running i get the error " java.io.IOException: CreateProcess: \ls-l error=2 "
    import java.io.*;
    import java.util.*;
    public class Test
       public static void main(String[] args) throws Exception
         try
              String[] cmd = {"/ls-l"};
    Runtime.getRuntime().exec(cmd);
         catch (Exception e)
               System.out.println(e);
      }what can i do for that
    thank u

  • How to execute unix command from ODI Procedure

    Hi,
    I am trying to execute below unix command from ODI Procedure (Command on Target tab) but I am getting the error "java.io.IOException: Cannot run program "cd": error=2, No such file or directory" but when I try to execute the same command using OdiOSCommand, it is executing successfully. I don't want to use shell script to execute this command. Is there any specific syntax am I missing to execute this command from ODI procedure?
    cd /project3/tmt/;ls *.dmp > dmplist.lst
    Please help me on this...
    Thanks
    MT

    Hi nahlikh,
    Thank you for the reply.
    I used below command in Procedure but still getting the same error as "java.io.IOException: Cannot run program "OdiOSCommand": error=2, No such file or directory".
    OdiOSCommand "-COMMAND=cd /project3/tmt/;ls *.dmp > dmplist.lst"
    as I mentioned earlier if I use the command cd /project3/tmt/;ls *.dmp > dmplist.lst in OdiOSCommand tool it is executing successfully without any issues.
    any thoughts appreciated to get a solution for this issue.
    Thanks
    MT

  • How to execute a unix/dos command in Java

    Hi,
    I want to execute dos/unix commands in my java program. Can anyone tell me how to do this. Say I want to restart my httpd daemon using the command: "service httpd restart" or test my httpd.conf file using the command "testparn"
    thanks in advance
    Hugo Hendriks

    hallo,
    test this:
    Process p = Runtime.getRuntime().exec(Your_Programm);
    p.waitFor();
    LineNumberReader lnr = new LineNumberReader(new InputStreamReader(p.getInputStream()));
    Your_Programm must be a shellscript. regard that your java programm must have the right to start the httpd!
    Carsten Bluetner

Maybe you are looking for