param( [string]$CIDR = "" ) function Get-DefaultCIDR { $ipObj = Get-NetIPAddress -AddressFamily IPv4 | Where-Object { $_.IPAddress -notlike "169.254*" -and $_.IPAddress -ne "127.0.0.1" -and $_.PrefixOrigin -ne "WellKnown" } | Sort-Object -Property InterfaceMetric | Select-Object -First 1 if (-not $ipObj) { return "192.168.1.0/24" } $ip = $ipObj.IPAddress $prefix = $ipObj.PrefixLength # Netzadresse grob berechnen $bytes = $ip.Split(".") | ForEach-Object { [int]$_ } $maskBits = $prefix $mask = @(0,0,0,0) for ($i=0; $i -lt 4; $i++) { $b = [Math]::Min(8, $maskBits) $maskBits -= $b $mask[$i] = if ($b -le 0) { 0 } else { (0xFF -shl (8-$b)) -band 0xFF } } $net = @() for ($i=0; $i -lt 4; $i++) { $net += ($bytes[$i] -band $mask[$i]) } return ("{0}.{1}.{2}.{3}/{4}" -f $net[0],$net[1],$net[2],$net[3],$prefix) } if (-not $CIDR -or $CIDR.Trim() -eq "") { $CIDR = Get-DefaultCIDR } # Check nmap $nmap = (Get-Command nmap -ErrorAction SilentlyContinue) if (-not $nmap) { Write-Host "FEHLER: nmap ist nicht installiert. Bitte installieren: https://nmap.org/download.html" -ForegroundColor Red exit 1 } $OutDir = Join-Path $PSScriptRoot ("lan-scan-" + (Get-Date -Format "yyyy-MM-dd_HH-mm-ss")) New-Item -ItemType Directory -Force -Path $OutDir | Out-Null $XmlPath = Join-Path $OutDir "scan.xml" $JsonPath = Join-Path $OutDir "scan.json" $CsvPath = Join-Path $OutDir "scan.csv" Write-Host "Scan läuft: $CIDR" & nmap -sn -n $CIDR -oX $XmlPath | Out-Null [xml]$xml = Get-Content $XmlPath $hosts = @() foreach ($h in $xml.nmaprun.host) { $status = $h.status.state if ($status -ne "up") { continue } $ip = "" $mac = "" $vendor = "" foreach ($a in $h.address) { if ($a.addrtype -eq "ipv4") { $ip = $a.addr } if ($a.addrtype -eq "mac") { $mac = $a.addr; $vendor = $a.vendor } } $name = "" if ($h.hostnames -and $h.hostnames.hostname) { $name = $h.hostnames.hostname[0].name } $hosts += [pscustomobject]@{ ip = $ip name = $name mac = $mac vendor = $vendor } } $payload = [pscustomobject]@{ ok = $true cidr = $CIDR scanned_at = (Get-Date).ToString("s") count = $hosts.Count hosts = $hosts } $payload | ConvertTo-Json -Depth 5 | Out-File -Encoding UTF8 $JsonPath $hosts | Export-Csv -NoTypeInformation -Encoding UTF8 -Delimiter ";" -Path $CsvPath Write-Host "Fertig. Dateien:" Write-Host " $JsonPath" Write-Host " $CsvPath"