---建立審計及審計規範
USE master
CREATE SERVER AUDIT my_first_audit TO FILE(FILEPATH='D:\SQL\TEST\',MAXSIZE=10MB)
GO
---建立和配置可以用於審計的 SQL Server 審計對象
USE Test
CREATE DATABASE AUDIT SPECIFICATION my_aud_spec FOR SERVER AUDIT my_first_audit ADD (SELECT,UPDATE,INSERT,DELETE,EXEC,REFERENCES ON dbo.T_A BY Public) ---本次使用的資料庫層級的審核操作(審核層級操作有;伺服器層級、資料庫層級、審核層級)
go
----查看審計是否存在,並存在的路徑
USE master
SELECT * FROM sys.server_file_audits
USE TEST
--審計規範是否存在及其狀態
SELECT * FROM sys.database_audit_specifications
-- 啟用審計和審計規範(即 是否允許或禁止審核收集此審核規範的記錄。)
USE master
ALTER SERVER AUDIT my_first_audit WITH (STATE=ON)
GO
USE Test
ALTER DATABASE AUDIT SPECIFICATION my_aud_spec WITH (STATE=ON)
go
------------執行相關的SQL語句
SELECT * FROM t_a
DELETE FROM t_a WHERE ID=3
update t_a set name='審計' where id=2
---查看審計收集的記錄資料
SELECT * FROM fn_get_audit_file ('D:\SQL\TEST\*',NULL, NULL)
go
一個完整的審核案例
---建立審核對象
USE [master]
GO
CREATE SERVER AUDIT [my_first_audit]
TO FILE
( FILEPATH = N'D:\test_audit'
,MAXSIZE = 0 MB ---檔案大小無限制
,MAX_ROLLOVER_FILES = 2147483647 --滾動檔案大小無限制
,RESERVE_DISK_SPACE = OFF--關閉保留硬碟空間
)
WITH
( QUEUE_DELAY = 1000 ---隊列延遲時間 MS為單位
,ON_FAILURE = CONTINUE ---稽核線索故障時不關閉伺服器(continue|shutdown)
)
---審核目標:FILE\SECURITY LOG\APPLICATION LOG
GO
---伺服器審核規範
USE [master]
GO
CREATE SERVER AUDIT SPECIFICATION [Server_AuditSpecification]
FOR SERVER AUDIT [my_first_audit]
ADD (BACKUP_RESTORE_GROUP), ---審核操作類型
ADD (DATABASE_OBJECT_CHANGE_GROUP),
ADD (TRACE_CHANGE_GROUP)
---具體審核操作類型:見聯機叢書
GO
---啟用伺服器審核規範
ALTER SERVER AUDIT SPECIFICATION [Server_AuditSpecification]
WITH (STATE = ON)
----關閉或禁用伺服器審核規範
ALTER SERVER AUDIT SPECIFICATION [Server_AuditSpecification]
WITH (STATE = OFF)
---啟用伺服器審核對象
ALTER SERVER AUDIT [my_first_audit] WITH (STATE = ON)
---關閉或禁用伺服器審核對象
ALTER SERVER AUDIT [my_first_audit] WITH (STATE = OFF)
/*建立資料庫審核規範*/
USE [db_test]
GO
CREATE DATABASE AUDIT SPECIFICATION [Database_AuditSpecification]
FOR SERVER AUDIT [my_first_audit]
ADD (SELECT ON OBJECT::[dbo].[a] BY [audit])---制定審核操作類型、對象類(object、schema、database)、對象架構(DBO))對象名稱(a)、 主體名稱(登入名稱或使用者名稱)
---具體審核操作類型:見聯機叢書
GO
---啟用資料庫審核規範
ALTER DATABASE AUDIT SPECIFICATION [Database_AuditSpecification]
WITH (STATE = ON)
---關閉或禁用資料庫審核規範
ALTER DATABASE AUDIT SPECIFICATION [Database_AuditSpecification]
WITH (STATE = OFF)