This script is useful for security audits (helping you gather information about failed login attempts), and for checking recent activity by a particular login (before you delete a login, for example).
The script lists all failed login attempts by a user, including the IP address of the computer from which the login attempts were made. The last successful login for a user is also listed.
Note that security logging must be enabled on the SQL Server you are monitoring, otherwise this script will not return accurate results.
DECLARE @TSQL NVARCHAR(2000)DECLARE @lC INTCREATE TABLE #TempLog (LogDate DATETIME,ProcessInfo NVARCHAR(50),[Text] NVARCHAR(MAX))CREATE TABLE #logF (ArchiveNumber INT,LogDate DATETIME,LogSize INT)INSERT INTO #logFEXEC sp_enumerrorlogsSELECT @lC = MIN(ArchiveNumber) FROM #logFWHILE @lC IS NOT NULLBEGININSERT INTO #TempLogEXEC sp_readerrorlog @lCSELECT @lC = MIN(ArchiveNumber) FROM #logFWHERE ArchiveNumber > @lCEND--Failed login counts. Useful for security audits.SELECT 'Failed - ' + CONVERT(nvarchar(5), COUNT(Text)) + ' attempts' AS [Login Attempt], Text AS DetailsFROM #TempLogwhere ProcessInfo = 'Logon'and Text like '%failed%'Group by Text--Find Last Successful login. Useful to know before deleting "obsolete" accounts.SELECT Distinct 'Successful - Last login at (' + CONVERT(nvarchar(64), MAX(LogDate)) + ')' AS [Login Attempt], Text AS DetailsFROM #TempLogwhere ProcessInfo = 'Logon' and Text like '%succeeded%'and Text not like '%NT AUTHORITY%'Group by TextDROP TABLE #TempLogDROP TABLE #logF
Post a Comment
Post a Comment