The below code will send an email alert when someone is added to the SYSADMIN Role on your SQL Server. You can run daily to keep an eye on it. I left some commented code so you can modify it also.
I have not posted any scripts in a long time, Enjoy!
The below code will send an email alert when someone is added to the SYSADMIN Role on your SQL Server. You can run daily to keep an eye on it. I left some commented code so you can modify it also.
I have not posted any scripts in a long time, Enjoy!
set nocount on
select Convert(varchar(35),@@servername) as 'Server_Name',
Convert(varchar(25),[name])as 'Name',
Convert(varchar(25),loginname)as 'LoginName',
sysadmin,
--hasaccess,
Convert(varchar(25),dbname) as 'Default_Db',
Createdate=Convert(varchar,createdate,100),
[Updatedate]=Convert(varchar,updatedate,100) from master..syslogins
where sysadmin = '1' and updatedate > Getdate()-1 --and sid != 0x01
--WHERE LOGINPROPERTY([name], 'PasswordLastSetTime') > DATEADD(dd, -7, GETDATE());
If @@rowcount = 0
return
else
Begin
Print 'Worked'
Declare @srvname varchar(55),@subject1 varchar(255)
Select @srvname = @@servername
DECLARE @xml NVARCHAR(MAX)
DECLARE @body NVARCHAR(MAX)
SET @xml =CAST(( select name AS 'td','',loginname AS 'td','',sysadmin as 'td','',
dbname AS 'td','',Convert(varchar,createdate,100) AS 'td','',Convert(varchar,updatedate,100) AS 'td'
from master..syslogins
where sysadmin = '1' and updatedate > Getdate()-1 and sid != 0x01
FOR XML PATH('tr'), ELEMENTS ) AS NVARCHAR(MAX))
SET @body ='<html><H1>Changed SQL SA Roles on Server '+ @srvname +'</H1><body bgcolor=white>
<table border="1" style="font-family:Georgia, Garamond, Serif;color:blue;font-style:italic;">
<tr><th>Name</th><th>LoginName</th><th>SysAdminBit</th>
<th>DefaultDb</th><th>CreateDate</th><th>UpdateDate</th>
</tr>' SET @body = @body + @xml +'</table></body></html>'
Set @subject1 = 'Debug Test SQL Sa Role Account Change Report on ' + @srvname
EXEC msdb.dbo.sp_send_dbmail
@recipients =N'someone@emailaddress.com',
@body = @body,@body_format ='HTML',
@subject = @subject1 ,
@profile_name ='Your_Mail__Profile'
End