Script : tester les ports TCP et UDP en PowerShell

ci-joint un petit script permettant de faire des tests des ports UDP et TCP. La version présente ici teste les ports spécifiques un client Active Directory, mais vous pouvez l’adapter. Le script est une adaptation de différentes bonnes idées trouvées sur le web (la partie UDP provenant directement du technet).

Note : le protocole ICMP est requis pour le test UDP (cmdlet test-connection).
Param ([Parameter(Mandatory=$True)][String]$Server)

#/.Variables
$FontKO = @{ ForeGroundColor = "Red"    ; BackGroundColor = "Black" }
$FontWN = @{ ForeGroundColor = "Yellow" ; BackGroundColor = "Black" }
$FontOK = @{ ForeGroundColor = "Green"  ; BackGroundColor = "Black" }
$Tcp = $false

#/.Fonction Test-Port
Function Test-Port
{
    Param(  
    [Parameter(ParameterSetName='ByName'   ,Position=0)][String]$CptrName,
    [Parameter(ParameterSetName='ByAddress',Position=0)][system.Net.IpAddress]$CptrAddr,
    [Parameter(Mandatory=$true,Position=1)][int]$Port,
    [Parameter(Mandatory=$true,Position=2)][ValidateSet("TCP","UDP")][String]$Protocol
    )
    
    $RemoteCptr = If ([string]::IsNullOrEmpty($CptrName)) {$CptrAddr} Else {$cptrName}
    
    Switch ($Protocol) 
    {
        "TCP" 
        {
            Try {       
                $error.Clear()
                $socket  = New-Object System.Net.Sockets.TcpClient
                $connect = $socket.BeginConnect($RemoteCptr,$Port,$null,$null)
                $TimeOut = $connect.AsyncWaitHandle.WaitOne(1000,$false)
                if ($TimeOut) 
                { 
                    $socket.EndConnect($connect) | Out-Null
                    $Result = New-Object PsObject -Property @{status=$true ;message=$null}
                } else {
                    $Result = New-Object PsObject -Property @{status=$false;message="Time Out reached"}
                }
            
            } Catch {
                $Result = New-Object PsObject -Property @{status=$false;message=$error.message}
            
            } Finally { 
                $socket.Dispose()
            }
        }
        "UDP" 
        {
            $error.Clear()
            $udpObject = New-Object System.Net.Sockets.UdpClient
            $udpobject.client.ReceiveTimeout = 1000
            $Asciiencd = New-Object System.Text.ASCIIEncoding
            $MsgToByte = $Asciiencd.GetBytes("$(Get-Date)")
            $udpObject.Connect("$RemoteCptr",$port)
            [void]$udpObject.Send($MsgToByte,$MsgToByte.Length)
            $TrgtEndPoint = New-Object System.Net.IPEndPoint([System.Net.IPAddress]::Any,0)
            Try
            {
                $ReceiveBytes = $udpObject.Receive([ref]$TrgtEndPoint)
                [string]$returnData = $Asciiencd.GetString($ReceiveBytes)
                if ($returnData) { $Result = New-Object PsObject -Property @{status=$true ;message=$null} }
                $udpObject.Close()
                                  
            } catch {
                 $errMsg = $error[0].ToString()
                 if ($errMsg -match "\bRespond after a period of time\b" -or $errMsg -match "\bpas répondu convenablement au-delà d’une certaine durée\b")
                 {
                    $udpObject.Close()
                    if (Test-Connection -ComputerName $RemoteCptr -Count 1 -Quiet)
                    {
                        $Result = New-Object PsObject -Property @{status=$true ;message=$null}
                    } else {
                        $Result = New-Object PsObject -Property @{status=$false;message="host down or port not listening"}
                    }
                 } 
                 elseif ($errMsg -match "forcibly closed by the the mremote host" -or $errMsg -match "force par l'h" ) 
                 {
                    $Result = New-Object PsObject -Property @{status=$false;message="time Out reached"}
                 } else {
                    $Result = New-Object PsObject -Property @{status=$false;message=$errMsg }
                 }
            }

        }
    }
    return $result
}

#/.Definition des ports
$TcpList = @(53,135,139,445,464,636,3268,3269,9389)
$UdpList = @(53,88,123,135,137,138,389,445,464,3268,3269)

Write-Host "=====================" -ForegroundColor Yellow
Write-Host "  TESTING TCP PORTS  " -ForegroundColor Green
Write-Host "=====================" -ForegroundColor Yellow

foreach ($TcpTgt in $TcpList)
{
    $msg = "$Server - TCP - $Tcptgt"
    Write-Host -NoNewline "$msg `t: " 
    $Res = Test-Port -CptrName $Server -Port $Tcptgt -Protocol "TCP"
    if ($Res.status) { Write-Host "OK" @FontOK } else { Write-Host "KO - $($Res.Message)" @FontKO }
}

Write-Host "=====================" -ForegroundColor Yellow
Write-Host "  TESTING UDP PORTS  " -ForegroundColor Green
Write-Host "=====================" -ForegroundColor Yellow

foreach ($UdpTgt in $UdpList)
{
    $msg = "$Server - UDP - $UdpTgt" 
    Write-Host -NoNewline "$msg `t: " 
    $Res = Test-Port -CptrName $Server -port $UdpTgt -protocol "UDP"
    if ($Res.status) { Write-Host "OK" @FontOK } else { Write-Host "KO - $($Res.Message)" @FontKO }
}

Lien Permanent pour cet article : https://ms-sec.fr/?p=2879

Laisser un commentaire

Your email address will not be published.

Ce site utilise Akismet pour réduire les indésirables. En savoir plus sur comment les données de vos commentaires sont utilisées.