Script :
$subnet = "192.168.1"
$ports = @(80, 21) # Array delle porte da controllare
$csvPath = "c:\temp\Scansione_Rete.csv"
# Inizializza l'array per il file CSV
$results = [System.Collections.Generic.List[PSCustomObject]]::new()
Write-Host "Scansione della rete $subnet.1 -$subnet.254 in corso..." -ForegroundColor Cyan
Write-Host "Controllo porte aperte: $($ports -join ', ')" -ForegroundColor Cyan
Write-Host "I risultati saranno salvati in: $csvPath`n" -ForegroundColor Yellow
1..254 | ForEach-Object {
$ip = "$subnet.$_"
$ping = New-Object System.Net.NetworkInformation.Ping
try {
$reply = $ping.Send($ip, 100) # Timeout di 100ms
if ($reply.Status -eq "Success") {
# Risoluzione Nome Host
try {
$hostName = [System.Net.Dns]::GetHostEntry($ip).HostName
} catch {
$hostName = "N/D"
}
# Controllo delle porte nell'array
$openPorts = foreach ($port in $ports) {
$socket = New-Object System.Net.Sockets.TcpClient
try {
$connect = $socket.BeginConnect($ip, $port, $null, $null)
$success = $connect.AsyncWaitHandle.WaitOne(150, $false) # Timeout 150ms per porta
if ($success -and $socket.Connected) {
$port
}
} catch {
} finally {
$socket.Close()
}
}
$openPortsStr = if ($openPorts) { $openPorts -join ", " } else { "Nessuna" }
# Output a video in tempo reale
Write-Host "[ATTIVO] IP: $ip | Hostname: $hostName | Porte aperte: $openPortsStr" -ForegroundColor Green
# Creazione oggetto per il CSV
$obj = [PSCustomObject]@{
IP = $ip
Hostname = $hostName
PorteAperte = $openPortsStr
}
$results.Add($obj)
}
} catch {}
}
# Esportazione finale in CSV (con codifica UTF8)
$results | Export-Csv -Path $csvPath -NoTypeInformation -Encoding UTF8
Write-Host "`nScansione completata! File CSV salvato in: $csvPath" -ForegroundColor Cyan

