Wednesday, December 21, 2022

Alert when a login is created or dropped

ALTER TRIGGER LoginCreateDropTrigger ON ALL SERVER FOR CREATE_LOGIN, DROP_LOGIN AS BEGIN DECLARE @mailBody Nvarchar(MAX); DECLARE @data XML = EVENTDATA(); Declare @Mailsubject NVarchar(MAX) = 'Someone Created or Dropped a Login on SOX Server.As this is a SOX server, please create a ticket:' +@@SERVERNAME SET @mailBody = 'A new login was created on SQL Server: ' + @@SERVERNAME + ' ' + 'By user: ' + ISNULL(@data.value('(/EVENT_INSTANCE/LoginName)[1]', 'nvarchar(max)'), 'Null Login' ) + ' ' + + 'The TSql executed to do this was: ' + ISNULL(@data.value('(/EVENT_INSTANCE/TSQLCommand)[1]', 'nvarchar(max)'), 'Null SQL ' )+ ' ' + 'At: ' + CONVERT(nvarchar, getdate(), 120) + ' ' + 'Please verify why this login was created and create a ticket if there is not' + ' ' ; Declare @bodyNew Nvarchar (Max) = Convert(Nvarchar(MAX),@data) Declare @SubjectNew Varchar(max)= 'As this is a SOX Server, Please create a Ticket'+CONVERT(VARCHAR(12),GETDATE(),107) EXECUTE MSDB.DBO.sp_send_dbmail @profile_name ='SQLMail' , @recipients = 'ABC @ABC.com', --this should be a distro @importance = 'High', @Subject=@Mailsubject, @body = @mailBody, @body_format = 'HTML' END ----DROP TRIGGER [LoginCreateDropTrigger] ON ALL SERVER go USE [master] CREATE LOGIN [TestNaresh] WITH PASSWORD=N'P@SSW)rd1@#$' MUST_CHANGE, DEFAULT_DATABASE=[master], CHECK_EXPIRATION=ON, CHECK_POLICY=ON GO DROP LOGIN [TestNaresh] go EXEC msdb.dbo.sysmail_start_sp; EXEC msdb.dbo.sysmail_help_status_sp;

No comments:

Post a Comment

https://blog.sqlauthority.com/2009/06/27/sql-server-fix-error-17892-logon-failed-for-login-due-to-trigger-execution-changed-database-context...