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!

Similar Messages

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

  • Getting result from a telnet command through Java

    Hi,
    I've been using a set of classes found here: http://javatelnet.org/
    to do telnet through Java in a non-interactive mode.
    However I've got a problem when retrieving the result of a command sent to the remote host: the classes read the stream until the prompt is encountered; my problem is I must execute commands on several remote hosts, and the prompt is not necessarily the same on all hosts.
    Is there a simple means to establish a telnet connection through Java and retrieve the result of the commands?
    Any help would be appreciated.

    Thanks again, this is a very good article
    I see it is still the same strategy to get the result of a command : wait 'til the prompt is sent. Maybe there is just no other way to get it .
    But as I don't know the prompt on the different hosts I have to query, this won't do it.
    The article gave me an idea though : I only need to count the files in a directory on the remote host; until now I was trying to send the 'ls | wc -l' command by Telnet.
    Maybe I can simply do it by FTP (retrieve the list of files, and then count the lines with JAVA).

  • 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

  • Getting  the current operating system information through java

    hi ,
    How can i get the information about the current operating system on which i am working through the java application.

    System.getProperties() and look through the results. All kinds of interesting stuff in there.

  • Getting the exace application page openning through java...

    Hi friends,
    I am able to open Ms word or Excel or any other application through java. Now I want to know in word or excel which pages the user has opened. How can I do this? that is....if user opnes abc.doc or abc.pdf through respective applications I should know that he has opned abc.pdf or abc.doc....
    Can anybody tell we what should I do?
    Thanks,
    BRS.

    Hi ,
    try my sample code and understand.
    import java.awt.BorderLayout;
    import java.awt.event.* ;
    import java.io.* ;
    import javax.swing.* ;
    import sun.awt.shell.ShellFolder;
    * @author Little Dany
    public class OtherApp
            extends JFrame {
        private JFileChooser fc ;
        private OtherApp() {
            super() ;
            setTitle( "Running Other Application" ) ;
            setDefaultCloseOperation( EXIT_ON_CLOSE ) ;
            init() ;
            setSize( 400 , 300 ) ;
            setVisible( true ) ;
        private void init() {
            fc = new JFileChooser() ;
            fc.setApproveButtonText( "Execute" ) ;
            getContentPane().add( new JButton( new ButAct() ) , BorderLayout.SOUTH ) ;
        public class ButAct extends AbstractAction {
            public ButAct() {
                super( "Button" ) ;
            public void actionPerformed ( ActionEvent actEvt ) {
                int r = fc.showOpenDialog( OtherApp.this ) ;
                if( r != JFileChooser.APPROVE_OPTION )
                    return ;
                openFile( fc.getSelectedFile() ) ;
            private void openFile( File file ) {
                Runtime r = Runtime.getRuntime() ;
                String cmd = getExecutable( file ) ;
                if( cmd == null )
                    cmd = file.getPath() ;
                else
                    cmd = cmd + " \"" + file.getPath() + "\"" ;
                try {
                    Process p = r.exec( cmd ) ;
                } catch ( IOException ioe ) {
                    ioe.printStackTrace() ;
            private String getExecutable( File file ) {
                try {
                    ShellFolder sf = ShellFolder.getShellFolder( file ) ;
                    String s = sf.getExecutableType() ;
                    if( s != null )
                        return s ;
                } catch ( FileNotFoundException fnfe ) {
                    fnfe.printStackTrace() ;
                String ext = getFileExtention( file ) ;
                if( ext == null || ext.equals( "txt" ) )
                    return "notepad" ;
                else if( ext.equals( "doc" ) || ext.equals( ".rtf" ) )
                    return "winword" ;
                else if( ext.equals( ".ppt" ) || ext.equals( ".pps" ) )
                    return "powerpnt" ;
                // Add more else if for handle more files like pdf
                // return value is the path of the executable
                // ex. return "C:\\program files\\notepad.exe" ;
                // ex. return "notepad" ; // if notepad.exe in the path variable.
                return null ;
            private String getFileExtention( File file ) {
                String name = file.getName() ;
                int id = name.lastIndexOf( '.' ) ;
                if( id == -1 || id == name.length() - 1 )
                    return null ;
                return name.substring( id + 1 ) ;
        public static void main ( String[] args ) {
            SwingUtilities.invokeLater( new Runnable() {
                public void run () {
                    new OtherApp() ;
    }

  • What is the best way to call SSH commands through Java technologies

    What is the best way to call SSH commands through Java technologies

    I don't think you can specify the password at the prompt using ssh. Plink has the -pw command option for passwords. What I did was except ssh to ask me and write the password programmatically through the outputStream I obtained from my Process object. I looked for "password: ", and then wrote the password with a trailing newline.
    Both plink and ssh will also ask if you trust the host if it is the first time you are connecting to it. So before just writing the password, check if the program wants verification from you: normally supplying "y" or "n". This should only have to happen the first time the client connects. It looks like thisPLINK:
    The server's host key is not cached in the registry. You
    have no guarantee that the server is the computer you
    think it is.
    The server's key fingerprint is:
    1024 f8:43:61:4c:a2:5b:77:be:5b:a7:bb:1f:f7:79:b3:b7
    If you trust this host, enter "y" to add the key to
    PuTTY's cache and carry on connecting.
    If you want to carry on connecting just once, without
    adding the key to the cache, enter "n".
    If you do not trust this host, press Return to abandon the
    connection.
    Store key in cache? (y/n)
    SSH:
    The authenticity of host '127.0.0.1 (127.0.0.1)' can't be established.
    RSA key fingerprint is e1:02:13:c8:52:c2:23:41:9b:5b:58:2c:18:e6:59:af.
    Are you sure you want to continue connecting (yes/no)?What I did was read character by character from the inputStream until I found things of interest ... like "password: ". You only need to search for this in your method which will launch the ssh or plink Process. Once you have verifyed yourself, you can just pass commands to the Process, which is an ssh connection.
    My suggestion is to read() each byte from the Process's inputStream and write it to stdout. Look and see what you need to be looking for so you can interactive with the program correctly. You can't use readLine here becuase when the ssh asks for the password it does not print a newline. I do know for sure, that ssh will simply print, "passowrd: ". Plink will print this as well if the -pw option is not supplied.

  • Running cmd commands through java

    Hi,
    I am trying to run few dos commands through java using Runtime.exec("command") but I am getting following error
    commmand is cd D:\CodeMerge\A\
    java.io.IOException: CreateProcess: cd.. error=2
    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 createDirectory.main(createDirectory.java:24)
    Basically what I am looking for is this:
    1) My program is in D:\Amit\RM
    2) I want to get out to D:\ go to CodeMerge\A\.
    3) Create folder with curretn date as name of the folder
    Hence I am doing
    rTime.exec("cd../..");
    rTime.exec("cd D:\CodeMerge\A\");
    rTime.exec("mkdir "+date);
    Can anybody tell me why I am getting this error
    Jounty

    U can run either DOS Commands or UNIX Commands thru the following Java Program
    Written By BalaNagaraju Malisetti
    contact: [email protected]
    import java.io.*;
    public class RunBdiff
    public static String rununixcmd(String v_prev_path,String v_curr_path,String v_delta_path,String v_beg,String v_len)
    String s = null;
    FileOutputStream fos;
    DataOutputStream dos;
    try
    int v_int_beg = Integer.parseInt(v_beg);
    int v_int_len=Integer.parseInt(v_len);
    int v_int_end=(v_int_beg+v_int_len)-1;
    String v_pos1=String.valueOf((v_int_beg+2));
    String v_pos2=String.valueOf((v_int_end+2));
    String cmd1 = "bdiff ";
    String cmd2=v_prev_path;
    String cmd3=" ";
    String cmd4=v_curr_path;
    String cmd5="| grep '^>'";
    String cmd6="| cut -c";
    String cmd7=v_pos1+"-"+v_pos2;
    String cmd8="| sort ";
    String cmd9="| uniq ";
    String cmd=cmd1+cmd2+cmd3+cmd4+cmd5+cmd6+cmd7+cmd8+cmd9;
    String[] commands = {"/bin/csh","-c",cmd}; //in Unix
    //String[] commands = {"cmd.exe","-c",cmd}; //in Windows
    Process p = Runtime.getRuntime().exec(commands);
    BufferedReader stdInput = new BufferedReader(new InputStreamReader(p.getInputStream()));
    BufferedReader stdError = new BufferedReader(new InputStreamReader(p.getErrorStream()));
    // read the output from the command
    File file = new File(v_delta_path);
    fos = new FileOutputStream(file);
    dos=new DataOutputStream(fos);
    //Writing the output of bdiff command to Delta File
    while ((s = stdInput.readLine()) != null)
    dos.writeChars(s);
    //Return Error Message to Calling Procedure
    while ((s = stdError.readLine()) != null)
    return s;
    return s;
    catch (IOException e)
    return String.valueOf(e);
    public static void main(String args[])
    String msg=rununixcmd("/home/g_anil/MS_ADDRESS1.dat","/home/g_anil/MS_ADDRESS2.dat","/home/g_anil/MS_ADDRESS_DELTA.dat","1","9");
    **************************************************************************************************************************************

  • 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

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

  • Invoking Unix command with java stored procedure

    Hi,
    I have a perfectly working environment and now I am trying to replicate the same in another server. I have a java stored procedure which invokes the Unix command using java Runtime.exec() in my code named "run". I am sure that the code is called and the java class run is resolved in oracle as I could see that in dba_java_resolvers dictionary. But I am not sure whether the function in java is called or whether a exception is thrown. how to identify this? Could there be any thing to do with settings in oracle side? please help me.
    Thanks in advance,
    Marutha

    Hi,
    Do you get any output while running the code?
    I'm testing similar solution and if there are any errors or Oracle can't execute the program due to permissions or other issues the error information will be displayed. Also in the Java class itself you need to catch exceptions and print stack trace to standard output.
    declare
    x number;
    begin
    dbms_output.enable(1000000);
    dbms_java.set_output(1000000);
    x:=system_command.run_command('testconnect.sh');
    dbms_output.put_line('Returned value='||x);
    exception
    when others then dbms_output.put_line('Sql error='||substr(sqlerrm,1,250));
    end;
    <system_command.run_command> - replace with a call to your java stored procedure.

  • Accessing OS level commands through Java?

    Hello everyone,
    Is it possible to access OS-level (Unix BSD for instance) commands through Java classes or methods?
    "OS-level commands" refers strictly to Unix commands such as I/O CTL (control), Poll and Select through a file descriptor.
    "Access" refers to legitimate, built-in OR illegitimate (forced by "fooling" the system) access.

    However, the calls that you refer to, have been implemented in java; that goes for read/write/select (java.io and java.nio). But they pass through the java api implementation, and then throught the native implementation inside the JVM. If you want to use the raw power of poll() through java, you'd have to implement it yourself in JNI. But even if you successfully implement that, you must always remember that you'd have to make corresponding java classes that serve as arguments to your call, which, inside C, you must unpack again - so there goes your speed-advantage out the window.

  • 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

  • Execute unix command using java

    Hello
    Can we execute a unix command using java? If it is how we can execute. Is this affect the performance of the program.
    Thanks

    I tried what you said. But its not working and returning error message,
    java.io.IOException: CreateProcess: ls -a error=2
         at java.lang.ProcessImpl.create(Native Method)
         at java.lang.ProcessImpl.<init>(Unknown Source)
         at java.lang.ProcessImpl.start(Unknown Source)
         at java.lang.ProcessBuilder.start(Unknown Source)
         at java.lang.Runtime.exec(Unknown Source)
         at java.lang.Runtime.exec(Unknown Source)
         at java.lang.Runtime.exec(Unknown Source)
    If i try this statement,
    Runtime.getRuntime().exec("c\windows\notepad");
    It is working fine.
    Any idea about this.
    Plz ...........

Maybe you are looking for

  • Problem with printing with Quicken

    I am suddenly experiencing a problem when trying to print checks with Quicken 11. I have been using this program with my HP C310a printer for several weeks with no real problem, but after having to reinstall the printer after some network problems I

  • OracleXML Publisher Builder 5.6.2 (on the desktop)

    Has anyone been able to display barcodes fonts in PDF files using Preview from the Desktop Template Builder?? I am reviewing "Check Printing using XML Plubliser" White Paper of June 2005 as a reference. I can not make the font for mico display correc

  • HP33120A RS232

    Dear Sir/Madam? I am using LabView 6.1 generic Advanced Serial Write and Read.vi and Basic Serial Write and Read.vi to communicate with a HP33120A. I am writing a simple SCPI command *IDN? to the equipment and I do not think this command is getting t

  • Interface execetuion error

    First I have created one package ,its name is fibonacci. In that I have created one interface ,the code of that programme is: package fibonacci; public interface Fibonacci { // Method to calculate the fibonacci sequence public int calculateFibonacci(

  • Show InstanceName In different Timeline

    I Had a main timeline, timeline2, and timeline3. In timeline2, I had 2 buttons in frame1 and a Movieclip In Frame2. In timeline3, I added 1 component, label. The movieclip will display beside the 2 different button when clicked. But how do i make the