- mobile-web/:独立的 Vue3 + TS + WeUI 手机网页(开发端口 7303、预览 7304, /api 反代到后端 7300);node_modules/、dist/ 由根 .gitignore 统一覆盖 - tools/scan-web-viewer.ps1:扫局域网 80 端口并按网页标题匹配设备的排查脚本 Co-authored-by: Copilot <223556219+Copilot@users.noreply.github.com>
760 lines
31 KiB
PowerShell
760 lines
31 KiB
PowerShell
<#
|
||
.SYNOPSIS
|
||
扫描局域网内 80 端口开放、且网页标题匹配(默认 "Web Viewer")的设备;结果可核对、不漏扫。
|
||
|
||
.DESCRIPTION
|
||
不只是列出"开放的主机",而是给扫描范围内**每个地址**一个确定结论,避免漏扫:
|
||
|
||
1) 第一轮全量 TCP 探测 80(默认 800ms 快速失败),逐台记录状态:
|
||
Open(端口开)/ Refused(收到 RST,端口明确关闭)/ Timeout(无响应)/ Unreachable / Error;
|
||
2) 读 ARP 邻居表(第一轮已把整个网段 ARP 唤醒),得到"真实在线"的主机集合;
|
||
3) 对「在线但无响应」的主机做定向重试(更长超时 + 更低并发,默认再重试 2 轮);
|
||
若 ARP 完全不可用(跨网段等),退回对所有无响应主机重试;
|
||
4) 对 80 开放的主机抓 <title>:
|
||
/ →(空标题或 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)<meta[^>]+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[^>]*>(.*?)</title>') {
|
||
$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)<script[^>]+src\s*=\s*["'']([^"'']+)["'']')) {
|
||
$src = $m.Groups[1].Value
|
||
if ($src -match '^(https?:)?//') { continue }
|
||
$sources += $src
|
||
}
|
||
$sources = @($sources | Select-Object -Unique | Select-Object -First 2)
|
||
if ($sources.Count -eq 0) { return '' }
|
||
|
||
foreach ($src in $sources) {
|
||
$path = if ($src.StartsWith('/')) { $src } else { '/' + $src }
|
||
$resp = Invoke-Request -HostIp $HostIp -WebPort $WebPort -Path $path -TimeoutMs $TimeoutMs
|
||
if ($resp.State -ne 'Open' -or -not $resp.Body) { continue }
|
||
|
||
$match = [regex]::Match($resp.Body, '(?i)(?:document\.title|window\.title)\s*=\s*["'']([^"'']{1,120})["'']')
|
||
if (-not $match.Success) {
|
||
$match = [regex]::Match($resp.Body, '(?i)titletext\s*=\s*["'']([^"'']{1,120})["'']')
|
||
}
|
||
if ($match.Success) {
|
||
$value = ([System.Net.WebUtility]::HtmlDecode($match.Groups[1].Value) -replace '\s+', ' ').Trim()
|
||
if ($value) { return $value }
|
||
}
|
||
}
|
||
|
||
return ''
|
||
}
|
||
|
||
$watch = [System.Diagnostics.Stopwatch]::StartNew()
|
||
$first = $null
|
||
$lastOpen = $null
|
||
|
||
foreach ($path in $ProbePaths) {
|
||
if ($watch.ElapsedMilliseconds -gt $HostBudgetMs) { break }
|
||
|
||
$currentPath = $path
|
||
for ($hop = 0; $hop -le 2; $hop++) {
|
||
if ($watch.ElapsedMilliseconds -gt $HostBudgetMs) { break }
|
||
|
||
$resp = Invoke-Request -HostIp $Ip -WebPort $TargetPort -Path $currentPath -TimeoutMs $HttpTimeoutMs
|
||
|
||
if ($resp.State -ne 'Open') {
|
||
if (-not $first) {
|
||
return [pscustomobject]@{ Ip = $Ip; State = $resp.State; Status = 0; Title = ''; Server = ''; Size = 0; Path = '' }
|
||
}
|
||
break
|
||
}
|
||
|
||
if (-not $first) { $first = $resp }
|
||
$lastOpen = $resp
|
||
if ($resp.Title) {
|
||
return [pscustomobject]@{
|
||
Ip = $Ip; State = 'Open'; Status = $resp.Status; Title = $resp.Title
|
||
Server = $resp.Server; Size = $resp.Size; Path = $currentPath
|
||
}
|
||
}
|
||
|
||
# 同主机内跟随跳转
|
||
$next = $null
|
||
if (@(301, 302, 303, 307, 308) -contains $resp.Status -and $resp.Location) {
|
||
if ($resp.Location -match '^https?://([^/]+)(/.*)?$') {
|
||
if ($Matches[1] -eq $Ip) { $next = if ($Matches[2]) { $Matches[2] } else { '/' } }
|
||
} elseif ($resp.Location.StartsWith('/')) {
|
||
$next = $resp.Location
|
||
}
|
||
}
|
||
if (-not $next) { break }
|
||
$currentPath = $next
|
||
}
|
||
}
|
||
|
||
if ($first) {
|
||
$title = ''
|
||
$titlePath = ''
|
||
if ($ScanScripts -and $lastOpen -and $lastOpen.Body) {
|
||
$title = Get-ScriptTitle -HostIp $Ip -WebPort $TargetPort -Html $lastOpen.Body -TimeoutMs $HttpTimeoutMs
|
||
if ($title) { $titlePath = '(js)' }
|
||
}
|
||
return [pscustomobject]@{
|
||
Ip = $Ip; State = 'Open'; Status = $first.Status; Title = $title
|
||
Server = $first.Server; Size = $first.Size; Path = $titlePath
|
||
}
|
||
}
|
||
return [pscustomobject]@{ Ip = $Ip; State = 'Timeout'; Status = 0; Title = ''; Server = ''; Size = 0; Path = '' }
|
||
}
|
||
|
||
# ---------------------------------------------------------------- 扫描执行
|
||
|
||
function Invoke-ScanPass {
|
||
param(
|
||
[string[]]$Ips,
|
||
[int]$ThreadCount,
|
||
[int]$ConnectTimeout,
|
||
[int]$HttpTimeout,
|
||
[string]$Label
|
||
)
|
||
|
||
$pool = [runspacefactory]::CreateRunspacePool(1, [math]::Max(1, $ThreadCount))
|
||
$pool.Open()
|
||
|
||
$pending = New-Object System.Collections.ArrayList
|
||
$passResults = New-Object System.Collections.ArrayList
|
||
$total = $Ips.Count
|
||
$next = 0
|
||
$done = 0
|
||
$inFlight = [math]::Max(1, $ThreadCount) * 4
|
||
|
||
try {
|
||
while ($next -lt $total -or $pending.Count -gt 0) {
|
||
while (($next -lt $total) -and ($pending.Count -lt $inFlight)) {
|
||
$ip = $Ips[$next]
|
||
$ps = [powershell]::Create()
|
||
$ps.RunspacePool = $pool
|
||
[void]$ps.AddScript($worker).
|
||
AddArgument($ip).AddArgument($Port).AddArgument($ConnectTimeout).
|
||
AddArgument($HttpTimeout).AddArgument($Paths).AddArgument($HostBudgetMs).
|
||
AddArgument($scanScriptsEnabled)
|
||
[void]$pending.Add([pscustomobject]@{ PS = $ps; Handle = $ps.BeginInvoke(); Ip = $ip })
|
||
$next++
|
||
}
|
||
|
||
$finished = @($pending | Where-Object { $_.Handle.IsCompleted })
|
||
if ($finished.Count -eq 0) {
|
||
Start-Sleep -Milliseconds 40
|
||
continue
|
||
}
|
||
|
||
foreach ($job in $finished) {
|
||
$output = $null
|
||
try {
|
||
$output = $job.PS.EndInvoke($job.Handle)
|
||
} catch {
|
||
$output = [pscustomobject]@{ Ip = $job.Ip; State = 'Error'; Status = 0; Title = ''; Server = ''; Size = 0; Path = '' }
|
||
}
|
||
foreach ($item in $output) { [void]$passResults.Add($item) }
|
||
try { $job.PS.Dispose() } catch { }
|
||
[void]$pending.Remove($job)
|
||
$done++
|
||
}
|
||
|
||
Write-Progress -Activity ("{0}(端口 {1})" -f $Label, $Port) -Status ("{0}/{1}" -f $done, $total) `
|
||
-PercentComplete ([math]::Min(100, [int](100 * $done / $total)))
|
||
}
|
||
} finally {
|
||
Write-Progress -Activity ("{0}(端口 {1})" -f $Label, $Port) -Completed
|
||
foreach ($job in @($pending)) { try { $job.PS.Stop(); $job.PS.Dispose() } catch { } }
|
||
$pool.Close()
|
||
$pool.Dispose()
|
||
}
|
||
|
||
return @($passResults)
|
||
}
|
||
|
||
$results = @{}
|
||
|
||
Write-Host ("[pass] 第 1 轮:{0} 个地址" -f $targets.Count) -ForegroundColor Cyan
|
||
foreach ($r in (Invoke-ScanPass -Ips $targets -ThreadCount $Threads -ConnectTimeout $ConnectTimeoutMs `
|
||
-HttpTimeout $HttpTimeoutMs -Label '第 1 轮')) {
|
||
$results[$r.Ip] = $r
|
||
}
|
||
|
||
# ARP 存活表(第 1 轮已把整个网段唤醒)
|
||
$aliveMap = @{}
|
||
if ($arpUsable) {
|
||
$rawAlive = Get-AliveNeighbors
|
||
foreach ($ip in $targets) {
|
||
if ($rawAlive.ContainsKey($ip)) { $aliveMap[$ip] = $rawAlive[$ip] }
|
||
}
|
||
Write-Host ("[pass] ARP 表命中:{0} 台(含可能过期的条目)" -f $aliveMap.Count) -ForegroundColor DarkGray
|
||
|
||
# 没扫开的主机才需要复核存活;已经扫开的一定在线
|
||
$verifyList = @($targets | Where-Object {
|
||
($results[$_].State -ne 'Open') -and $aliveMap.ContainsKey($_)
|
||
})
|
||
if (-not $SkipAliveCheck -and $verifyList.Count -gt 0) {
|
||
Write-Host ("[pass] 复核存活(ICMP 触发 ARP 刷新):{0} 台" -f $verifyList.Count) -ForegroundColor DarkGray
|
||
$confirmed = Confirm-AliveHosts -Ips $verifyList
|
||
foreach ($ip in @($aliveMap.Keys)) {
|
||
if ($results[$ip].State -eq 'Open') { continue }
|
||
if (-not $confirmed.ContainsKey($ip)) { $aliveMap.Remove($ip) }
|
||
}
|
||
Write-Host ("[pass] 复核后在线:{0} 台" -f ($aliveMap.Count)) -ForegroundColor DarkGray
|
||
}
|
||
} else {
|
||
Write-Host '[pass] 目标网段不在本机直连范围内,ARP 存活判定不可用;无响应主机将全部重试' -ForegroundColor DarkYellow
|
||
}
|
||
|
||
# 定向重试:① 在线但没扫开的主机(可能只是慢);② 端口开但标题没取到的主机
|
||
$attempt = 0
|
||
$retryList = @($targets | Where-Object {
|
||
$r = $results[$_]
|
||
if ($r.State -eq 'Open') { -not $r.Title }
|
||
else { (-not $arpUsable) -or $aliveMap.ContainsKey($_) }
|
||
})
|
||
|
||
while ($attempt -lt $Retries -and $retryList.Count -gt 0) {
|
||
$attempt++
|
||
Write-Host ("[pass] 第 {0} 轮重试:{1} 台(未扫开的在线主机 + 标题未取到的开放主机)" -f ($attempt + 1), $retryList.Count) -ForegroundColor Cyan
|
||
|
||
$retryResults = Invoke-ScanPass -Ips $retryList -ThreadCount $RetryThreads `
|
||
-ConnectTimeout $RetryConnectTimeoutMs -HttpTimeout $RetryHttpTimeoutMs `
|
||
-Label ("第 {0} 轮" -f ($attempt + 1))
|
||
|
||
foreach ($r in $retryResults) {
|
||
$prev = $results[$r.Ip]
|
||
if ($r.State -eq 'Open' -and ($r.Title -or $prev.State -ne 'Open')) { $results[$r.Ip] = $r }
|
||
}
|
||
|
||
$retryList = @($retryList | Where-Object {
|
||
$r = $results[$_]
|
||
if ($r.State -eq 'Open') { -not $r.Title }
|
||
elseif ($arpUsable) { $aliveMap.ContainsKey($_) }
|
||
else { $true }
|
||
})
|
||
}
|
||
|
||
# ---------------------------------------------------------------- 汇总输出
|
||
|
||
$all = @()
|
||
foreach ($ip in ($targets | Sort-Object { ConvertTo-UInt32 ([System.Net.IPAddress]::Parse($_)) })) {
|
||
$r = $results[$ip]
|
||
$mac = ''
|
||
$isAlive = $false
|
||
if ($aliveMap.ContainsKey($ip)) {
|
||
$mac = [string]$aliveMap[$ip]
|
||
$isAlive = $true
|
||
}
|
||
# 端口扫开即视为在线(ARP 可能因跨网段/缓存缺失而没匹配到)
|
||
if ($r.State -eq 'Open') { $isAlive = $true }
|
||
$all += [pscustomobject]@{
|
||
Ip = $ip
|
||
State = $r.State
|
||
Status = $r.Status
|
||
Title = $r.Title
|
||
Server = $r.Server
|
||
Path = $r.Path
|
||
Size = $r.Size
|
||
Mac = $mac
|
||
Alive = $isAlive
|
||
}
|
||
}
|
||
|
||
$openHosts = @($all | Where-Object { $_.State -eq 'Open' })
|
||
$refusedHosts = @($all | Where-Object { $_.State -eq 'Refused' })
|
||
$silentAlive = @($all | Where-Object { $_.State -ne 'Open' -and $_.State -ne 'Refused' -and $_.Alive })
|
||
$silentOther = @($all | Where-Object { $_.State -ne 'Open' -and $_.State -ne 'Refused' -and -not $_.Alive })
|
||
$aliveHosts = @($all | Where-Object { $_.Alive })
|
||
|
||
$hits = @()
|
||
foreach ($h in $openHosts) {
|
||
if (-not $h.Title) { continue }
|
||
if (-not $TitleMatch) { $hits += $h; continue }
|
||
if ($h.Title -match $TitleMatch) { $hits += $h }
|
||
}
|
||
|
||
Write-Host ''
|
||
Write-Host ("===== 全量分类({0} 个地址)=====" -f $all.Count) -ForegroundColor Yellow
|
||
Write-Host (" ARP 在线:{0}" -f $(if ($arpUsable) { $aliveHosts.Count } else { 'n/a(非直连网段)' }))
|
||
Write-Host (" {0} 端口开放:{1}" -f $Port, $openHosts.Count)
|
||
Write-Host (" {0} 端口关闭(RST):{1}" -f $Port, $refusedHosts.Count)
|
||
Write-Host (" 在线但 {0} 无响应:{1}" -f $Port, $silentAlive.Count) -ForegroundColor DarkYellow
|
||
if ($arpUsable) {
|
||
Write-Host (" 未响应(判定不在线):{0}" -f $silentOther.Count)
|
||
} else {
|
||
Write-Host (" 未响应(非直连网段,无法判定是否在线):{0}" -f $silentOther.Count)
|
||
}
|
||
|
||
if ($openHosts.Count -gt 0) {
|
||
Write-Host ''
|
||
Write-Host '--- 端口开放的主机 ---' -ForegroundColor Yellow
|
||
$openHosts |
|
||
Select-Object @{N = 'IP'; E = { $_.Ip } },
|
||
@{N = 'MAC'; E = { $_.Mac } },
|
||
@{N = '状态'; E = { $_.Status } },
|
||
@{N = '标题'; E = { $_.Title } },
|
||
@{N = 'Server'; E = { $_.Server } } |
|
||
Format-Table -AutoSize
|
||
}
|
||
|
||
if ($silentAlive.Count -gt 0) {
|
||
Write-Host '--- 在线但端口无响应(需人工确认,可能被过滤/设备忙)---' -ForegroundColor DarkYellow
|
||
$silentAlive |
|
||
Select-Object @{N = 'IP'; E = { $_.Ip } }, @{N = 'MAC'; E = { $_.Mac } }, State |
|
||
Format-Table -AutoSize
|
||
}
|
||
|
||
$openNoTitle = @($openHosts | Where-Object { -not $_.Title })
|
||
if ($openNoTitle.Count -gt 0) {
|
||
Write-Host ("--- 端口开放但未取到标题({0} 台,可能非 HTML/标题由 JS 生成)---" -f $openNoTitle.Count) -ForegroundColor DarkYellow
|
||
$openNoTitle |
|
||
Select-Object @{N = 'IP'; E = { $_.Ip } }, @{N = 'MAC'; E = { $_.Mac } },
|
||
@{N = '状态'; E = { $_.Status } }, @{N = 'Server'; E = { $_.Server } } |
|
||
Format-Table -AutoSize
|
||
}
|
||
|
||
Write-Host ("===== 标题匹配 '{0}':{1} 台 =====" -f $TitleMatch, $hits.Count) -ForegroundColor Green
|
||
if ($hits.Count -eq 0) {
|
||
Write-Host '未发现匹配设备。' -ForegroundColor DarkYellow
|
||
} else {
|
||
foreach ($hit in $hits) {
|
||
Write-Host (" {0,-16} {1,-6} {2} ({3})" -f $hit.Ip, $hit.Status, $hit.Title, $hit.Path) -ForegroundColor Green
|
||
}
|
||
}
|
||
|
||
if ($CsvPath) {
|
||
$all |
|
||
Select-Object Ip, State, Alive, Mac, Status, Title, Server, Path, Size |
|
||
Export-Csv -Path $CsvPath -NoTypeInformation -Encoding UTF8
|
||
Write-Host ("已导出:{0}" -f $CsvPath) -ForegroundColor Cyan
|
||
}
|