Powershell to show and log SMTP Port 25, 465, 2525 after Decomission old Exchange Server
When decommissioning an Exchange Server, it’s common to install SMTP/IIS to capture and redirect the failing SMTP sender traffic, allowing us to monitor if there’s still traffic coming to the old Exchange.
Below is a PowerShell script that you can modify to display and log connections to specific SMTP and SMTPS ports, enabling you to track activity.
Typically, we redirect SMTP port 25 to the new Exchange or cloud and monitor sporadic incoming traffic on other ports like 587, 465, and 2525. The approach may vary depending on how the customer has secured internal SMTP flow.
Change $ports = @(587, 465, 2525) to you need and depending on what you have active allready running.
Capture and Log SMTP traffic to the host, SHOW if port is already BIND/BOUND to another app (We can’t monitor it in that case) |
# Define the ports to monitor $ports = @(587, 465, 2525)
# Define the logfile path $logfilePath = “logfile.txt”
# Create a TCP listener for each port $tcpListeners = @() foreach ($port in $ports) { $tcpListener = [System.Net.Sockets.TcpListener]::new([System.Net.IPAddress]::Any, $port) try { $tcpListener.Start() $tcpListeners += $tcpListener } catch { # If port is already in use, find the application using the port if ($_.Exception.Message -match ‘Only one usage of each socket address’) { $usedPort = $port $appUsingPort = @(Get-NetTCPConnection | Where-Object { $_.LocalPort -eq $usedPort } | Select-Object -ExpandProperty OwningProcess | Get-Process | Select-Object -ExpandProperty Path) if ($appUsingPort) { Write-Host “Port $usedPort is already in use by: $($appUsingPort)” } else { Write-Host “Port $usedPort is already in use, but the application couldn’t be identified.” } } } }
# Continuously listen for incoming connections while ($true) { foreach ($tcpListener in $tcpListeners) { if ($tcpListener -and $tcpListener.Pending()) { $client = $tcpListener.AcceptTcpClient() $stream = $client.GetStream() $localEndPoint = $client.Client.LocalEndPoint $targetPort = $localEndPoint.Port
# Display connection information on console $remoteEndPoint = $client.Client.RemoteEndPoint $sourceIP = $remoteEndPoint.Address Write-Host “Incoming connection from $($sourceIP):$($targetPort)”
# Log connection to the logfile with source IP and target port $logEntry = “$(Get-Date -Format ‘yyyy-MM-dd HH:mm:ss’) – Incoming connection from $($sourceIP):$($targetPort)” Add-Content -Path $logfilePath -Value $logEntry
$stream.Close() $client.Close() } } Start-Sleep -Milliseconds 1000 }
# Clean up foreach ($tcpListener in $tcpListeners) { if ($tcpListener) { $tcpListener.Stop() } } |
IF you mention or scan a port which is already mounted/bound by another application the code will show:
You can’t monitor add. existing PORTS that are used like 25 when SMTP IIS Service is running