Run Unix command from PLSQL

I am trying to execute simple Unix command such as (/UItools/touch test.txt or /UItools/cp t1.txt t2.txt ) from PL/SQL. Could somebody pls help?

Hi,
you can use DBMS_PIPE to achieve this
CREATE OR REPLACE FUNCTION exec_host_command( lc_cmd IN VARCHAR2 )
RETURN INTEGER IS
ln_status NUMBER;
lc_errormsg VARCHAR2(80);
lc_pipe_name VARCHAR2(30);
BEGIN
lc_pipe_name := ‘HOST_PIPE’;
dbms_pipe.pack_message( lc_cmd );
ln_status := dbms_pipe.send_message(lc_pipe_name);
RETURN ln_status;
END;
Alternatively you can write a java stored procedure to do the same
CREATE OR REPLACE AND COMPILE JAVA SOURCE NAMED "Cmd" AS
--==========================================================--
-- Class Cmd
--==========================================================--
import java.io.BufferedReader;
import java.io.InputStreamReader;
public class Cmd {
*Static method to invoke host system commands
*input variable String Command
*Returns int. 0 for success and any other number
*for failure of the command
public static int executeCommand(String s_command) {
try {
/*Get the runtime shell and execute the system command
*Wait till the command is executed
final Process pr = Runtime.getRuntime().exec(s_command);
pr.waitFor();
return pr.exitValue();
catch (Exception ex) {
System.out.println(ex.getLocalizedMessage());
return -1;
}/*End of function executeCommand*/
SHOW ERRORS
EXIT;
Grant the permissions
--Grant Host File permissions to the APPS schema
DBMS_JAVA.grant_permission ('<USER>', 'java.io.FilePermission',
'<<ALL FILES>>', 'read ,write, execute, delete');
--Grant Runtime Write permissions to the APPS schema
DBMS_JAVA.grant_permission ('<USER>', 'SYS:java.lang.RuntimePermission',
'writeFileDescriptor', '');
--Grant Runtime Read permissions to the APPS schema
DBMS_JAVA.grant_permission ('<USER>', 'SYS:java.lang.RuntimePermission',
'readFileDescriptor', '');
and create a wrapper plsql call
FUNCTION Cmd (p_command IN VARCHAR2)
RETURN NUMBER
AS LANGUAGE JAVA
NAME 'Cmd.executeCommand (java.lang.String) return int';
Edited by: navsriva on Apr 13, 2010 3:21 PM

Similar Messages

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

  • Unix command from Plsql block

    Hi all ,
    I have tried unix command from PLSQL Block,
    Please see the code.
    DECLARE
    stat INTEGER;
    host_command varchar2(100);
    errormsg VARCHAR2(80);
    command varchar2(2000);
    BEGIN
    command:='touch /home/oracle/testting.txt';
    dbms_pipe.reset_buffer;
    host_command:= dbms_pipe.unique_session_name;
    dbms_output.put_line('host_command:'||host_command);
    dbms_pipe.pack_message(command);
    dbms_output.put_line('pack message:'||command);
    stat := dbms_pipe.send_message(host_command);
    dbms_output.put_line('stat:'||stat);
    IF stat <> 0 THEN
    raise_application_error(-20000, 'Error:'||TO_CHAR(stat)||' sending on pipe');
    END IF;
    stat := dbms_pipe.receive_message(host_command);
    dbms_output.put_line('stat2:'||stat);
    IF stat <> 0 THEN
    raise_application_error(-20000, 'Error:'||TO_CHAR(stat)||' receiving on pipe');
    END IF;
    dbms_pipe.unpack_message(errormsg);
    dbms_output.put_line('errormsg:'||errormsg);
    IF errormsg <> 'SUCCESS' THEN
    raise_application_error(-20000, 'Execution error: '||errormsg);
    END IF;
    END;
    Nothing happend from this code just getting only following result with error.
    -----------------result-----------------------------
    host_command:ORA$PIPE$002D19820001
    pack message:touch /home/oracle/testting.txt
    stat:0
    stat2:0
    errormsg:touch /home/oracle/testting.txt
    DECLARE
    ERROR at line 1:
    ORA-20000: Execution error: touch /home/oracle/testting.txt
    ORA-06512: at line 33
    Can any one tell me what i doing wrong in this code.
    I m working on Oracle 11g and AIX unix server.

    This is the forum for the SQL Developer product, not for general PL/SQL questions. There is a link to the SQL and PL/SQL forum in the announcement at the top of this forum.

  • 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

  • Running unix commands from within a procedure

    Oracle 11.1, AIX 6.1
    ================
    A developer would like to know what the commands are to execute from within a procedure to run unix commands on the database server and capture those results back to the procedure for parsing & manipulation.
    Thanks.

    Don't take this as the correct way to do it, but this is merely 'a' way to do it:
    have a db procedure thats executes a db function
    create or replace procedure csproc(p_cmd in varchar2)
    as
    x number;
    begin
    x:=csfunc(p_cmd);
    dbms_output.put_line('x is: '||x);
    end;
    /The function calls a piece of java to execute the os command and return the return code of the os command
    create or replace function csfunc( p_cmd  in varchar2) return number
    as language java
    name 'csclass.RunThis(java.lang.String[]) return integer';
    /Here is the java class to run the os command
    create or replace and compile java source
    named "csclass"
    as
    import java.io.*;
    import java.lang.*;
    public class csclass extends Object
    public static int RunThis(String[] args)
       Runtime rt = Runtime.getRuntime();
        int        rc = -1;
        try
           Process p = rt.exec(args[0]);
          int bufSize = 4096;
           BufferedInputStream bis =
           new BufferedInputStream(p.getInputStream(), bufSize);
           int len;
           byte buffer[] = new byte[bufSize];
           // Echo back what the program spit out
           while ((len = bis.read(buffer, 0, bufSize)) != -1)
              System.out.write(buffer, 0, len);
           rc = p.waitFor();
        catch (Exception e)
           e.printStackTrace();
           rc = -1;
        finally
           return rc;
    /and finally the os command - in this case its a very simple shell script
    #!/usr/bin/ksh
    echo "Hi" >> /app/oracle/workdir/cs.logwill have to grant privileges to my user 'CS' to run the various os commands
    exec dbms_java.grant_permission('CS','java.io.FilePermission','/app/oracle/workdir/cs.ksh','read,execute');
    exec dbms_java.grant_permission('CS','java.io.FilePermission','/app/oracle/workdir/cs.log','write');
    exec dbms_java.grant_permission('CS','SYS:java.lang.RuntimePermission','*','readFileDescriptor');
    exec dbms_java.grant_permission('CS','SYS:java.lang.RuntimePermission','*','writeFileDescriptor');and finally can run the procedure from within the db
    set serveroutput on
    exec dbms_java.set_output(1000000);
    exec csproc('/app/oracle/workdir/cs.ksh');
    x is: 0
    PL/SQL procedure successfully completed.to prove it works ok the logfile shows an entry:
    'Hi'

  • Run Unix command from windows

    I would like to run a unix command and capture the output by running a java program on a windows 98 machine, this will be ran on a secure intranet. What is the best way to do that. If anyone knows of an example source code that would be great.
    thanks,
    Dean

    Try this. It always works for me.
    import java.io.*;
    public class Exec {
        private BufferedReader out;
        private Process p;
        public Exec(String cmd) throws IOException {
            p = Runtime.getRuntime().exec(cmd);
            out = new BufferedReader(new InputStreamReader(p.getInputStream()));
        public BufferedReader getBufferedReader() {
            return out;
        public void waitFor() throws InterruptedException {
            p.waitFor();
        public static void main(String [] args) throws IOException,
                InterruptedException {
            final Exec p = new Exec("your command goes here.");
            new Thread(new Runnable() {
                public void run() {
                    try {
                        String s = null;
                        while((s = p.getBufferedReader().readLine()) != null) {
                            System.out.println(s);
                    catch(IOException io){}
            }).start();
            p.waitFor();
    }

  • Running Unix Commands from SQLJ

    In straight JAVA I can execute a UNIX command like this
    String [] cmd = {"foo"} ;
    Process m ;
    m = Runtime.getRuntime().exec(cmd) ;
    When I do this in SQLJ I gen an exception raised.
    Is there a way around this?

    I assume you are trying to execute this Java code in a server-side stored procedure?
    I do not think that the server-side JavaVM allows you to execute Unix command lines. On the other hand, if you are trying to do this on the client, there should be nothing preventing you.

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

  • Running unix commands from sqlplus

    I will like to change my directory from sqlprompt. What is the command to do that?
    SQL>

    Don't think you can do what you want. The 'host' or '!' command in sqlplus spawns another shell, as soon as it returns the settings are back to the parent shell "the one that started sqlplus".

  • Run Unix command / Run Unix shell script from Forms9i

    Hi,
    I have a requirement to run Unix command and Unix shell scripts from Forms9i.
    I know HOST command cannot be used directly. I also know we can create some JAVA stored procedure to perform the task, but I don't want to create any JAVA stored procedure as there are some security concerns.
    Please point me towards any other way to achieve the same.
    I would really appreciate your help.
    Thanks,
    Kumar

    There is no reason why HOST can't be used. This is what it is for. As for using Java, it is not a stored procedure that you would be using, it would be imported Java (imported into the form).
    The best way to use the HOST command is to call a script (.sh) rather than calling a Unix command directly. This is because HOST will not pick up environment variables set at the system level. So the script would first need to set the necessary environment variables then call the desired commands.

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

  • Running ssh command from java and then answering password prompt

    Hi,
    I have a situation that has not solved yet. I am running ssh command from unix terminal without any problem, and then i enter password.
    For example :
    [oracle@fuata]:/export/home/oracle> ssh -N [email protected] -L 9901:127.0.0.1:9999
    Password:
    It is working. I have question that how can i perform this in java? I am thinking that i can run ssh command by using Runtime Class, it is ok. But how can i answer the password? I am a bit confused. Is there any example looks like this?
    Thanks for responses.

    futi wrote:
    Thanx. Firstly i insisted to do this without jsch but actually this is harder than jsch. I edit some of code pieces PortForwardingL.java and could run it. It works problem-free. Could you say why you "insisted" on this approach. It can't be for speed+ since jsch is very fast. It can't be for portability+ since jsch is portable but the use of Runtime.exec() requires the installation of ssh software. It can't be because of limitations+ since jsch is a fully featured library. It can't be for security+ since jsch is secure. It can't be for ease of use+ since jsch is much easier to use than ssh with Runtime.exec(). Unless it's a licensing issue, it can't be for commercial+ reasons since jsch is free. The only reason I can think of why one would "insisted" on this approach is if it is for some college project.

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

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

Maybe you are looking for