windows-rdp-login-alert/login-notication.ps1

64 lines
1.8 KiB
PowerShell

# =============================
# LOGIN LOGGER
# =============================
# --- Initialization ---
$time = Get-Date -Format "yyyy-MM-dd HH:mm:ss"
$username = $env:USERNAME
$hostname = $env:COMPUTERNAME
$remoteIp = "Unknown"
$asnInfo = ""
$locationInfo = ""
$logPath = "C:\<YOUR_DIRECTORY>\log.txt"
$ntfyUrl = "<your_ntfy_instance>"
# --- Try to Get RDP Connection Info ---
try {
$queryOutput = query session
$activeLine = $queryOutput | Where-Object { $_ -match "$username" -and $_ -match "Active" }
if ($activeLine) {
# Normalize spacing and extract session ID
$clean = $activeLine -replace '\s{2,}', ' '
$parts = $clean.Split(' ')
$sessionId = $parts[2]
# Find established remote connections on RDP port
$rdpConns = Get-NetTCPConnection -LocalPort 3389 -State Established
foreach ($conn in $rdpConns) {
if ($conn.RemoteAddress -ne "127.0.0.1" -and $conn.RemoteAddress -ne "::1") {
$remoteIp = $conn.RemoteAddress
break
}
}
# --- IP Info Lookup ---
if ($remoteIp -ne "Unknown") {
$ipInfo = Invoke-RestMethod -Uri "https://ipinfo.io/$remoteIp/json"
if ($ipInfo) {
$asnInfo = $ipInfo.org
$locationInfo = "$($ipInfo.city), $($ipInfo.region), $($ipInfo.country)"
}
}
}
} catch {
$remoteIp = "Error: $($_.Exception.Message)"
}
# --- Construct Final Message ---
$eventMessage = @"
Time: [$time]
Who: $username logged into $hostname
From: $remoteIp
ASN: $asnInfo
Location: $locationInfo
"@
# --- Write to Log File ---
$eventMessage | Out-File $logPath -Append
# --- Send to NTFY ---
Invoke-RestMethod -Uri $ntfyUrl -Method Post -Body $eventMessage