How do run unix command in java

hi
All unix command working fine in our java program.
but i want change user in linux by using java. it's not working.
"su root" This command onely not working.
anybody know help me
This is my ID [email protected]
This my code
<% String s = null;
try{
Process p = Runtime.getRuntime().exec("su root");
BufferedReader stdInput = new BufferedReader(new
InputStreamReader(p.getInputStream()));
BufferedReader stdError = new BufferedReader(new
InputStreamReader(p.getErrorStream()));
out.println("Here is the standard output of the command:\n");
while ((s = stdInput.readLine()) != null)
out.println(s);
catch(Exception e) {}
%>

I don't have further info to add to your first post, but think your guess seems quite reasonable. I thought of starting a new thread on the same topic, but think this (question) fits in here, too.
I have Java code (freeware, not opensoure), intended for Unix, which basically provides the graphical interface and relies on an I/O layer (C + shell scripts) to do most of the work. I have access to the C+shell scripts which are opensource. I ported it to Cygwin and want to use it under Windows (there is no Cygwin native Java VM).
My problem now boils down to " how to run commands under Unix and what differences are there with Windows". What are the variants?
I have to guess what the program is doing when I get an IOException at some point. E.g.: a call to shell script may be made in a different way as to a compiled exe in Unix?. I found a way to bypass path problems because forward slashes are also accepted and /cygdrive/c construct can be replace by c:/; shell scripts can be compiled into exes using shc and they work; if symbolic links are replaced by duplication of exe files, they work. What will happen in an instance whereby a process runs a shell script dynamically, through a pipe (the shell script is compiled in the Cygwin/win version and receives parameters) in a construct like:
pipefp = epopen(cmdbuf,"w"); /* (cmbuf is "makehdr par1 par2 ... ") (makehdr was a shell script and is now compiled exe for Cygwin/Windows) */?.
Thanks.
LT

Similar Messages

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

  • 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 run DOS command in Java environment?

    Can i run DOS command in Java environment?
    I did like this:
    Runtime r = Runtime.getRuntime();
    r.exec("cmd.exe");
    r.exec("set classpath=%CLASSPATH%;.\\tmp")
    but failed.
    However if I run the java command, it runs successfully.
    r.exec("javac Test.java");
    r.exec("java Test");
    how should I do so that i can run the DOS commands metioned above in Java Environment?
    thanks a lot.

    Have a look at http://www.javaworld.com/javaworld/jw-12-2000/jw-1229-traps.html
    This may help. I wonder if this is ok ?
    Runtime r= Runtime.getRuntime();
    r.exec("cmd.exe /C set classpath=%CLASSPATH%;.\\tmp\"");

  • How to run unix command from Oracle Foms 10g

    OS: UNIX Solaries, Oracle Application Server 10g
    To run shell script from Oracle Forms, I used the following host('/bin/bash /u01/compile.sh') and it works well
    Now, I need to run unix command something like
    host('mv form1.fmx FORM1.FMX') but it's not working
    I tried to append the command "mv form1.fmx FORM1.FMX" to the compile.sh shell script but also it's not working although the rest lines of the shell script is running well
    Edited by: slamonty on Aug 23, 2012 12:36 AM

    Yes, Thank you so much, it works well as follow
    $ /bin/mv /u01/oracle/runtime/test/form1.fmx  /u01/oracle/runtime/test/FORM1.FMX Edited by: slamonty on Aug 23, 2012 9:59 AM
    Edited by: slamonty on Aug 23, 2012 11:14 AM

  • How to run UNIX command to a remote SUN machine through Java from Windows

    Dear All:
    I want to write one Java program which will be run on my Windows Machine.
    My Java program will will login in a SUN machine remotely say telnet and run some command.
    I want all those command output in my client windows PC for futher processing.
    Can anyone help me doing this?
    BR,
    P. Gupta

    import java.net.*;
    import java.io.*;
    import java.util.*;
    public class TelnetSocketDemo {
    static String list="";
    static String listArr[], hostArr[];
    static String host="", lhost="";
    public static void main(String[] args)throws IOException
    ExecuteUnixCmd obj=new ExecuteUnixCmd();
    // InetAddress localMachine = InetAddress.getLocalHost();
    // host=localMachine.getHostName();
    list=obj.ExecuteUnixCmdMain();
    int port=getPort(list,"Live");
    System.out.println(port);
    Socket sock = null;
    String prompt=">";
    String output = null;
    try
    // Connect to the PoleStar process.
    sock = new Socket("localhost",port);
    sock.setSoTimeout(60000);
    // Get the I/O streams for the socket.
    PrintWriter out = new PrintWriter(sock.getOutputStream(), true);
    InputStream in = sock.getInputStream();
    // Get to the silent console port.
    // out.println("S");
    // readToPrompt(in,area);
    // Fetch the response to the command.
    out.println("list all");
    output = readToPrompt(in,prompt);
    //System.out.println(output);
    //out.println("quit");
    //output=readToPrompt(in);
    catch (Exception ex)
    String msg = "unable to get Connection for PoleStar";
    finally
    try
    // close socket
    sock.close();
    catch (Exception ex)
    System.out.println(output);
    private static String readToPrompt(InputStream in,String prompt)throws IOExcepti
    on
    byte[] mByte = null;
    int iStrt = 0, iLen = 2000, nBytes = 0;
    StringBuffer buf = new StringBuffer();
    String s = null;
    boolean bNotFinished = true;
    do
    mByte = new byte[2000];
    nBytes = in.read(mByte, iStrt, iLen);
    if (nBytes == -1)
    break;
    // lost our TCP/IP connection
    // bNotFinished = false;
    // Convert byte stream to a string
    s = new String(mByte, 0, iStrt + nBytes);
    if (prompt.equals("") == false)
    if (prompt.equals(">"))
    if (s.indexOf(0x04) != -1)
    bNotFinished = false;
    // the hub sends the prompt at the beginning and the end
    else if (s.indexOf(prompt) != -1)
    bNotFinished = false;
    buf.append(s);
    } while (bNotFinished);
    return buf.toString();
    public static int getPort(String list, String area)
    int port;
    String listArr[],hostArr[];
    String lhost="";
    listArr=list.split(",");
    for(int i =0; i < listArr.length ; i++)
    lhost=listArr;
    hostArr=lhost.split("#");
    if((hostArr[1].equalsIgnoreCase("connectDev20"))&&(hostArr[0].indexOf(area)!=-
    1))
    port=Integer.parseInt(hostArr[2]);
    return port;
    else
    continue ;
    return 0;

  • Running unix command using java shows error

    Hi All,
    I am trying to run UNIX move command using Java exec method but its throwing error, unable to rename. Here below is the code i am trying to run to move all files from one directory to another directory. source and destination directory exists.
    public class Demo
        public static void main(String args[])
            try
                Runtime rt = Runtime.getRuntime();
                Process proc = rt.exec("mv /home/demo1/* /home/demo2");
                int exitVal = proc.waitFor();
                System.out.println("Process exitValue: " + exitVal);
            } catch (Throwable t)
                t.printStackTrace();
    }if i give "mv /home/demo1 /home/demo2" in exec method, its working, with * character its giving problem.
    Please help me in resolving the problem.
    Thank you

    Characters like *, >, &, |, etc. are interpreted by the command shell--that is by the bash, zsh, etc. programs. When you execute a command with ProcessBuilder or Runtime.exec, you're not going through one of those shells, so their interpretation of those characters is not available.
    In your code, the character * is being delivered directly to the mv command (which doesn't think * is anything special), as opposed to being turned into a list of files and directories as it would be when it's interpreted by the shell. The mv command doesn't know anything about the * character being special.
    If you want to have those shell interpretations, you need to execute the command through a shell. One example is like so, but a) you'll want to read up on the methods in exec() that take arrays of String, and b) you'll want to read up on ProcessBuilder, and c) you'll need to check your shell's man pages to see the exact syntax and arguments.
    runtime.exec("/bin/bash -c 'mv x/* y'");

  • Running Unix command through Java

    Hi
    I am trying to run the unix command "rf filename" through Java and it doesnt seem to work.
    Can anyone help in this case please
    String cm = "rm ";
    String delFile =  args[0];        // this path is /data/temp/filename.doc
    Process p = Runtime.getRuntime.exec(cmd +delFile);Also since i dont have access to delete the file through my login i always login as root for a few commands.
    Is there a way i can specify user name & password & then run the command?
    Please let me know
    Thanx

    Please discard the above msg i got a solution by just adding file.delete
    thanx

  • How to run system commands from JAVA

    Hi Friends,
    How to run windows system commands from JAVA
    Runtime r=Runtime.getRuntime();
    r.exec("dir");
    Throwing following Exception
    CreateProcess :dir error=2
    Thanks in advance
    Hamsa

    Hi ,
    in Windows NT this is not possible, you can use the following :
    Runtime r=Runtime.getRuntime();
    StringBuffer sbuf = new StringBuffer();
    String dir = new String();
    java.lang.Process proc = r.exec("cmd /c dir");
    InputStream is = proc.getInputStream();
    int ch ;
    while((ch=is.read() ) != -1)
    sbuf.append((char)ch);
    is.close();
    dir = sbuf.toString();
    System.out.println(dir );

  • How to run solaris commands through java code ....

    Hi,
    actually i want to run some solaris commands for zipping some files on Solaris OS...
    any idea how can i do that ?
    thanks

    public class TABLES
    public static void main( String[] args )
                      //database is connected
            try
                   Connection con = null;
                   Statement stmt = null;
                   String strShowTables = "";
                ResultSet resultSet = null;
                   // CBA Statistics period is m_lStatisticsPeriod minutes
                   con = DriverManager.getConnection( g_strRWURI, g_strRWUsername, g_strRWPassword );
                   stmt = con.createStatement();
               ResultSet rs = stmt.executeQuery("use db");
             resultSet = stmt.executeQuery(strShowTables);
        String tableName = "";
             while(resultSet.next()){
    tableName = resultSet.getString(1);
              System.out.println(tableName);
            break;
    String strCmd = "tar cvzf file.tar.gz var/lib/mysql/db/GROUPS.*";
    Process p= Runtime.getRuntime().exec(strCmd);
    System.out.println(strCmd);
        stmt.close();
                rs.close();
                resultSet.close();
                   con.close();
              catch ( Exception e )
                   System.out.println( ": Failed to create database connection (" + e.getMessage() + ")" );
                   e.printStackTrace();
              catch ( Throwable t )
                   System.out.println( " Throwable: " + t.getMessage() );
                   t.printStackTrace();
        }//end of main mehtod
    }//END OF CLASSi hava tried the above code... what the problem is
    when is run that command on shell >    tar cvzf file.tar.gz var/lib/mysql/db/GROUPS.*i works fine but in code even though it didn't give any error but the created "file.tar.gz" is empty...
    Edited by: aftab_ali on Apr 7, 2009 7:15 AM
    Edited by: aftab_ali on Apr 7, 2009 7:17 AM

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

  • How to run SQLLDR Command in java

    Hi All,
    I want to upload large amount of data in to a table using SQL Loader and i am using SQLLDR command in command prompt. i need to automate the process because i have to do 2 to 3 times a day manually.
    i have tried the below code inside the main method, but it is not working
    Runtime rt = Runtime.getRuntime();
    Process proc = rt.exec("SQLLDR idm/idm@idmdev control=E:\\SAP_HR\ttsldata.ctl");
    I have Control file and CSV Format data with me. While trying in command prompt it is working but not using java. Please help me to finish this.
    Thanks in Advance!!!!

    Sorry for that, SQLLDR means SQL Loader command to upload the data in to the database. Please let me know how to do it.

  • How to run dos command on java

    would java run the dos command ?
    if yes ~would you mind give me some example~please~

    ..or just use:
    Runtime.getRuntime().exec("cmd /c commandyouwanttouse");
    Hope it works!                                                                                                                                                                                               

  • How to run  batch command in java?

    Hi, my program needs to use an outside batch file command, for instance, its name is "generateXML", its syntax is
    [command prompt] : generateXML sourceFile.dtd XMLFile.xml
    I want to include this command into my code so that do that and other things at one go.
    Thanks

    public class Test{
    public static String genXML() throws IOException{
        Process p = Runtime.getRuntime.exec( "generateXML sourceFile.dtd   XMLFile.xml" );
        try{
            p.waitFor();
        }catch( InterruptedException ie ){}
        InputStream err = p.getErrorStream();
        int ctr = 0;
        if ( (ctr = err.available()) > 0 ){
           byte[] buf = new byte[ ctr ];
           throw new IOException( "Process failed with error:\n" + new String( buf, 0, ctr );
        String str = "Process was successful...Output was:\n";
        InputStream output = p.getInputStream();
        if ( (ctr = output.available()) > 0 ){
           byte[] buf = new byte[ ctr ];
           str += new String( buf, 0, ctr );
        return str;

  • How to run a unix command in java

    Hi all,
    I need to run a unix command in my standalone java application.my java program is in windows.Is it possible to run unix command on windows system.help me out.
    I tried this
    Process p = Runtime.getRuntime().exec("ps -ef");
                BufferedReader stdInput = new BufferedReader(new
                     InputStreamReader(p.getInputStream()));
                BufferedReader stdError = new BufferedReader(new
                     InputStreamReader(p.getErrorStream()));i get IO Exception -Create Process ps-ef error=2

    If you want to run a command from java for a windows platform, you should check windows knows the command.
    So, load up a DOS prompt and type ps -ef and see what happens.

Maybe you are looking for

  • Timeouts

    When I start iChat and have my iSight camera off on several occasions iChat starts but the camera is absent despite the fact that I belatedly switched it on. Also when inactive for a while, though iChat is still displayed or in the dock, the camera d

  • My mac wont load when I turn it on

    When I turn my Macbook on all it shows is the apple sign and says its loading but doesnt load. I cannot get to my login screen and log on to my account on my Macbook and access my desktop. How do I fix this?

  • Red eye problem

    hi all, I've used the red eye tool to fix 3 red eyes in a photo. 2 of them are fine. with 1 of them, it looks fixed in the normal view, but when I hover the loupe over it, it's still red.. more importantly, when I export a jpeg or other version, the

  • No records generated

    Hi gurus Below is the script for rolling forecast I am on SP6,EPM 10 NW , though I was using another system with SP16 I had the same issue why  am i seeing no records both in DM and UJKT "norecords generated" there is data in Actuals for the immediat

  • Jre upgrade in EBS database 11.2.0.2

    As per the metalink document 455492.1 we are planning upgrade to Jre1.6.38 on database node. where can I download Jre1.6.38 for RHEL 64 bit.