#
.SYNOPSIS
扫描局域网内 80 端口开放、且网页标题匹配(默认 "Web Viewer")的设备;结果可核对、不漏扫。
.DESCRIPTION
不只是列出"开放的主机",而是给扫描范围内**每个地址**一个确定结论,避免漏扫:
1) 第一轮全量 TCP 探测 80(默认 800ms 快速失败),逐台记录状态:
Open(端口开)/ Refused(收到 RST,端口明确关闭)/ Timeout(无响应)/ Unreachable / Error;
2) 读 ARP 邻居表(第一轮已把整个网段 ARP 唤醒),得到"真实在线"的主机集合;
3) 对「在线但无响应」的主机做定向重试(更长超时 + 更低并发,默认再重试 2 轮);
若 ARP 完全不可用(跨网段等),退回对所有无响应主机重试;
4) 对 80 开放的主机抓
:
/ →(空标题或 4xx 时)依次补探 -Paths 中的常见登录页;同主机内跟随跳转;
按 header/meta 的 charset 解码(GB2312 中文页正常)。
网段与掩码:默认取本机每块网卡的真实前缀(如 192.168.11.56/22 → 192.168.8.0/22),
扫描范围严格限制在该网段的可用地址内(跳过网络地址/广播地址/本机地址),并打印出来便于核对。
输出会给出全量分类:80 开放 / 80 关闭 / 在线但 80 无响应 / 未响应(判定不在线),
其中「在线但 80 无响应」单独列出——这是最可能藏着设备的一类,需要人工确认。
.EXAMPLE
# 默认:按本机真实掩码扫所有网段,找标题含 Web Viewer 的设备
powershell -NoProfile -ExecutionPolicy Bypass -File tools\scan-web-viewer.ps1
.EXAMPLE
# 指定网段并导出明细
powershell -NoProfile -ExecutionPolicy Bypass -File tools\scan-web-viewer.ps1 `
-Network 192.168.8.0/22 -CsvPath D:\scan.csv
.EXAMPLE
# 更保守(慢但更稳):并发 16、首轮 1500ms、重试 3 轮
powershell -NoProfile -ExecutionPolicy Bypass -File tools\scan-web-viewer.ps1 `
-Threads 16 -ConnectTimeoutMs 1500 -Retries 3
.EXAMPLE
# 只看端口开放主机的标题(-TitleMatch 传空)
powershell -NoProfile -ExecutionPolicy Bypass -File tools\scan-web-viewer.ps1 -TitleMatch ''
#>
[CmdletBinding()]
param(
# 网段(CIDR 或单个 IP),可传多个;留空则自动取本机所有 IPv4 网段
[string[]]$Network = @(),
[int]$Port = 80,
# 标题匹配(正则,不区分大小写;传空表示端口开放且有标题的都算命中)
[string]$TitleMatch = 'Web Viewer',
# 探测路径,按顺序尝试,取第一个拿到标题的
[string[]]$Paths = @('/', '/doc/page/login.asp', '/login.asp', '/login.html', '/index.html'),
[int]$Threads = 64,
[int]$ConnectTimeoutMs = 800,
[int]$HttpTimeoutMs = 2500,
# 在线但首轮无响应时的定向重试轮数,以及重试用的超时/并发
[int]$Retries = 2,
[int]$RetryConnectTimeoutMs = 3000,
[int]$RetryHttpTimeoutMs = 5000,
[int]$RetryThreads = 32,
# 单机总耗时上限,防止慢设备把整轮扫描拖住
[int]$HostBudgetMs = 6000,
# 地址数上限,防手滑扫大段
[int]$MaxHosts = 8192,
# 默认跳过本机地址
[switch]$IncludeOwnHost,
# 跳过 ARP 存活复核(复核会额外发 ICMP,约每台 0.3s)
[switch]$SkipAliveCheck,
# 跳过 JS 标题兜底(首页标题为空时,去同源脚本里找 document.title = '...')
[switch]$SkipScriptTitle,
[string]$CsvPath
)
Set-StrictMode -Version 2.0
$ErrorActionPreference = 'Stop'
$scanScriptsEnabled = -not $SkipScriptTitle
# 兼容 -File 调用方式:-Network 可能被当成一个逗号分隔的字符串
$Network = @($Network | ForEach-Object { $_ -split ',' } | ForEach-Object { $_.Trim() } | Where-Object { $_ })
# ---------------------------------------------------------------- 地址计算
function ConvertTo-UInt32 {
param([System.Net.IPAddress]$Address)
$b = $Address.GetAddressBytes()
return ([uint64]$b[0] -shl 24) -bor ([uint64]$b[1] -shl 16) -bor ([uint64]$b[2] -shl 8) -bor [uint64]$b[3]
}
function ConvertFrom-UInt32 {
param([uint64]$Value)
return ('{0}.{1}.{2}.{3}' -f (($Value -shr 24) -band 255), (($Value -shr 16) -band 255), (($Value -shr 8) -band 255), ($Value -band 255))
}
function Expand-Cidr {
param([string]$Cidr)
if ($Cidr -notmatch '/') { $Cidr = "$Cidr/32" }
$parts = $Cidr.Split('/')
$address = [System.Net.IPAddress]::Parse($parts[0].Trim())
$prefix = [int]$parts[1]
if ($address.AddressFamily -ne [System.Net.Sockets.AddressFamily]::InterNetwork) {
throw "只支持 IPv4:$Cidr"
}
if ($prefix -lt 0 -or $prefix -gt 32) { throw "掩码非法:$Cidr" }
$hostBits = 32 - $prefix
$size = [uint64][math]::Pow(2, $hostBits)
$mask = [uint64]([math]::Pow(2, 32) - $size)
$network = (ConvertTo-UInt32 $address) -band $mask
$broadcast = $network + $size - 1
$start = if ($prefix -le 30) { $network + 1 } else { $network }
$end = if ($prefix -le 30) { $broadcast - 1 } else { $broadcast }
for ($i = $start; $i -le $end; $i++) { ConvertFrom-UInt32 $i }
}
function Get-NetworkInfo {
param([string]$Cidr)
if ($Cidr -notmatch '/') { $Cidr = "$Cidr/32" }
$parts = $Cidr.Split('/')
$address = [System.Net.IPAddress]::Parse($parts[0].Trim())
$prefix = [int]$parts[1]
if ($address.AddressFamily -ne [System.Net.Sockets.AddressFamily]::InterNetwork) {
throw "只支持 IPv4:$Cidr"
}
if ($prefix -lt 0 -or $prefix -gt 32) { throw "掩码非法:$Cidr" }
$hostBits = 32 - $prefix
$size = [uint64][math]::Pow(2, $hostBits)
$maskValue = [uint64]([math]::Pow(2, 32) - $size)
$network = (ConvertTo-UInt32 $address) -band $maskValue
$broadcast = $network + $size - 1
$first = if ($prefix -le 30) { $network + 1 } else { $network }
$last = if ($prefix -le 30) { $broadcast - 1 } else { $broadcast }
return [pscustomobject]@{
Cidr = ('{0}/{1}' -f (ConvertFrom-UInt32 $network), $prefix)
InterfaceIp = $address.ToString()
Prefix = $prefix
Mask = (ConvertFrom-UInt32 $maskValue)
Network = (ConvertFrom-UInt32 $network)
Broadcast = (ConvertFrom-UInt32 $broadcast)
First = (ConvertFrom-UInt32 $first)
Last = (ConvertFrom-UInt32 $last)
Count = [int]($last - $first + 1)
}
}
function Get-DefaultNetworks {
$found = New-Object System.Collections.Generic.List[string]
foreach ($nic in [System.Net.NetworkInformation.NetworkInterface]::GetAllNetworkInterfaces()) {
if ($nic.OperationalStatus -ne 'Up') { continue }
if ($nic.NetworkInterfaceType -eq 'Loopback') { continue }
$prefixes = @()
foreach ($u in $nic.GetIPProperties().UnicastAddresses) {
if ($u.Address.AddressFamily -ne [System.Net.Sockets.AddressFamily]::InterNetwork) { continue }
$ip = $u.Address.ToString()
if ($ip -like '127.*' -or $ip -like '169.254.*') { continue }
$prefixes += ('{0}/{1}' -f $ip, $u.PrefixLength)
}
if ($prefixes.Count -eq 0) { continue }
# 同一张网卡上的多个地址归并到它自己的网段,避免重复扫描
foreach ($cidr in ($prefixes | Select-Object -Unique)) {
$info = Get-NetworkInfo $cidr
if (-not $found.Contains($info.Cidr)) { $found.Add($info.Cidr) }
}
}
return @($found)
}
function Get-AliveNeighbors {
# 返回 @{ ip = mac }:ARP 表里"真实存在"的主机(用于判定漏扫、定向重试)
$alive = @{}
try {
foreach ($n in (Get-NetNeighbor -AddressFamily IPv4 -ErrorAction Stop)) {
if (-not $n.LinkLayerAddress) { continue }
$mac = ([string]$n.LinkLayerAddress).ToUpper()
if ($mac -eq '00-00-00-00-00-00') { continue }
if ($mac -match '^(FF-FF-FF-FF-FF-FF|01-00-5E-|33-33-)') { continue }
if ($n.State -eq 'Unreachable' -or $n.State -eq 'Incomplete') { continue }
$alive[[string]$n.IPAddress] = $mac
}
} catch { }
if ($alive.Count -eq 0) {
try {
foreach ($line in (& arp -a 2>$null)) {
$m = [regex]::Match($line, '^\s*(\d+\.\d+\.\d+\.\d+)\s+([0-9a-fA-F]{2}(-[0-9a-fA-F]{2}){5})')
if ($m.Success) {
$mac = $m.Groups[2].Value.ToUpper()
if ($mac -eq '00-00-00-00-00-00' -or $mac -match '^(FF-FF-FF-FF-FF-FF|01-00-5E-|33-33-)') { continue }
$alive[$m.Groups[1].Value] = $mac
}
}
} catch { }
}
return $alive
}
function Confirm-AliveHosts {
# ARP 表可能有过期条目:对候选主机先发一次 ICMP 触发 ARP 刷新,再读邻居状态复核
param([string[]]$Ips, [int]$ProbeWaitMs = 300)
$confirmed = @{}
if (-not $Ips -or $Ips.Count -eq 0) { return $confirmed }
foreach ($ip in $Ips) {
try { $null = & ping -n 1 -w $ProbeWaitMs $ip 2>$null } catch { }
}
Start-Sleep -Milliseconds 500
try {
foreach ($n in (Get-NetNeighbor -AddressFamily IPv4 -ErrorAction Stop)) {
$ip = [string]$n.IPAddress
if (-not ($Ips -contains $ip)) { continue }
if (-not $n.LinkLayerAddress) { continue }
$mac = ([string]$n.LinkLayerAddress).ToUpper()
if ($mac -eq '00-00-00-00-00-00') { continue }
if ($n.State -eq 'Unreachable' -or $n.State -eq 'Incomplete') { continue }
$confirmed[$ip] = $mac
}
} catch { }
return $confirmed
}
# ---------------------------------------------------------------- 目标网段
$ownIps = @()
foreach ($nic in [System.Net.NetworkInformation.NetworkInterface]::GetAllNetworkInterfaces()) {
foreach ($u in $nic.GetIPProperties().UnicastAddresses) {
if ($u.Address.AddressFamily -eq [System.Net.Sockets.AddressFamily]::InterNetwork) {
$ownIps += $u.Address.ToString()
}
}
}
$localNetworks = @(Get-DefaultNetworks)
if ($Network.Count -eq 0) { $Network = $localNetworks }
if ($Network.Count -eq 0) { throw '没有找到可扫描的 IPv4 网段,请用 -Network 指定,例如 192.168.1.0/24' }
# 统一按网卡真实掩码归一化成「网络地址/掩码」,扫描范围就是该网段的可用地址
$networkInfos = @()
foreach ($cidr in $Network) {
$info = Get-NetworkInfo $cidr
if (-not ($networkInfos | Where-Object { $_.Cidr -eq $info.Cidr })) { $networkInfos += $info }
}
$Network = @($networkInfos | ForEach-Object { $_.Cidr })
# 目标网段是否都在本机直连段内(决定 ARP 存活判定是否可信)
# 注意:显式传入的子网(如 192.168.8.0/24)只要落在本机 192.168.8.0/22 内,ARP 同样可用
$localInfos = @(foreach ($cidr in $localNetworks) { Get-NetworkInfo $cidr })
$arpUsable = $true
foreach ($info in $networkInfos) {
$covered = $false
foreach ($local in $localInfos) {
$childFirst = ConvertTo-UInt32 ([System.Net.IPAddress]::Parse($info.Network))
$childLast = ConvertTo-UInt32 ([System.Net.IPAddress]::Parse($info.Broadcast))
$parentFirst = ConvertTo-UInt32 ([System.Net.IPAddress]::Parse($local.Network))
$parentLast = ConvertTo-UInt32 ([System.Net.IPAddress]::Parse($local.Broadcast))
if (($childFirst -ge $parentFirst) -and ($childLast -le $parentLast)) {
$covered = $true
break
}
}
if (-not $covered) { $arpUsable = $false }
}
Write-Host '[net] 本机网段(按网卡真实掩码):' -ForegroundColor Cyan
foreach ($info in $networkInfos) {
Write-Host (" {0,-20} 掩码 {1,-16} 可用 {2} - {3} ({4} 个地址)" -f
$info.Cidr, $info.Mask, $info.First, $info.Last, $info.Count) -ForegroundColor DarkCyan
}
if (-not $IncludeOwnHost) {
Write-Host ("[net] 跳过本机地址:{0}" -f ($ownIps -join ', ')) -ForegroundColor DarkGray
}
$targets = New-Object System.Collections.Generic.List[string]
foreach ($cidr in $Network) {
foreach ($ip in (Expand-Cidr $cidr)) {
if (-not $IncludeOwnHost -and ($ownIps -contains $ip)) { continue }
if (-not $targets.Contains($ip)) { $targets.Add($ip) }
}
}
$targets = @($targets)
if ($targets.Count -gt $MaxHosts) {
throw ("目标地址 {0} 个,超过上限 {1}。请缩小 -Network 或调大 -MaxHosts。" -f $targets.Count, $MaxHosts)
}
Write-Host ("[scan] 网段 {0} → {1} 个地址,端口 {2},标题匹配 '{3}'" -f
($Network -join ', '), $targets.Count, $Port, $TitleMatch) -ForegroundColor Cyan
Write-Host ("[scan] 首轮 并发 {0} / 连接超时 {1}ms;重试 {2} 轮 / 并发 {3} / 连接超时 {4}ms" -f
$Threads, $ConnectTimeoutMs, $Retries, $RetryThreads, $RetryConnectTimeoutMs) -ForegroundColor DarkGray
Write-Host ("[scan] 探测路径:{0}" -f ($Paths -join ' ')) -ForegroundColor DarkGray
# ---------------------------------------------------------------- 单机探测
$worker = {
param($Ip, $TargetPort, $ConnectTimeoutMs, $HttpTimeoutMs, $ProbePaths, $HostBudgetMs, $ScanScripts)
function Invoke-Request {
param($HostIp, $WebPort, $Path, $TimeoutMs)
$client = New-Object System.Net.Sockets.TcpClient
$state = 'Timeout'
try {
$iar = $client.BeginConnect($HostIp, $WebPort, $null, $null)
if ($iar.AsyncWaitHandle.WaitOne($ConnectTimeoutMs)) {
try {
$client.EndConnect($iar)
$state = 'Open'
} catch {
$socketError = $null
if ($_.Exception.InnerException -is [System.Net.Sockets.SocketException]) {
$socketError = $_.Exception.InnerException.SocketErrorCode
} elseif ($_.Exception -is [System.Net.Sockets.SocketException]) {
$socketError = $_.Exception.SocketErrorCode
}
switch ([string]$socketError) {
'ConnectionRefused' { $state = 'Refused' }
'HostUnreachable' { $state = 'Unreachable' }
'NetworkUnreachable' { $state = 'Unreachable' }
'TimedOut' { $state = 'Timeout' }
default { $state = 'Error' }
}
}
}
} catch {
$state = 'Error'
}
if ($state -ne 'Open') {
try { $client.Close() } catch { }
return [pscustomobject]@{ State = $state; Status = 0; Title = ''; Server = ''; Location = ''; Size = 0; Body = '' }
}
$status = 0
$title = ''
$server = ''
$location = ''
$size = 0
$body = ''
try {
$client.ReceiveTimeout = $TimeoutMs
$client.SendTimeout = $TimeoutMs
$stream = $client.GetStream()
$stream.ReadTimeout = $TimeoutMs
$stream.WriteTimeout = $TimeoutMs
$request = "GET $Path HTTP/1.1`r`n" +
"Host: $HostIp`r`n" +
"User-Agent: Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36`r`n" +
"Accept: text/html,application/xhtml+xml,*/*`r`n" +
"Accept-Language: zh-CN,zh;q=0.9`r`n" +
"Connection: close`r`n`r`n"
$bytes = [System.Text.Encoding]::ASCII.GetBytes($request)
$stream.Write($bytes, 0, $bytes.Length)
$stream.Flush()
$buffer = New-Object byte[] 8192
$memory = New-Object System.IO.MemoryStream
while ($memory.Length -lt 262144) {
try {
$read = $stream.Read($buffer, 0, $buffer.Length)
} catch {
break
}
if ($read -le 0) { break }
$memory.Write($buffer, 0, $read)
}
$size = [int]$memory.Length
$latin1 = [System.Text.Encoding]::GetEncoding(28591)
$all = $memory.ToArray()
$text = $latin1.GetString($all)
$split = $text.IndexOf("`r`n`r`n")
if ($split -lt 0) {
$head = $text
$bodyOffset = $all.Length
} else {
$head = $text.Substring(0, $split)
$bodyOffset = $split + 4
}
if ($head -match '^HTTP/\d\.\d\s+(\d{3})') { $status = [int]$Matches[1] }
if ($head -match '(?im)^Server:\s*(.+?)\s*$') { $server = $Matches[1] }
if ($head -match '(?im)^Location:\s*(.+?)\s*$') { $location = $Matches[1] }
# header / meta 里声明的 charset,中文固件常见 gb2312
$charset = $null
if ($head -match '(?i)charset\s*=\s*["'']?([\w\-]+)') {
$charset = $Matches[1]
} elseif ($bodyOffset -lt $all.Length) {
$bodyProbe = $latin1.GetString($all, $bodyOffset, [math]::Min(2048, $all.Length - $bodyOffset))
if ($bodyProbe -match '(?i)]+charset\s*=\s*["'']?([\w\-]+)') { $charset = $Matches[1] }
}
$encoding = [System.Text.Encoding]::UTF8
if ($charset) {
try {
if ($charset -match '(?i)^(gb2312|gbk|gb18030|x-gbk)$') {
$encoding = [System.Text.Encoding]::GetEncoding(936)
} elseif ($charset -notmatch '(?i)^utf-?8$') {
$encoding = [System.Text.Encoding]::GetEncoding($charset)
}
} catch { }
}
if ($bodyOffset -lt $all.Length) {
$decoded = $encoding.GetString($all, $bodyOffset, $all.Length - $bodyOffset)
$body = $decoded
if ($decoded -match '(?is)]*>(.*?)') {
$title = (([System.Net.WebUtility]::HtmlDecode($Matches[1])) -replace '\s+', ' ').Trim()
}
}
} catch {
# 端口开着但不是 HTTP,或读超时
} finally {
try { $client.Close() } catch { }
}
return [pscustomobject]@{ State = 'Open'; Status = $status; Title = $title; Server = $server; Location = $location; Size = $size; Body = $body }
}
function Get-ScriptTitle {
# 首页标题为空时,跟同源脚本里的 document.title = '...' / titletext = '...'
param($HostIp, $WebPort, $Html, $TimeoutMs)
if (-not $Html) { return '' }
$sources = @()
foreach ($m in [regex]::Matches($Html, '(?is)