10.2. Running OS Commands through Java

Running OS commands through Java does not rely on external procedures, and commands execute with the privileges of the Oracle user. Once the Java source has been created, it is wrapped in a PL/SQL procedure and can then be executed:

CREATE OR REPLACE AND RESOLVE JAVA SOURCE NAMED "JAVACMD" AS
import java.lang.*;
import java.io.*;

public class JAVACMD
{
 public static void execCommand (String command) throws IOException
 {
     Runtime.getRuntime().exec(command);
 }
};
/

CREATE OR REPLACE PROCEDURE JAVACMDPROC (p_command IN VARCHAR2)
AS LANGUAGE JAVA
NAME 'JAVACMD.execCommand (java.lang.String)';
/

exec javacmdproc('cmd.exe /c dir > c:\orajava.txt');

The Java permissions required to execute OS commands are as follows:

exec dbms_java.grant_permission( 'SCOTT', 'SYS:java.io.FilePermission',
'<<ALL FILES>>','execute');
exec dbms_java.grant_permission( 'SCOTT',
'SYS:java.lang.RuntimePermission', 'writeFileDescriptor', '' );
exec dbms_java.grant_permission( 'SCOTT',
'SYS:java.lang.RuntimePermission', 'readFileDescriptor', '' );

Get The Oracle® Hacker's Handbook: Hacking and Defending Oracle now with the O’Reilly learning platform.

O’Reilly members experience books, live events, courses curated by job role, and more from O’Reilly and nearly 200 top publishers.