Runtime.exec() - Need to execute unix command through pipe

I want to execute something like this from Runtime.exec() :
tar -czp -C /tmp/ myfile | ssh -qx -c blowfish remoteHost tar -xz -C /tmp/
If I give the complete string as it is, then the system takes ssh command and the arguments to ssh (-qx) as arguments for tar and, thus, fails. I guess the reason is that the Runtime just takes the first string as the command and passes everything else as arguments to the command.
How can I achieve this?

The pipe symbol is interpreted by the shell, so you'd need the command you execute to be a shell (/bin/sh, /bin/csh /bin/bash, etc.) and the rest of it to be the args to that shell.
Look at the man page for your shell. There should be a -c or somesuch argument that means "take the rest of this line as a command to execute in the shell I'm creating, which will then execute."
Something like /bin/bash -c foo \| bar Not sure if you have to escape the pipe or not. Futz around with it and see.

Similar Messages

  • Executing Unix command through Java

    Hi,
    Hi, I am trying to run some unix command through:
    Runtime.getRuntime().exec("some unix command line");
    I am running the code on Linux platform. However, I always got some errors. Here are the stack trace of them:
    java.io.IOException: Cannot allocate memory
    java.io.IOException: java.io.IOException: Cannot allocate memory
            at java.lang.UNIXProcess.<init>(UNIXProcess.java:148)
            at java.lang.ProcessImpl.start(ProcessImpl.java:65)
            at java.lang.ProcessBuilder.start(ProcessBuilder.java:451)
            at java.lang.Runtime.exec(Runtime.java:591)
            at java.lang.Runtime.exec(Runtime.java:429)
            at java.lang.Runtime.exec(Runtime.java:326)Anybody has any idea why is this happening? Thanks.
    Aulia

    Hi, thanks for your reply so far. I tried the following code:
         public boolean executeCommand() {
              boolean success = true;
              for (int i = 0; i < 5; i++) {
                   Process p = null;
                   try {
                        p = Runtime
                        .getRuntime()
                        .exec("ls");
                        InputStreamReader inR = new InputStreamReader(p
                                  .getErrorStream());
                        BufferedReader buf = new BufferedReader(inR);
                        String line;
                        while ((line = buf.readLine()) != null) {
                             System.out.println(line);
                        p.destroy();
                   } catch (Exception e) {
                        System.err.println(e.getMessage());
                        e.printStackTrace();
                        success = false;
                   } finally {
                        p = null;
              return success;
         }However, it still throws the same exception. Yes, I put it in a tight loop, but not recursively.

  • How to execute unix command through odi and store the result in table

    I have to reconcile  if data is loaded in table from csv file or not . I have to create a oracle data integrator package/interface/procedure to execute unix command to count number of rows in the csv files and store the count result in a table then i have to query the loaded table and count number of rows there and store in the table and have to compare is counts are same or not,  Please assist me how to make package/interface/procedure to  execute unix command and store result in oracle table.
    Thanks in Advance

    Use ODI OS command tool in the ODI package.
    create an interface in ODI using LKM File to Sql and the output file generated with the csv file's row count as a source and the db table(where the count needs to be stored) as a target

  • 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

  • Executing Unix Commands

    Hi
    I realise there is a Runtime class to help execute Unix commands from within Java code, but how would this work if the command required a password.
    For example, were I to try to execute:
    ssh -Y myserver.domain.com -u Myself -p
    How would this work with supplying the password (which is prompted for after the command is sent to the shell)?
    Thanks
    Dave

    from the ssh man page under "environment variables":     SSH_ASKPASS
                  If ssh needs a passphrase, it will read the passphrase from the
                  current terminal if it was run from a terminal.  If ssh does not
                  have a terminal associated with it but DISPLAY and SSH_ASKPASS
                  are set, it will execute the program specified by SSH_ASKPASS
                  and open an X11 window to read the passphrase.  This is particu-
                  larly useful when calling ssh from a .xsession or related
                  script.  (Note that on some machines it may be necessary to
                  redirect the input from /dev/null to make this work.)

  • 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

  • GETTING THE OUPUT OF UNIX COMMAND THROUGH JAVA

    Hi Guyz...
    Please help me in the below code...
    My intention is to print the output of Unix command through a java program.
    The Java program resides in the Unix Server only.
    I have written the below java code , but its not returning any values....
    String s1= "ls -lt $APPL_TOP/patch/115/odf/jtfgh.odf";
    Runtime r = Runtime.getRuntime();
    Process p= r.exec(s1);
    StringBuffer ret=new StringBuffer();
    InputStream in = p.getInputStream();
    int c;     
    while ((c = in.read()) != -1)
    {                  ret.append((char)c);       
    }     in.close();
    out.println("OTUPUT : "+ ret.toString());
    Can you please help me in this by debugging the existing code or giving me the exact code??
    IT IS URGENT FOR MY PROJECT!!!!!!!!!!!!!!!!!!!!!!!!!!!
    PLEASE HELP ME!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!

    Since you are expecting the shell to expand the environment variable you need to use
    String[] s1= {"sh","-c","ls -lt $APPL_TOP/patch/115/odf/jtfgh.odf"};
    Also, you should read, digest and implement the recommendations of
    http://www.javaworld.com/javaworld/jw-12-2000/jw-1229-traps.html .
    P.S Your urgency is not my problem and SHOUTING IS CONSIDERED VERY RUDE!

  • Runtime.exec does not work for commands with lengthy outputs

    I need to use Runtime.exec to run some custom commands on a Unix box. I have been doing this for quite some time now and had begun to feel comfortable when recently I started facing a problem. The thing is, whenever there is a command which prints a lot of data on to the console, the program is not able to exit from the waitFor method. Is there some thing that can be done about this?
    Following is a part of the code I use:
    Runtime rt = Runtime.getRuntime();
    Process p = rt.exec (command);
    System.out.println ("Got the process");
    int exitValue = p.waitFor();
    System.out.println ("Exit value: " + exitValue);When the output of the "command" is lengthy, it hangs after printing "Got the process".
    PS: By lengthy output, I mean that the command results in printing lines to the console which might be more than 100 in number. Say, something like what "ls -R /" would do in Unix / Linux.

    From java.lang.Process API doc:
    The Runtime.exec methods may not work well for special processes on certain native platforms, such as native windowing processes, daemon processes, Win16/DOS processes on Microsoft Windows, or shell scripts. The created subprocess does not have its own terminal or console. All its standard io (i.e. stdin, stdout, stderr) operations will be redirected to the parent process through three streams (Process.getOutputStream(), Process.getInputStream(), Process.getErrorStream()). The parent process uses these streams to feed input to and get output from the subprocess. Because some native platforms only provide limited buffer size for standard input and output streams, failure to promptly write the input stream or read the output stream of the subprocess may cause the subprocess to block, and even deadlock.
    So you need to consume the process' output. Check the StreamGobbler example from this article.
    Hope it helps.

  • Execute dos commands through java

    Hi,
    Im trying to execute dos commands through java like
              try {
                   java.lang.Runtime.getRuntime().exec("cmd /c cls");
              }catch(IOException e){
                   System.out.println(e.getMessage());
              }Not sure if its possible? however
    open notepad would work
              try {
                   java.lang.Runtime.getRuntime().exec("notepad");
              }catch(IOException e){
                   System.out.println(e.getMessage());
              }Im trying to execute a cls commands to clear screen but without luck.

    The question is, which shell do you want to clear?
    I don't really know, but it could be that Runtime.exec executes its command in a new shell window...

  • JSP executing UNIX command

    Hi,
    I'm new to JSP. I'm just curious whether is there a utility in Java that we can use to execute unix command?
    thanks.

    Hi,
    You can try this,
    import java.io.*;
    public class test
    public static void main(String args[]) {
    try {
    Process ps = Runtime.getRuntime().exec("ls -al");
    BufferedReader br = new BufferedReader(new InputStreamReader(ps.getInputStream()));
    BufferedWriter bw = new BufferedWriter(new OutputStreamWriter(ps.getOutputStream()));
    bw.write("1");
    bw.flush();
    String line;
    while ((line = br.readLine()) != null) {
    System.out.println(line);
    br.close();
    bw.close();
    System.out.println(ps.exitValue());
    catch(Exception e) {
    System.out.println(e);
    Hope that helps.
    Regards,
    Senthil Babu
    Developer Technical Support
    SUN Microsystems
    http://www.sun.com/developers/support/

  • What is the absolute client permission needed to receive Unix commands?

    The ARD error "This task is not authorized on (computerName)" is forcing me to allow almost all the privileges in the Remote Management section of client computer's Sharing System Preferences. I've already had to add:
    "open and quit applications"
    "change settings"
    "delete and replace items"
    "restart and shutdown" (see this Apple document's suggestion for Unix commands)
    "copy items"
    It makes no sense to my why 'Generate reports' must also be added, but clicking it off makes the error return. I'm just triggering a Unix command that goes something like "echo 1" and runs as root on the one test computer (and potentially dozens, so it wouldn't be pretty changing settings in that many) If it helps, the ARD host is 10.6.7 with ARD 3.4 (installed via the App Store a couple weeks ago) and the clients are 10.4.11 and 10.5.8.
    I'm preparing documentation for ARD and some clients installing our software will not warm to the idea of widening up the permissions footprint. Potentially dozens of computers will need to be retweaked, even if they wouldn't have to leave their seat.
    We also will need to deploy a pkg installer, so some of those may need to remain checked, but ...
    What is the absolute client permission needed to receive Unix commands?
    Thanks

    Have you tried sending it as User: Root
    To my knowledge with that setting you do not need any client permissions as a unix command used as Root overides any permission set. If this is something you need to do often I do know for a fact you can make the report task up use send as Root and tell it to save as template. After this you will be able use the templte to make things a bet quicker. I believe in oder to do this you must enable root user open Directory Utility in order to do this. Keep in mind root has full permissions and any command you enter with unix will be executed as such. This is a word around in the way that the normal client users do not need to have permissions enabled, also having root available at times is handy in stick situations.

  • How to execute unix command line from cocoa?

    how to execute unix command line from cocoa?
    for example, if I want to call "ping" from cocoa, how should I do it? and how can I obtain the return value?
    thank you.
    Power G5 Quad Mac OS X (10.4.3)

    The following article may also help:
    http://cocoadevcentral.com/articles/000025.php
    Mihalis.
    Dual G5 @ 2GHz   Mac OS X (10.4.6)  

  • Send a Unix command through ARD that will change a OS X admin user to a standard user.

    I would love to send a Unix command through ARD that will change a OS X admin user to a standard user. The only thing I found close is
    sudo dscl . -delete /Groups/admin GroupMembership USERNAME
    which does remove the user from the list of admins, but they are still listed as an admin in the user preference panel, and can still use their account to authenticate for admin privileges.

    I'm not having any problems adding or removing users from the 'admin' group by using the syntax's
    dscl . -delete /Groups/admin GroupMembership ARDusername
    or
    dscl . -append /Groups/admin GroupMembership ARDusername
    What I'm saying is if a user is ticked as an Adminstrator in System Preferences and I run the
    dscl . -delete /Groups/admin GroupMembership ARDusername syntax and remove them from the 'admin' GroupMembership they still have the Administrator box ticked in System Prefs and can administer the machine.
    By the way the '/' doesn't work in the syntax in ARD.
    Thanks

  • Facing Problem while executing a command through WLST

    Hi,
    Iam using Weblogic 11g(10.3.2).Whenever I execute the below command in WLST on windows it is working fine.
    reassociateSecurityStore(domain="base_domain",admin="cn=orcladmin",password="welcome1",ldapurl="ldap://<hostname>:389",servertype="OID",jpsroot="cn=jpsroot_idm_idmhost1")
    But whenever i execute the same in Linux,it is throwing the error as below:
    wls:/base_domain/serverConfig> reassociateSecurityStore(domain="base_domain",admin="cn=orcladmin",password="welcome1",ldapurl="ldap://<hoistname>:389",servertype="OID",jpsroot="cn=jpsroot_idm_idm1")
    Traceback (innermost last):
    File "<console>", line 1, in ?
    NameError: reassociateSecurityStore
    Please suggest....
    Regards
    Pavan

    Facing Problem while executing a command through WLST

  • How to run Unix command with Pipe ( | )?

    Dear Friends,
    I have to execute the below unix command through java program.
    *ps -ewwo pid,args | grep -E "abc.sh|xyz.jar" | gawk '{ print $1 }' | wc -l*
    My code to execute this command is,
    Runtime run = Runtime.getRuntime();
    File workDir = new File("/root/sat");
    String psCmd = "ps -ewwo pid,args | grep -E \"abc.sh|xyz.jar \" | gawk '{ print $1 }' | wc -l";
    Process process = run.exec(psCmd, null, workDir);
              String line;
              int i = process.waitFor() ;
              if(i == 0) {
              BufferedReader buf = new BufferedReader( new InputStreamReader( process.getInputStream() ) ) ;
              while ( ( line = buf.readLine() ) != null )
                   System.out.println("Line - ["+line+"]") ;
              } else {
                   BufferedReader stdErr = new BufferedReader(new InputStreamReader(process.getErrorStream()));
                   // read the output from the command
                   while ((line = stdErr.readLine()) != null) {
                   System.out.println(line);
                   }When i execute this command, i'm getting output as,
    ERROR: Garbage option.
    When i analyse the above error, i found that, the PIPE ( | ) command is not supported through java.
    Could anyone please help me how to execute the above unix command (with | ) in java?
    Thanks in advance,
    Sathish

    The pipe has to be interpreted by a shell so you need
    String[] psCmd =
        "sh",
        "-c"
        "ps -ewwo pid,args | grep -E \"abc.sh|xyz.jar \" | gawk '{ print $1 }' | wc -l"
    Process process = run.exec(psCmd, null, workDir);You should also read, re-read and then implement the recommendations in the 4 sections of http://www.javaworld.com/javaworld/jw-12-2000/jw-1229-traps.html .

Maybe you are looking for

  • How to connect airport time capsule through wireless internet

    Just purchased an Airport Time Capsule but having trouble to connect it through my Macbook Air using wireless. Could you please help? many thanks

  • XSLT Transform issue : Same target variable

    Hi all, I have to make 4 database transactions and each database output variable updates the schema output variable. so i have 4 db adapters (and their corresponding assigns) followed by 4 transforms. Now the problem is that all the transforms have t

  • Dynamic Columns in Ref Cursor

    Hi All, I have a requirement that i need to execute query having dynamic number of columns using Ref Cursor e.g. v_string := 'PO_NUMBER , ORG_ID' ; v_query := 'SELECT '|| v_string || 'FROM table_name'; Can someone please quide me how to define Type d

  • Getting return value of a method in an interface

    Hello! I have a problem. I have an interface called I. One of the declared method in this interface is M. And I have a class called C. Class C declares Interface I. I want to get the return value of the method M. I used invoke method. M.invoke(anInst

  • A dozen iPods on my desktop

    I have a 512 MB iPod shuffle 1st gen, and recently I have been having connectivity issues. I believe the origin of this is when I had my iPod plugged into one USB slot on my G4 iBook when I had a USB cable for a mouse plugged in to the other, the lay