用PowerShell查询Windows登录失败的用户名和客户端IP

看看是谁在尝试登录我的Windows

## Minimal refactor: list all failed usernames and all client IPs that attempted and failed

$Days = 30

try {
    $events = Get-WinEvent -FilterHashtable @{LogName='Security'; Id=4625; StartTime=(Get-Date).AddDays(-$Days)} -ErrorAction Stop
} catch {
    Write-Host "Failed to read Security log: $($_.Exception.Message)" -ForegroundColor Red
    exit 1
}

if (-not $events -or $events.Count -eq 0) {
    Write-Host "No 4625 (failed logon) events found in the Security log for the last $Days day(s)." -ForegroundColor Yellow
    exit 0
}

# extract TargetUserName and IpAddress from each event
$users = @()
$ips = @()

foreach ($e in $events) {
    try {
        $xml = [xml]$e.ToXml()
    } catch {
        continue
    }
    $data = $xml.Event.EventData.Data
    $target = ($data | Where-Object { $_.Name -eq 'TargetUserName' } ).'#text'
    $ip = ($data | Where-Object { $_.Name -eq 'IpAddress' } ).'#text'

    if ($target) { $users += $target }
    if ($ip -and $ip -ne '-' -and $ip -ne '::1' -and $ip -ne '0.0.0.0') { $ips += $ip }
}

Write-Host "Failed usernames:" -ForegroundColor Cyan
$users | Where-Object { $_ } | Sort-Object -Unique | ForEach-Object { Write-Host " - $_" }

Write-Host "`nFailed client IP addresses (with addr from whois.pconline.com.cn):" -ForegroundColor Cyan
$uniqueIps = $ips | Where-Object { $_ } | Sort-Object -Unique

# Write unique IPs to ips.csv in the same directory as the script (clear file first)
$scriptDir = if ($PSScriptRoot) { $PSScriptRoot } else { Split-Path -Parent $MyInvocation.MyCommand.Definition }
if (-not $scriptDir) { $scriptDir = (Get-Location).Path }
$outFile = Join-Path $scriptDir 'ips.csv'
try {
    # clear the file (create if missing)
    if (-not (Test-Path $outFile)) { New-Item -Path $outFile -ItemType File -Force | Out-Null }
    Set-Content -Path $outFile -Value $null -Encoding utf8 -ErrorAction Stop
} catch {
    # fallback: try to create/overwrite
    Out-File -FilePath $outFile -Encoding utf8 -Force | Out-Null
}

# write only the IPs, one per line
$uniqueIps | Out-File -FilePath $outFile -Encoding utf8 -Force
foreach ($ip in $uniqueIps) {
    $addr = 'N/A'
    try {
        $url = "http://whois.pconline.com.cn/ipJson.jsp?json=true&ip=$ip"
        # -UseBasicParsing helps on older Windows PowerShell versions
        $res = Invoke-RestMethod -Uri $url -UseBasicParsing -ErrorAction Stop
        if ($res -and $res.addr) { $addr = $res.addr }
    } catch {
        # ignore errors, leave addr as N/A
    }
    Write-Host (" - {0}  {1}" -f $ip, $addr)
}

运行结果:

Failed usernames:
 - -
 - ADMIN
 - ADMINISTRATOR

Failed client IP addresses (with addr from whois.pconline.com.cn):
 - 79.124.59.86   保加利亚
 - 93.123.109.72   保加利亚
posted @ 2025-10-13 10:51  d-_-b  阅读(11)  评论(0)    收藏  举报