Get failed sshd logons from Windows Eventlog

This script grabs IP addresses of the last 7 days worth (Customisable) of failed logon attempts for sshd from the Windows event log. This is handy if you use a Windows-based OpenSSH package like copSSH and want to be able to generate a list of all the people making random attempts to logon to your machine for adding to a blacklist or firewall rule.

#Get all SSH events from the last 7 days from the Application eventlog (this may take some time). Change "adddays(-7)" to alter the timeframe.
$events = Get-WinEvent -LogName Application -FilterXPath "*[System[Provider[@Name='sshd']]]" | ?{$_.timecreated -gt $((get-date).adddays(-7))}
#Create array to store IPs
$ips = @()
foreach($event in $events){
	#Convert the event data to XML so we can access the EventData (Otherwise there's no way to access the event message contents with "unregistered" eventids)
	$event = [xml]$event.ToXml()
	#Thin the herd a little and only process "Failed Password" messages
	if($event.Event.EventData.Data.Contains("Failed password")){
	#Do regex search of the message data for IP addresses and if found, add them to the $ips array
	$ip = $event.Event.EventData.Data
	$regex = [regex]"\d{1,3}\.\d{1,3}\.\d{1,3}\.\d{1,3}"
	$ip = $($($regex.matches($ip)).Captures).Value
	$ips = $ips + $ip
$date = get-date -Format yyyy-MM-dd
$file = new-item -type file "SSHLog-$date.txt" -force
#Add unique IPs to output file
add-content $file $($ips | select -uniq)

If anyone has a better way to filter Get-Eventlog using FilterXPath by date as well as something else (Provider in this case) rather than having to get the whole thing and “where” it after, please let me know. I know I *should* be able to do it, but I could never get it to work properly (I think it was a timestamp formatting issue) and the documentation is a bit spartan.

Published by


I am the person responsible for all this, that's all you need to know.

One thought on “Get failed sshd logons from Windows Eventlog”

Leave a Reply

Your email address will not be published. Required fields are marked *

This site uses Akismet to reduce spam. Learn how your comment data is processed.