oracle 调用java执行系统命令(linux环境)

来源:互联网 发布:windows mobile模拟器 编辑:程序博客网 时间:2024/05/20 21:22
create or replace and compile java source named runcmd as
import 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(), 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用户)

begin
Dbms_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');

注意,执行的系统命令必须是绝对路径
0 0
原创粉丝点击