使用Server Trigger保護重要資料庫物件
阿新 • • 發佈:2018-12-27
一 .Server Trigger的簡單介紹
在SQL Server資料庫中,Server Trigger 是一種特殊型別的儲存過程,它可以對特定表、檢視或儲存中的必然事件自動響應,不由使用者呼叫。建立觸發器時對其進行定義,以便在對特定的資料庫物件作特定型別的修改時執行,根據觸發器定義的動作做出反應。
其主要被用在保持資料庫物件的完整性方面。例如,防止資料庫中已建好的表和儲存過程被更改或刪除。此外還可以 進行更改歷史記錄的追蹤,查看錶或儲存被修改的記錄。
Server Trigger比Database Trigger所管控的範圍更廣,可以管控Server下的所有Database的物件。
二. 主要表 及建立指令碼
表Protected_Objects ,主要用來儲存被保護的資料庫物件,例如 表和儲存過程。 欄位 ActiveFlag設定為Y時有效,N是無效。
有新的資料庫物件建立,最自動Insert一筆資料。
CREATE TABLE [dbo].[Protected_Objects]( [ServerIP] [varchar](100) NULL, [ServerName] [varchar](100) NULL, [DBName] [varchar](100) NULL, [ObjName] [varchar](100) NULL, [Objtype] [varchar](100) NULL, [Creator] [varchar](100) NULL, [ActiveFlag] [varchar](10) NULL, [TransDateTime] [datetime] NULL ) ON [PRIMARY] GO
表DBTrigger_Log,主要儲存資料庫物件變動記錄。
CREATE TABLE [dbo].[DBTrigger_Log]( [ServerIP] [varchar](20) NULL, [ServerName] [varchar](50) NULL, [DBName] [varchar](100) NULL, [ObjectName] [varchar](100) NULL, [ObjectType] [varchar](100) NULL, [EventType] [varchar](100) NULL, [HostName] [varchar](128) NULL, [AppName] [varchar](128) NULL, [EventData] [xml] NULL, [TransDateTime] [datetime] NULL, [Flag] [int] NULL DEFAULT ((0)) ) ON [PRIMARY] TEXTIMAGE_ON [PRIMARY] GO SET ANSI_PADDING OFF GO EXEC sys.sp_addextendedproperty @name=N'MS_Description', @value=N'伺服器IP' , @level0type=N'SCHEMA',@level0name=N'dbo', @level1type=N'TABLE',@level1name=N'DBTrigger_Log', @level2type=N'COLUMN',@level2name=N'ServerIP' GO EXEC sys.sp_addextendedproperty @name=N'MS_Description', @value=N'伺服器名稱' , @level0type=N'SCHEMA',@level0name=N'dbo', @level1type=N'TABLE',@level1name=N'DBTrigger_Log', @level2type=N'COLUMN',@level2name=N'ServerName' GO EXEC sys.sp_addextendedproperty @name=N'MS_Description', @value=N'資料庫名稱' , @level0type=N'SCHEMA',@level0name=N'dbo', @level1type=N'TABLE',@level1name=N'DBTrigger_Log', @level2type=N'COLUMN',@level2name=N'DBName' GO EXEC sys.sp_addextendedproperty @name=N'MS_Description', @value=N'物件名稱' , @level0type=N'SCHEMA',@level0name=N'dbo', @level1type=N'TABLE',@level1name=N'DBTrigger_Log', @level2type=N'COLUMN',@level2name=N'ObjectName' GO EXEC sys.sp_addextendedproperty @name=N'MS_Description', @value=N'物件型別' , @level0type=N'SCHEMA',@level0name=N'dbo', @level1type=N'TABLE',@level1name=N'DBTrigger_Log', @level2type=N'COLUMN',@level2name=N'ObjectType' GO EXEC sys.sp_addextendedproperty @name=N'MS_Description', @value=N'事件型別' , @level0type=N'SCHEMA',@level0name=N'dbo', @level1type=N'TABLE',@level1name=N'DBTrigger_Log', @level2type=N'COLUMN',@level2name=N'EventType' GO EXEC sys.sp_addextendedproperty @name=N'MS_Description', @value=N'終端機器名' , @level0type=N'SCHEMA',@level0name=N'dbo', @level1type=N'TABLE',@level1name=N'DBTrigger_Log', @level2type=N'COLUMN',@level2name=N'HostName' GO EXEC sys.sp_addextendedproperty @name=N'MS_Description', @value=N'名稱' , @level0type=N'SCHEMA',@level0name=N'dbo', @level1type=N'TABLE',@level1name=N'DBTrigger_Log', @level2type=N'COLUMN',@level2name=N'AppName' GO EXEC sys.sp_addextendedproperty @name=N'MS_Description', @value=N'觸發事件xml' , @level0type=N'SCHEMA',@level0name=N'dbo', @level1type=N'TABLE',@level1name=N'DBTrigger_Log', @level2type=N'COLUMN',@level2name=N'EventData' GO EXEC sys.sp_addextendedproperty @name=N'MS_Description', @value=N'發生時間' , @level0type=N'SCHEMA',@level0name=N'dbo', @level1type=N'TABLE',@level1name=N'DBTrigger_Log', @level2type=N'COLUMN',@level2name=N'TransDateTime' GO EXEC sys.sp_addextendedproperty @name=N'MS_Description', @value=N'是否上傳' , @level0type=N'SCHEMA',@level0name=N'dbo', @level1type=N'TABLE',@level1name=N'DBTrigger_Log', @level2type=N'COLUMN',@level2name=N'Flag' GO
三. 建立Server Trigger的指令碼
USE [master] GO /****** Object: DdlTrigger [ServerDBTrigger_ProtectObjects] Script Date: 2018/12/27 13:36:00 ******/ SET ANSI_NULLS ON GO SET QUOTED_IDENTIFIER ON GO /*########################################################################################### *Program*: <DB Trigger> *Description*: <Protect SQL key objects> *programer*: <> *Date*: 2015-12-03 ---0001 2015-12-03 11:12 第一階段期間只保留修改記錄,暫時不阻止(不RollBack) ---0002 2015-12-03 15:32 增加發郵件的功能. ---0003 2015-12-04 14:20 出現set ANSI_PADDING Off後,還有(如果是script出來的表,其中有索引約束等, --- 需要Alter表時,就會報錯。)程式碼時,@xEvent.query會報錯。 ##############################################################################################*/ CREATE TRIGGER [ServerDBTrigger_DBA_ProtectObjects] ON ALL SERVER FOR DROP_TABLE,DROP_PROCEDURE,DROP_VIEW,DROP_FUNCTION, CREATE_TABLE,CREATE_PROCEDURE,CREATE_VIEW,CREATE_FUNCTION, ALTER_PROCEDURE,ALTER_VIEW,ALTER_TABLE,ALTER_FUNCTION,RENAME AS SET NOCOUNT ON ; BEGIN TRY DECLARE @ServerIP varchar(20) DECLARE @ServerName varchar(50) DECLARE @AppName nvarchar(128) DECLARE @HostName nvarchar(128) DECLARE @DBName varchar(100) DECLARE @ObjectName varchar(100) DECLARE @ObjectType varchar(100) DECLARE @EventType varchar(100) DECLARE @ObjectAction varchar(100) DECLARE @xEvent XML SET @xEvent = EVENTDATA() ----------------------0003 start ---------- --Set @DBName=CONVERT(VARCHAR(100),@xEvent.query('data(/EVENT_INSTANCE/DatabaseName)')) --Set @ObjectName=CONVERT(VARCHAR(100),@xEvent.query('data(/EVENT_INSTANCE/ObjectName)')) --Set @ObjectType=CONVERT(VARCHAR(100),@xEvent.query('data(/EVENT_INSTANCE/ObjectType)')) --Set @ObjectAction=CONVERT(VARCHAR(100),@xEvent.query('data(/EVENT_INSTANCE/EventType)')) DECLARE @EventData varchar(MAX) SELECT @EventData=CONVERT(VARCHAR(MAX),@xEvent) SET @DBName= SUBSTRING (@EventData, CHARINDEX('<DatabaseName>',@EventData)+14, CHARINDEX('</DatabaseName>',@EventData)-CHARINDEX('<DatabaseName>',@EventData)-14) SET @ObjectName= SUBSTRING (@EventData, CHARINDEX('<ObjectName>',@EventData)+12, CHARINDEX('</ObjectName>',@EventData)-CHARINDEX('<ObjectName>',@EventData)-12) SET @ObjectType= SUBSTRING (@EventData, CHARINDEX('<ObjectType>',@EventData)+12, CHARINDEX('</ObjectType>',@EventData)-CHARINDEX('<ObjectType>',@EventData)-12) SET @ObjectAction= SUBSTRING (@EventData, CHARINDEX('<EventType>',@EventData)+11, CHARINDEX('</EventType>',@EventData)-CHARINDEX('<EventType>',@EventData)-11) SET @EventType=SUBSTRING(@EventData, CHARINDEX('<EventType>',@EventData)+11, CHARINDEX('</EventType>',@EventData)-CHARINDEX('<EventType>',@EventData)-11) ------------0003 end --------------- SELECT @HostName=HOST_NAME(),@AppName=APP_NAME() SELECT @ServerName = @@SERVERNAME SELECT @ServerIP = MIN(LOCAL_NET_ADDRESS) FROM SYS.DM_EXEC_CONNECTIONS WHERE LOCAL_NET_ADDRESS IS NOT NULL IF EXISTS(SELECT TOP 1 ObjName FROM Protected_Objects WITH(NOLOCK) WHERE ServerName = @@SERVERNAME AND DBName=@DBName AND ObjName=@ObjectName AND ActiveFlag='Y') BEGIN IF (@ObjectName LIKE 'TMP%')OR (/*@ObjectAction LIKE 'ALTER%' AND */@ObjectName LIKE '[_]%') BEGIN INSERT INTO DBTrigger_Log ( ServerIP ,ServerName ,DBName ,ObjectName ,ObjectType,EventType ,HostName , AppName ,[EventData] ,TransDateTime) VALUES ( @ServerIP ,@ServerName , @DBName , @ObjectName ,@ObjectType ,@EventType,@HostName ,@AppName ,@EventData , GETDATE()) END ELSE BEGIN -----------------0001 start --- INSERT INTO DBTrigger_Log ( ServerIP ,ServerName ,DBName ,ObjectName ,ObjectType,EventType ,HostName , AppName ,[EventData] ,TransDateTime) VALUES ( @ServerIP ,@ServerName , @DBName , @ObjectName ,@ObjectType ,@EventType,@HostName ,@AppName ,@EventData , GETDATE()) --Rollback TRANSACTION -----------------end -------- -------------0002 begin ---------------- DECLARE @Subject AS nvarchar(200) DECLARE @Body AS nvarchar(MAX) DECLARE @SPName AS nvarchar(MAX) SET @Subject = 'ServerDBTrigger-重要!;ServerIP:' + @ServerIP SET @SPName = '' SET @Body = '<html><body>Dear All,<br> <br> ServerName:' + @ServerName+ ' ; ServerIP:' + @ServerIP+ '上的object已被改動,請及時檢查!!! <br> You can get detail information from DBA_DBTrigger_Log. <br><br><table border=1 bgcolor=#aaff11>' SET @Body = @Body+ '<tr bgcolor=#ffaa11><td>ServerName</td><td>ServerIP</td><td>DBName</td><td>EventType</td><td>ObjectName</td><td>ObjectType</td><td>HostName </td><td>TransDateTime</td></tr>' SELECT @SPName = @SPName + '<tr bgcolor=#ffaa11><td>'+ CAST(@ServerName AS NVARCHAR(50))+ '</td><td>'+ CAST(@ServerIP AS NVARCHAR(50))+ '</td><td>' + CAST(@DBName AS NVARCHAR(50)) + '</td><td>'+ CAST(@EventType AS NVARCHAR(50))+ '</td><td>'+CAST(@ObjectName AS NVARCHAR(50))+ '</td><td>'+ CAST(@ObjectType AS NVARCHAR(20))+ '</td><td>'+ SUBSTRING(REPLACE(CAST(@HostName AS varchar(500)), CHAR(0), ''), 1, 500)+ '</td><td>'+ CONVERT(varchar(100), GETDATE(), 21)+ '</td></tr>' SET @Body = @Body + @SPName + '</table>' SET @BODY=REPLACE(@BODY,'''','') IF REPLACE(@BODY,' ','')<>'' BEGIN DECLARE @AllEmailToAddress varchar(3000)='' DECLARE @AllEmailCcAddress varchar(3000)='' DECLARE @Allprofile_name varchar(100)='' SELECT @AllEmailToAddress='收件人的地址' SELECT @AllEmailCcAddress='抄送人的地址' SELECT TOP 1 @Allprofile_name=NAME FROM msdb.dbo.sysmail_profile ORDER BY profile_id EXEC msdb..sp_send_dbmail @profile_name = @Allprofile_name -- profile 名稱 ,@recipients = @AllEmailToAddress -- 收件人郵箱 ,@copy_recipients=@AllEmailCcAddress ,@subject = @Subject -- 郵件標題 ,@body = @BODY -- 郵件內容 ,@body_format = 'HTML' -- 郵件格式 ,@file_attachments='' END ------------- 0002 end ------------ END END ----新建物件自動塞入保護表 ELSE BEGIN --PRINT 3 DELETE FROM Protected_Objects WHERE ServerName = @@SERVERNAME AND DBName=@DBName AND ObjName=@ObjectName IF @ObjectAction LIKE 'Create%' AND @AppName LIKE '%Microsoft SQL Server Management Studio%' AND @ObjectName NOT LIKE '[_]%' AND @ObjectName NOT LIKE 'TMP%' BEGIN INSERT INTO Protected_Objects VALUES ( @ServerIP, @ServerName, @DBName, @ObjectName,@ObjectType, @HostName, 'Y', GETDATE() ) INSERT INTO DBTrigger_Log ( ServerIP ,ServerName ,DBName ,ObjectName ,ObjectType,EventType ,HostName , AppName ,[EventData] ,TransDateTime) VALUES ( @ServerIP ,@ServerName , @DBName , @ObjectName ,@ObjectType ,@EventType,@HostName ,@AppName ,@EventData , GETDATE()) END ELSE IF @ObjectAction NOT LIKE 'Create%' AND @AppName LIKE '%Microsoft SQL Server Management Studio%' AND @ObjectName NOT LIKE '[_]%' BEGIN INSERT INTO DBTrigger_Log ( ServerIP ,ServerName ,DBName ,ObjectName ,ObjectType,EventType ,HostName , AppName ,[EventData] ,TransDateTime) VALUES ( @ServerIP ,@ServerName , @DBName , @ObjectName ,@ObjectType ,@EventType,@HostName ,@AppName ,@EventData , GETDATE()) END END END TRY BEGIN CATCH PRINT '@ObjectName:'+@ObjectName PRINT '@ObjectType:'+@ObjectType PRINT ERROR_MESSAGE() ROLLBACK TRANSACTION END CATCH SET ANSI_NULLS OFF GO SET ANSI_NULLS OFF GO SET QUOTED_IDENTIFIER OFF GO ENABLE TRIGGER [ServerDBTrigger_ProtectObjects] ON ALL SERVER GO
四. 補充
建立Server Trigger 後,此時表Protected_Objects是空的,沒有被保護的資料庫物件。我們可以將資料庫下面的物件批量插入。例如,我們將資料庫XXXX下除 _和unuse開頭之外的所有物件批量插入。其指令碼如下:
INSERT INTO Protected_Objects(DBName,ObjName,ObjType,Creator,ActiveFlag,TransDateTime) SELECT 'XXXXXX',Name, CASE xtype WHEN 'U' THEN 'Table' WHEN 'P' THEN 'Procedure' WHEN 'FN' THEN 'Function' WHEN 'TF' THEN 'Function' WHEN 'V' THEN 'View' END, HOST_NAME(),'Y' ,CONVERT(VARCHAR(10),DATEADD(DAY,-46,GETDATE()),120) FROM [XXXXXXX].dbo.sysobjects WHERE xtype IN ('U','P','FN','V','TF') AND name NOT LIKE '[_]%' AND name NOT LIKE 'unuse%'