重庆思庄Oracle、Redhat认证学习论坛

 找回密码
 注册

QQ登录

只需一步,快速开始

搜索
查看: 3252|回复: 0
打印 上一主题 下一主题

[Oracle] 使用自治事务加触发器实现阻止非法主机dml操作

[复制链接]
跳转到指定楼层
楼主
发表于 2019-3-13 17:15:25 | 只看该作者 回帖奖励 |倒序浏览 |阅读模式
--创建测试表
create table hr.emp as select * from hr.employees;
--创建日志表
create table HR.TR_EMP_LOG ( os_user varchar2(30),
                            host varchar2(50),
                            program varchar2(50),
                            oper_date date,
                            client_ip varchar2(30),
                            db_user varchar2(30),
                            oper_type varchar2(20))
                            tablespace users;
--授予权限
grant select on v_$session to HR;

--创建触发器
create or replace trigger HR.TR_EMP
  before update or insert or delete on HR.EMP
  for each row
DECLARE
  exe_program varchar2(100);
begin
select program
    into exe_program
    from v$session
   where sid = sys_context('userenv', 'SID');
  if  (sys_context('userenv', 'ip_address') = '192.168.133.1' and exe_program = 'plsqldev.exe' and sys_context('userenv', 'SESSION_USER') = 'HR' and inserting)
       or
      (sys_context('userenv', 'ip_address') = '192.168.133.117' and exe_program = 'plsqldev.exe' and sys_context('userenv', 'SESSION_USER') = 'HR' and updating) then
     dbms_output.put_line('success!');
  else
    if inserting then
      p_save_err_result(1,exe_program);
    elsif deleting then
      p_save_err_result(2,exe_program);
    elsif updating then
      p_save_err_result(3,exe_program);
    end if;
    RAISE_APPLICATION_ERROR(-20001, 'you cannot execute DML in EMP table!');
  end if;
end;
/

create or replace procedure p_save_err_result(
                                              in_type        in number,
                                              in_exe_program in varchar2) is
  PRAGMA AUTONOMOUS_TRANSACTION;
BEGIN
  if in_type = 1 then
    insert into HR.TR_EMP_LOG
    values (sys_context('userenv', 'os_user'),SYS_CONTEXT('USERENV', 'HOST'),in_exe_program,sysdate,sys_context('userenv', 'ip_address'),sys_context('userenv', 'SESSION_USER'),'insert');
  elsif in_type = 2 then
    insert into HR.TR_EMP_LOG
    values
      (sys_context('userenv', 'os_user'),SYS_CONTEXT('USERENV', 'HOST'),in_exe_program,sysdate,sys_context('userenv', 'ip_address'),sys_context('userenv', 'SESSION_USER'),'delete');
  else
    insert into HR.TR_EMP_LOG
    values
      (sys_context('userenv', 'os_user'),SYS_CONTEXT('USERENV', 'HOST'),in_exe_program,sysdate,sys_context('userenv', 'ip_address'),sys_context('userenv', 'SESSION_USER'),'update');
  end if;
  commit;
END p_save_err_result;



分享到:  QQ好友和群QQ好友和群 QQ空间QQ空间 腾讯微博腾讯微博 腾讯朋友腾讯朋友
收藏收藏1 支持支持 反对反对
回复

使用道具 举报

您需要登录后才可以回帖 登录 | 注册

本版积分规则

QQ|手机版|小黑屋|重庆思庄Oracle、Redhat认证学习论坛 ( 渝ICP备12004239号-4 )

GMT+8, 2024-6-2 19:21 , Processed in 0.086842 second(s), 21 queries .

重庆思庄学习中心论坛-重庆思庄科技有限公司论坛

© 2001-2020

快速回复 返回顶部 返回列表