create or replace and compile java source named runcmd asimport java.io.IOException;import java.io.InputStream;import java.io.OutputStream;public class RunCmd{ private static void copyStream(InputStream inputStream, OutputStream outStream,String type) throws IOException { byte[] bytes = new byte[1024]; int len = 0; System.out.println("========"+type+"========"); while ( (len = inputStream.read(bytes)) != -1) { System.out.println(new String(bytes,0,len)); outStream.write(bytes,0,len); } } public static void exec(String cmd) { try { Process pc = Runtime.getRuntime().exec(cmd); copyStream(pc.getInputStream(), System.out,"InputStream()"); copyStream(pc.getErrorStream(),oracle账号 System.out,"ErrorStream()"); } catch (IOException e) { e.printStackTrace(); } }};
然后,创建存储过程
CREATE OR REPLACE PROCEDURE SP_RUNCMD(cmd string)as language java name 'RunCmd.exec(java.lang.String)';
然后给java存储过程的用户授予一定的权限 <<ALL FILE>>表示所有文件(以下是SCOTT用户)
beginDbms_Java.Grant_Permission('SCOTT', 'java.io.FilePermission', '<<ALL FILE>>', 'read ,write, execute, delete');dbms_java.grant_permission('SCOTT','java.lang.RuntimePermission','*','writeFileDescriptor' );end;
然后,打开sqlplus
依次输入
set serveroutput on;call dbms_java.set_output(5000);call sp_runcmd('/bin/sh -c /sbin/ifconfig');
或者是
exec sp_runcmd('/bin/ls /home');
注意,执行的系统命令必须是绝对路径