Shell commands in pl/sql

Hi i´m having trouble using this:
http://asktom.oracle.com/pls/ask/f?p=4950:8:6113176678923179734::NO::F4950_P8_DISPLAYID,F4950_P8_CRITERIA:16212348050
the code i used is:
create or replace procedure host( cmd in varchar2 ) as
status number;
begin
dbms_pipe.pack_message( cmd );
status := dbms_pipe.send_message( 'HOST_PIPE' );
if ( status <> 0 ) then
     raise_application_error( -20001, 'Pipe error' );
end if;
end host;
I've granted the privileges to run dbms_pipe, BUT when i try to use it, it gets stuck while trying to run :
exec host('ls -l')
it doesn't respond....
then i tryed the part where it uses a shell to see what the procedure is doing, the code is:
#!/bin/csh -f
sqlplus tkyte/tkyte <<"EOF" | grep '^#' | sed 's/^.//' > tmp.csh
set serveroutput on
declare
status number;
command varchar2(255);
begin
status := dbms_pipe.receive_message( 'HOST_PIPE' );
if ( status <> 0 ) then
dbms_output.put_line( '#exit' );
else
dbms_pipe.unpack_message( command );
dbms_output.put_line( '##!/bin/csh -f' );
dbms_output.put_line( '#' || command );
dbms_output.put_line( '#exec host.csh' );
end if;
end;
spool off
"EOF"
chmod +x tmp.csh
exec tmp.csh
I supose it runs ok, becouse it creates a file named tmp.sch, but i can't really be sure becouse the previous part can't be done.
another question is that what does tom mean when he says "running this in the background", do i have to do it o does it do it itself.
what i need to do with this is send a file trough ftp, i've been using this shell named A-ftp.txt:
ftp -v -n 10.128.0.89 << EOF
user username password
bin
put "$1"
bye
EOF
where $1 is the name of the file. so when i try it trough my procedure it would be:
exec host('A-ftp.txt name-of-file')
but it olso gets stuck. I need this urgent!!!! what is the problem??? is there another solution to my problem?? is dbms_pipe the only way???
the code is the same as in the web page were i retrieved it, so i need to be given instructions in what to change and what to leave it as it is.
Restrictions:
I can only use pl/sql
I have little time
Thank You in advance

Restrictions:
I can only use pl/sql
I have little timeYou don't say which version of the database you are using. If it's 9.2 or higher you should check out Tim Hall's PL/SQL ftp implementation.
Cheers, APC

Similar Messages

  • Run a shell command using Pl/Sql

    hi all
    i wonder if anyone knows a way to run a shell command using pl/sql
    other than java stored procedure
    as it seems not to be working in my case
    thanx in advance,
    Rasha

    ofcourse not
    i sent it once then i've got disconnected from interent then i reconnected
    and resend my question so it was sent twice
    now i hope you can answer my question !!!
    Do you really think when asking twice or more often you will get a quicker answer?

  • Runnings Shell Commands in PL/SQL Procedure

    Hi folks,
    I want to run the SQL/Plus HOST command within an PL/SQL Procedure.
    I tried it with "EXECUTE IMMEDIATE 'HOST ls -la';"
    and I'm afraid, that it didn't work.
    Has anyone of you a suggestion?
    regards
    Markus

    you can use system library.
    Example for UNIX:
    <<< create library in DB >>>
    SQL>create or replace library libc
    as
    '/lib/libc.so';
    <<< create procedure >>>
    SQL>create or replace function libc_system (
    cmd_str in varchar2
    ) return pls_integer
    as external
    library libc
    name "system"
    language c
    parameters (cmd_str string);
    <<< use it! >>>
    SQL>exec libc_system('/usr/bin/cp /home/myhome/thefile /export/myfiles/thefile1);
    NOTE1: You are need to be a familiar with "extproc" feature...
    NOTE2: sometime(or always) you are need to put full path to executable files, like: "/usr/bin/cp"
    I didn't checked a usage of env variables, like: $HOME, $ORACLE_HOME, etc...
    NOTE3: This way can't be used to return a "screen" info from the function, like: "cat file1.txt | grep SOMETHING ".
    For this case you can use utl_file package, like: "cat file1.txt | grep SOMETHING > file2". After that you can use utl_file package to read file2...
    null

  • How can i run oralce copy command with in sql j code [urgent]

    I try it but it give me error inavalid sql command etc
    i need help urgent

    http://www.oracle.com/technetwork/database/enterprise-edition/calling-shell-commands-from-plsql-1-1-129519.pdf

  • Excute Unix command Using PL SQL

    Greeting,
    how can I execute shell unix commands from PL SQL and without passing by the Java virtual machine, because my database server is not very performant to support the heaviness of Java.
    Thank you for ur help!!!

    Is this what you need ?
    TEST@db102 SQL> create table test(dir varchar2(100), url varchar2(200));
    Table created.
    TEST@db102 SQL> insert into test values('/tmp','http://otn.oracle.com');
    1 row created.
    TEST@db102 SQL> commit;
    Commit complete.
    TEST@db102 SQL> exit
    Disconnected from Oracle Database 10g Enterprise Edition Release 10.2.0.1.0 - Production
    With the Partitioning, OLAP and Data Mining options
    [ora102 work db102]$ cat /tmp/wget.sh
    #!/bin/bash
    rm -f /tmp/index.html
    /usr/bin/wget -P $1 $2
    [ora102 work db102]$ sqlplus test/test
    SQL*Plus: Release 10.2.0.1.0 - Production on Sat Jul 29 17:11:28 2006
    Copyright (c) 1982, 2005, Oracle.  All rights reserved.
    Connected to:
    Oracle Database 10g Enterprise Edition Release 10.2.0.1.0 - Production
    With the Partitioning, OLAP and Data Mining options
    TEST@db102 SQL> DECLARE
      2     v_dir   varchar2(100);
      3     v_url   varchar2(200);
      4  BEGIN
      5     select dir, url into v_dir, v_url
      6     from test;
      7     DBMS_SCHEDULER.CREATE_JOB(
      8     job_name=>'testjob',
      9     job_type=>'EXECUTABLE',
    10     job_action=>'/tmp/wget.sh',
    11     number_of_arguments => 2,
    12     enabled => FALSE);
    13     dbms_scheduler.set_job_argument_value('testjob',1,v_dir);
    14     dbms_scheduler.set_job_argument_value('testjob',2,v_url);
    15     dbms_scheduler.enable('testjob');
    16* end;
    TEST@db102 SQL> /
    PL/SQL procedure successfully completed.
    TEST@db102 SQL>sorry for lost indentations, but tags do not help us these days....

  • How to prepare for Converting UNIX shell scripts to PL/SQL

    Hi All
    I was said, that i may have to convert a lot of unix shell script to PL/SQL, what are the concepts i need to know to do it efficently,
    what are the options PL/SQL is having to best do that.
    I know the question is little unclear, but I too dont have much inputs about that i'm sorry for that, just its a question of how
    to prepare myself to do it the best way. What are the concepts i have to be familiar with.
    Many Thanks
    MJ

    Just how much work is involved, is hard to say. Many years ago I also wrote (more than once) a complete ETL system using a combination of shell scripts, SQL*Plus and PL/SQL.
    If the PL/SQL code is fairly clean, uses bind variables and not substitution variables, then it should be relatively easy to convert that PL/SQL code in the script to a formal stored procedure in the database.
    There is however bits and pieces that will be difficult to move into the PL/SQL layer as it requires new software - like for example FTP'ing a file from the production server to the ETL server. This can be done using external o/s calls from within PL/SQL. Or, you can install a FTP API library in PL/SQL and FTP that file directly into a CLOB and parse and process the CLOB.
    Think of Oracle as an o/s in its own right. In Oracle we have a mail client, a web browser, IPC methods like pipes and messages queues, cron, file systems, web servers and services, etc. And PL/SQL is the "shell scripting" (times a thousand) language of this Oracle o/s .
    In some cases you will find it fairly easy to map a Unix o/s feature or command to one in Oracle. For example, a Unix wget to fetch a HTML CSV file can easily be replaced in Oracle using a UTL_HTTP call.
    On the other hand, techniques used in Unix like creating a pipe to process data, grep for certain stuff and awk certain tokens for sed to process further... in Oracle this will look and work a lot different and use SQL.

  • How to append linux shell command output to MariaDB?

    That link gave me an idea, I can create an .sql template file with the "insert" query, dump the shell command output to a text file (>), then use "grep" and "sed" to append the desired parts of the command's output file to that .sql file and then execute the .sql file. What do you think?

    I haven't done this myself, but it is probably something along the lines of the answer provided in this link:
    http://stackoverflow.com/questions/3900496/using-shell-script-to-insert-data-into-remote-mysql-datab...
    

  • Running shell commands in pre-post session commands

    Hi Nikita: It depends on what kind of OS your Secure Agent is running on. If you're running your Secure Agent on Windows, you can enter DOS commands into these fields which may include SQL scripts using batch files. Similarly, if you're running your Secure Agent on Linux you can enter shell commands which may include SQL scripts using shell scripts. You should be able to find some examples of these commands from other Informatica Cloud users by searching the Community. Hope this helps,Josh

    Hi all,I am new to informatica, can anyone please explain me how should i run shell commands in pre/post session commands?and what type of shell scripting is usually needed for the informatica jobs? Thank you

  • Executing Shell Scripts through PL-SQL

    Hi All,
    I am trying to execute a shell script from PL-SQL but I am not getting it right .
    the code i used is as follows
    ----JAVA CLASS ---
    CREATE OR REPLACE AND COMPILE JAVA SOURCE NAMED "Host" AS
    import java.io.*;
    public class Host {
    public static void executeCommand(String command) {
    try {
    String[] finalCommand;
    if (isWindows()) {
    finalCommand = new String[4];
    // Use the appropriate path for your windows version.
    finalCommand[0] = "C:\\windows\\system32\\cmd.exe"; // Windows XP/2003
    //finalCommand[0] = "C:\\winnt\\system32\\cmd.exe"; // Windows NT/2000
    finalCommand[1] = "/y";
    finalCommand[2] = "/c";
    finalCommand[3] = command;
    else {
    finalCommand = new String[3];
    finalCommand[0] = "/bin/sh";
    finalCommand[1] = "-c";
    finalCommand[2] = command;
    final Process pr = Runtime.getRuntime().exec(finalCommand);
    pr.waitFor();
    new Thread(new Runnable(){
    public void run() {
    BufferedReader br_in = null;
    try {
    br_in = new BufferedReader(new InputStreamReader(pr.getInputStream()));
    String buff = null;
    while ((buff = br_in.readLine()) != null) {
    System.out.println("Process out :" + buff);
    try {Thread.sleep(100); } catch(Exception e) {}
    br_in.close();
    catch (IOException ioe) {
    System.out.println("Exception caught printing process output.");
    ioe.printStackTrace();
    finally {
    try {
    br_in.close();
    } catch (Exception ex) {}
    }).start();
    new Thread(new Runnable(){
    public void run() {
    BufferedReader br_err = null;
    try {
    br_err = new BufferedReader(new InputStreamReader(pr.getErrorStream()));
    String buff = null;
    while ((buff = br_err.readLine()) != null) {
    System.out.println("Process err :" + buff);
    try {Thread.sleep(100); } catch(Exception e) {}
    br_err.close();
    catch (IOException ioe) {
    System.out.println("Exception caught printing process error.");
    ioe.printStackTrace();
    finally {
    try {
    br_err.close();
    } catch (Exception ex) {}
    }).start();
    catch (Exception ex) {
    System.out.println(ex.getLocalizedMessage());
    public static boolean isWindows() {
    if (System.getProperty("os.name").toLowerCase().indexOf("windows") != -1)
    return true;
    else
    return false;
    ---PROCEDURE TO BE EXECUTED WHICH USES THE ABOVE JAVA CLASS IS ----
    CREATE OR REPLACE PROCEDURE Host_Command (p_command IN VARCHAR2)
    AS LANGUAGE JAVA
    NAME 'Host.executeCommand (java.lang.String)';
    --- THE PERMISSIONS ---
    call dbms_java.grant_permission('SYSTEM', 'SYS:java.io.FilePermission', '<<ALL FILES>>', 'read ,write, execute, delete');
    call dbms_java.grant_permission('SYSTEM', 'SYS:java.lang.RuntimePermission', 'writeFileDescriptor', '');
    call dbms_java.grant_permission('SYSTEM', 'SYS:java.lang.RuntimePermission', 'readFileDescriptor', '');
    --- THE SHELL SCRIPT IS -----
    #!/bin/sh
    # This script removes the carriage returns from the Files having .DAT1 extensions in the /test/ Directory
    # and the sends the single line stream to the new file with the use of 'gawk' command
    # so finaly the files with same primary name but different secondary name are created
    # e.g. file 'test.DAT1' is onverted to 'test.DAT'
    # LOOP on /test/ DIRECTORY FOR SEARCHING FILES HAVING EXTENSION *.DAT1
    for file_name in `ls /test/*.DAT1`
    do
    new_file_name=`echo $file_name | sed 's/DAT1/DAT/'`
    # SEND THE CONTAINTS OF SELECTED FILE IN LOOP AS A CONTINUOUS STREAM TO NEW FILE NAME USING 'gawk' COMMAND
    gawk 'BEGIN { ORS = "''" } { print $0 }' $file_name >> $new_file_name
    # ABOVE LINE WILL CREATE A NEW FILE WITH SAME PRIMARY NAME BUT .DAT AS SECONDARY NAME(EXTENSION)
    # REMOVE THE PRIOR FILE(s) AFTER SUCCESSFUL CALL TO 'gawk'
    # $? returns 0 if the call to gawk command is succesfull
    if test 0 = "$?"
         then
         rm -f $file_name
    fi
    done
    # END LOOP ON /test/ DIRECTORY
    ---THE CALL TO THE PROCEDURE --
    SQL>CALL DBMS_JAVA.SET_OUTPUT(1000000);
    SQL>SET SERVEROUTPUT ON SIZE 1000000
    SQL>exec host('/root/sh ecs_script.sh'); -----------------------------------------------1
    now, the statement 1 is the path of the Shell Script ecs_script.sh
    which uses gawk command and does some operations on some file..
    but when i give the call in Statement 1 its giving error like
    /bin/sh is not a directory
    so i am not getting wHat should I do so that my script "ecs_script.sh" gets executed..
    Please Help.

    The Java proc says:
    > finalCommand[0] = "/bin/sh";
    finalCommand[1] = "-c";
    finalCommand[2] = command;
    You call it as follows:
    SQL>exec host('/root/sh ecs_script.sh');
    The final command will be:
    /bin/sh -c /root/sh ecs_script.sh
    Is this what you intended?

  • Shell commands in applescript noob

    Hi all this is my first post in these forums and I come seeking help with a certain script I'm writing for my current college job. The purpose of the script is to install creative cloud from a server and this is as far as I've got. First I can get as far as setting the correct directory in the server by doing:
    do script "cd /Volumes/applications/Mac/'Adobe Creative Cloud'/'Enterprise - enduser'/Build"
    now when I press run the terminal screen pops up just fine with no errors in the right directory. However I've been reading up that to do other commands in the same shell I must do do shell script. When doing this however terminal doesn't do...anything. The reason why I was trying this is because my next command would be initiating the install which is the command:
    "installer -verbose -pkg 'enterprise_Install.pkg' -target /" with adminitrator privilages
    Now my question is how would formulate this within applescript? Thanks.

    do shell script "cd /Volumes/applications/Mac/'Adobe Creative Cloud'/'Enterprise - enduser'/Build ;  installer -verbose -pkg 'enterprise_Install.pkg' -target / with administrator privilages"
    You got the double quote in the wrong place.
    do shell script "cd /Volumes/applications/Mac/'Adobe Creative Cloud'/'Enterprise - enduser'/Build ;  installer -verbose -pkg 'enterprise_Install.pkg' -target / " with administrator privilages
    It is easier to diagnose problems with debug information. I suggest adding log statements to your script to see what is going on.  Here is an example.
        Author: rccharles
        For testing, run in the Script Editor.
          1) Click on the Event Log tab to see the output from the log statement
          2) Click on Run
        For running shell commands see:
        http://developer.apple.com/mac/library/technotes/tn2002/tn2065.html
    on run
        -- Write a message into the event log.
        log "  --- Starting on " & ((current date) as string) & " --- "
        --  debug lines
        set unixDesktopPath to POSIX path of "/System/Library/User Template/"
        log "unixDesktopPath = " & unixDesktopPath
        set quotedUnixDesktopPath to quoted form of unixDesktopPath
        log "quoted form is " & quotedUnixDesktopPath
        try
            set fromUnix to do shell script "sudo ls -l  " & quotedUnixDesktopPath with administrator privileges
            display dialog "ls -l of " & quotedUnixDesktopPath & return & fromUnix
        on error errMsg
            log "ls -l error..." & errMsg
        end try
    end run

  • Calling Shell commands in C programme

    How would i call shell command using C programme.

    #include <unistd.h>
    #include <sys/types.h>
    #include <stdlib.h>
    #include <sys/types.h>
    #include <wait.h>
    int main(void) {
    pid_t pid;
    pid = fork();
    if (pid == 0) {
    execl("/bin/sh", "sh", "-c", "/bin/ls -l > /tmp/ls", NULL);
    exit(1);
    else if (pid > 0) {
    wait(NULL);
    else {
    return -1;
    return 0;
    }

  • Run shell commands using java program

    Hi guys,
    I am trying to run shell commands like cd /something and ./command with arguments as follows, but getting an exception that ./command not found.Instead of changing directory using "cd" command I am passing directory as an argument in rt,exec().
    String []cmd={"./command","arg1", "arg2", "arg3"};
    File file= new File("/path");
    try{
    Runtime rt = Runtime.getRuntime();
    Process proc = rt.exec(cmd,null,file);
    proc.waitFor();
    System.out.println(proc.exitValue())
    BufferedReader buf = new BufferedReader(new InputStreamReader(proc.getInputStream()));
    catch(Exception e)
    {e.printStackTrace();
    So can anyone please tell me what is wrong with this approach? or is there any better way to do this?
    Thanks,
    Hardik

    warnerja wrote:
    What gives you the idea that the process to execute is called "./command"? If this is in Windows, it is "cmd.exe" for example.It does not have to be cmd.exe in Windows. Any executable or .bat file can be executed as long as one either specifies the full path or the executable is in a directory that is in the PATH.
    On *nix the file has to have the executable bit set and one either specifies the full path or the executable must be in a directory that is in the PATH . If the executable is a script then if there is a hash-bang (#!) at the start of the first line then the rest of the line is taken as the interpreter  to use. For example #!/bin/bash or #!/usr/bin/perl .
    One both window and *nix one can exec() an interpreter directly and then pass the commands into the process stdin. The advantage of doing this is that one can change the environment in one line and it  remains in effect for subsequent line. A simple example of this for bash on Linux is
    import java.io.OutputStreamWriter;
    import java.io.Writer;
    public class ExecInputThroughStdin
        public static void main(String args[]) throws Exception
            final Process process = Runtime.getRuntime().exec("bash");
            new Thread(new PipeInputStreamToOutputStreamRunnable(process.getErrorStream(), System.err)).start();
            new Thread(new PipeInputStreamToOutputStreamRunnable(process.getInputStream(), System.out)).start();
            final Writer stdin = new OutputStreamWriter(process.getOutputStream());
            stdin.write("xemacs&\n");
            stdin.write("cd ~/work\n");
            stdin.write("dir\n");
            stdin.write("ls\n");
            stdin.write("gobbldygook\n"); // Forces output to stderr
            stdin.write("echo $PATH\n");
            stdin.write("pwd\n");
            stdin.write("df -k\n");
            stdin.write("ifconfig\n");
            stdin.write("echo $CWD\n");
            stdin.write("dir\n");
            stdin.write("cd ~/work/jlib\n");
            stdin.write("dir\n");
            stdin.write("cat /etc/bash.bashrc\n");
            stdin.close();
            final int exitVal = process.waitFor();
            System.out.println("Exit value: " + exitVal);
    }One can use the same approach with Windows using cmd.exe but then one must be aware of the syntactic differences between commands running in .bat file and command run from the command line. Reading 'help cmd' s essential here.
    The class PipeInputStreamToOutputStreamRunnable in the above example just copies an InputStream to an OutputStream and I use
    import java.io.IOException;
    import java.io.InputStream;
    import java.io.OutputStream;
    public class PipeInputStreamToOutputStreamRunnable implements Runnable
        public PipeInputStreamToOutputStreamRunnable(InputStream is, OutputStream os)
            is_ = is;
            os_ = os;
        public void run()
            try
                final byte[] buffer = new byte[1024];
                for (int count = 0; (count = is_.read(buffer)) >= 0;)
                    os_.write(buffer, 0, count);
            } catch (IOException e)
                e.printStackTrace();
        private final InputStream is_;
        private final OutputStream os_;
    }

  • Incorporate shell commands from forms

    How to incorporate unix shell commands(eg. ls, cp) from forms9i?
    In Windows environment,it is possible by issuing
    host command(eg. HOST('DIR >k.lis') -- it moves the list of files from Oracle9i/forms90 path to a file k.lis).
    The same thing I have to do in a unix environment.

    I think you have the wrong forum. This forum has to do
    with the UIX technology inside of JDeveloper. Your
    question seems to have to do with UNIX or forms. I can't
    tell which.

  • Executing shell commands from Java.

    I want to execute shell commands in Java using the Runtime.exec( String ) method.
    The method works fine under Linux OS, but under Windows '98 the method didn't work at all!
    For example the following call: Runtime.exec( "dir" ) throws an exception showing that the command was not completed. If I replace dir with ls under Linux all is good. What is the problem with the Microsoft Windows '98 ? Is there any solution at my problem ?!
    thx in advance!

    hey JSarmis,
    You can help me... "ls" doesn't work for me on linux.. using Runtime.exec, some commands work, others don't... you may hold the key to what i need? How did u get "ls" to work?

  • Running Shell Commands (not Executable) in Unix from Java

    What are my options to run shell commands from Java?
    My goal is to change my existing shell environment variables to some new ones provided by .anotherProfile.
    Using an executable from Java is not an option because it does not work i.e. ( exec(". /home/.profile") ) brings up errors.
    Someone has suggested that I start a child shell with that profile and work from there, but I'm unfamiliar with that sort of syntax and programming in general.
    Any good help equals duke dollars :)

    Well there are some possibilities. In the original thread you mentioned that you wanted the shell script to be executed to change some enviroment parameters of the shell the JVM is executing in.
    If so, and you are able to rewrite the profile so you can parse it manually. Then you can change some environment setting by writing the JNI wrappers for the getenv and setenv system calls. (Check your man pages)
    That will change the environment. I am just wondering what good it will do for you? What's use of sourcing the profile in a JVM?

Maybe you are looking for