chore: 入库手机网页(mobile-web)与局域网扫描脚本(tools)

- 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>
This commit is contained in:
liufumingren 2026-11-01 03:43:43 +08:00
parent 73ee020025
commit 6e52f82cde
16 changed files with 3459 additions and 0 deletions

12
mobile-web/README.md Normal file
View File

@ -0,0 +1,12 @@
# PackService 手机网页
独立的 Vue 3 + TypeScript + WeUI 手机网页,开发端口默认为 `7303`,预览端口为 `7304`。
```powershell
npm install
npm run dev
```
开发服务器会将 `/api` 请求代理到 `http://127.0.0.1:7300`。可通过 `VITE_BACKEND` 更改后端地址,通过 `VITE_MOBILE_PORT` 更改开发端口。
执行 `npm run build` 生成 `dist/`。路由使用 HTML5 History 模式,生产部署时需将 `/login`、`/home`、`/profile` 等前端路径回退到 `index.html`,并将 `/api` 请求转发至后端。

13
mobile-web/index.html Normal file
View File

@ -0,0 +1,13 @@
<!doctype html>
<html lang="zh-CN">
<head>
<meta charset="UTF-8" />
<meta name="viewport" content="width=device-width, initial-scale=1.0, viewport-fit=cover" />
<meta name="theme-color" content="#f5f7fb" />
<title>PackService</title>
</head>
<body>
<div id="app"></div>
<script type="module" src="/src/main.ts"></script>
</body>
</html>

1723
mobile-web/package-lock.json generated Normal file

File diff suppressed because it is too large Load Diff

23
mobile-web/package.json Normal file
View File

@ -0,0 +1,23 @@
{
"name": "pack-service-mobile-web",
"version": "1.0.0",
"private": true,
"type": "module",
"scripts": {
"dev": "vite",
"build": "vue-tsc --noEmit && vite build",
"preview": "vite preview",
"typecheck": "vue-tsc --noEmit"
},
"dependencies": {
"vue": "^3.5.44",
"vue-router": "^5.4.0",
"weui": "^2.6.20"
},
"devDependencies": {
"@vitejs/plugin-vue": "^6.0.10",
"typescript": "^5.9.3",
"vite": "^8.3.4",
"vue-tsc": "^3.3.13"
}
}

3
mobile-web/src/App.vue Normal file
View File

@ -0,0 +1,3 @@
<template>
<RouterView />
</template>

View File

@ -0,0 +1,24 @@
<script setup lang="ts">
import { useRoute } from 'vue-router';
const route = useRoute();
</script>
<template>
<nav class="bottom-nav" aria-label="底部导航">
<RouterLink class="nav-item" :class="{ active: route.name === 'home' }" to="/home">
<svg viewBox="0 0 24 24" aria-hidden="true">
<path d="m3.5 10 8.5-7 8.5 7v9a1.5 1.5 0 0 1-1.5 1.5h-14A1.5 1.5 0 0 1 3.5 19z" />
<path d="M9 20.5v-7h6v7" />
</svg>
<span>首页</span>
</RouterLink>
<RouterLink class="nav-item" :class="{ active: route.name === 'profile' }" to="/profile">
<svg viewBox="0 0 24 24" aria-hidden="true">
<circle cx="12" cy="8" r="3.5" />
<path d="M4.5 21a7.5 7.5 0 0 1 15 0" />
</svg>
<span>我的</span>
</RouterLink>
</nav>
</template>

7
mobile-web/src/main.ts Normal file
View File

@ -0,0 +1,7 @@
import { createApp } from 'vue';
import App from './App.vue';
import { router } from './router';
import 'weui/dist/style/weui.min.css';
import './styles.css';
createApp(App).use(router).mount('#app');

42
mobile-web/src/router.ts Normal file
View File

@ -0,0 +1,42 @@
import { createRouter, createWebHistory } from 'vue-router';
import { getToken } from './types';
declare module 'vue-router' {
interface RouteMeta {
requiresAuth?: boolean;
guestOnly?: boolean;
}
}
export const router = createRouter({
history: createWebHistory(),
routes: [
{ path: '/', redirect: () => (getToken() ? '/home' : '/login') },
{
path: '/login',
name: 'login',
component: () => import('./views/LoginView.vue'),
meta: { guestOnly: true },
},
{
path: '/home',
name: 'home',
component: () => import('./views/HomeView.vue'),
meta: { requiresAuth: true },
},
{
path: '/profile',
name: 'profile',
component: () => import('./views/ProfileView.vue'),
meta: { requiresAuth: true },
},
{ path: '/:pathMatch(.*)*', redirect: '/' },
],
});
router.beforeEach((to) => {
const loggedIn = Boolean(getToken());
if (to.meta.requiresAuth && !loggedIn) return { name: 'login' };
if (to.meta.guestOnly && loggedIn) return { name: 'home' };
return true;
});

568
mobile-web/src/styles.css Normal file
View File

@ -0,0 +1,568 @@
:root {
font-family: -apple-system, BlinkMacSystemFont, "Segoe UI", "PingFang SC", "Hiragino Sans GB",
"Microsoft YaHei", sans-serif;
color: #17233b;
background: #f5f7fb;
font-synthesis: none;
text-rendering: optimizeLegibility;
-webkit-font-smoothing: antialiased;
-moz-osx-font-smoothing: grayscale;
font-weight: 400;
}
* {
box-sizing: border-box;
}
html,
body,
#app {
width: 100%;
min-width: 0;
min-height: 100%;
margin: 0;
}
body {
min-height: 100vh;
min-height: 100dvh;
overflow-x: hidden;
background: #f5f7fb;
}
button,
input {
font: inherit;
}
button,
a {
-webkit-tap-highlight-color: transparent;
}
a {
color: inherit;
text-decoration: none;
}
.page-shell,
.app-page {
width: 100%;
max-width: 480px;
min-height: 100vh;
min-height: 100dvh;
margin: 0 auto;
overflow-x: clip;
background: #f5f7fb;
}
.login-page {
display: flex;
flex-direction: column;
justify-content: center;
padding: 48px 24px max(32px, env(safe-area-inset-bottom));
background:
radial-gradient(ellipse at 95% 4%, rgb(91 128 255 / 13%), transparent 42%),
#f5f7fb;
}
.login-brand {
margin-bottom: 32px;
}
.brand-mark {
display: grid;
width: 54px;
height: 54px;
place-items: center;
border-radius: 18px;
background: linear-gradient(140deg, #6e8eff, #4162e8);
box-shadow: 0 12px 24px rgb(65 98 232 / 25%);
color: #fff;
font-size: 28px;
font-weight: 800;
}
.eyebrow {
margin: 0 0 10px;
color: #8490a8;
font-size: 10px;
font-weight: 700;
letter-spacing: 0.18em;
}
.login-brand .eyebrow {
margin-top: 24px;
}
.login-brand h1,
.home-header h1,
.page-title h1 {
margin: 0;
color: #182440;
font-size: 27px;
font-weight: 750;
letter-spacing: -0.04em;
}
.muted {
margin: 9px 0 0;
color: #8993a8;
font-size: 14px;
}
.login-card {
padding: 8px 18px 20px;
border: 1px solid #edf0f7;
border-radius: 20px;
background: #fff;
box-shadow: 0 14px 40px rgb(36 57 112 / 6%);
}
.login-fields {
margin-top: 0;
}
.login-fields::before,
.login-fields::after,
.login-fields .weui-cell::before {
border-color: #edf0f5;
}
.login-fields .weui-cell {
min-height: 58px;
padding: 10px 0;
}
.login-fields .weui-label {
width: 52px;
color: #424e67;
font-size: 14px;
}
.login-fields .weui-input {
min-width: 0;
color: #17233b;
font-size: 14px;
}
.login-fields .weui-input::placeholder {
color: #b0b7c5;
}
.form-error {
margin: 12px 0 0;
color: #d94b4b;
font-size: 13px;
line-height: 1.5;
}
.login-button {
height: 48px;
margin-top: 24px;
border-radius: 12px;
background: #4d6ff0;
font-size: 15px;
font-weight: 650;
line-height: 48px;
}
.login-button:not(.weui-btn_disabled):active {
background: #3e5fdd;
}
.login-footnote {
margin: 22px 0 0;
color: #a0a9ba;
font-size: 12px;
text-align: center;
}
.app-page {
display: flex;
flex-direction: column;
}
.page-content {
flex: 1;
min-width: 0;
padding: max(28px, env(safe-area-inset-top)) 20px 24px;
}
.home-content {
padding-top: max(38px, env(safe-area-inset-top));
}
.home-header {
display: flex;
align-items: center;
justify-content: space-between;
gap: 12px;
margin-bottom: 27px;
}
.home-header h1 {
font-size: 23px;
}
.home-header .muted {
font-size: 13px;
}
.avatar-badge,
.profile-avatar {
display: grid;
flex: 0 0 auto;
place-items: center;
border-radius: 50%;
background: #e8edff;
color: #4e6be1;
font-weight: 700;
}
.avatar-badge {
width: 48px;
height: 48px;
font-size: 20px;
}
.welcome-card {
position: relative;
display: flex;
min-height: 172px;
align-items: center;
justify-content: space-between;
overflow: hidden;
padding: 24px 20px;
border-radius: 22px;
background: linear-gradient(120deg, #4968e9, #6687f6);
box-shadow: 0 16px 30px rgb(77 111 240 / 21%);
color: #fff;
}
.welcome-copy {
position: relative;
z-index: 1;
max-width: 70%;
}
.welcome-tag {
display: inline-block;
padding: 5px 9px;
border: 1px solid rgb(255 255 255 / 34%);
border-radius: 20px;
background: rgb(255 255 255 / 13%);
font-size: 10px;
}
.welcome-copy h2 {
margin: 15px 0 6px;
font-size: 21px;
font-weight: 700;
}
.welcome-copy p {
margin: 0;
color: rgb(255 255 255 / 78%);
font-size: 12px;
line-height: 1.6;
}
.welcome-orbit {
position: absolute;
top: 50%;
right: -17px;
display: grid;
width: 132px;
height: 132px;
place-items: center;
transform: translateY(-50%);
border: 1px solid rgb(255 255 255 / 21%);
border-radius: 50%;
background: rgb(255 255 255 / 9%);
}
.welcome-orbit::before {
position: absolute;
width: 92px;
height: 92px;
border: 1px solid rgb(255 255 255 / 25%);
border-radius: 50%;
content: "";
}
.welcome-orbit span {
color: rgb(255 255 255 / 48%);
font-size: 42px;
font-weight: 800;
}
.section-block {
margin-top: 31px;
}
.section-heading {
display: flex;
align-items: baseline;
justify-content: space-between;
margin-bottom: 14px;
}
.section-heading h2 {
margin: 0;
font-size: 17px;
font-weight: 700;
}
.section-heading span {
color: #a6afbf;
font-size: 9px;
font-weight: 700;
letter-spacing: 0.12em;
}
.quick-card {
display: flex;
min-height: 78px;
align-items: center;
gap: 13px;
padding: 13px 15px;
border: 1px solid #edf0f7;
border-radius: 16px;
background: #fff;
}
.quick-icon {
display: grid;
width: 44px;
height: 44px;
flex: 0 0 auto;
place-items: center;
border-radius: 14px;
background: #edf1ff;
color: #5472ec;
}
.quick-icon svg,
.nav-item svg {
width: 22px;
height: 22px;
fill: none;
stroke: currentColor;
stroke-linecap: round;
stroke-linejoin: round;
stroke-width: 1.8;
}
.quick-copy {
display: flex;
min-width: 0;
flex: 1;
flex-direction: column;
gap: 5px;
}
.quick-copy strong {
font-size: 14px;
}
.quick-copy small {
color: #929caf;
font-size: 11px;
}
.chevron,
.profile-arrow {
color: #aeb6c5;
font-size: 24px;
line-height: 1;
}
.tip-card {
display: flex;
gap: 10px;
margin-top: 16px;
padding: 15px;
border-radius: 15px;
background: #edf2ff;
}
.tip-dot {
width: 7px;
height: 7px;
flex: 0 0 auto;
margin-top: 5px;
border-radius: 50%;
background: #6482f1;
}
.tip-card strong {
color: #435dba;
font-size: 12px;
}
.tip-card p {
margin: 5px 0 0;
color: #7180ad;
font-size: 11px;
line-height: 1.6;
}
.page-title {
margin-bottom: 25px;
}
.page-title h1 {
font-size: 25px;
}
.profile-card {
display: flex;
min-width: 0;
align-items: center;
gap: 14px;
padding: 21px 17px;
border-radius: 19px;
background: linear-gradient(120deg, #4968e9, #6687f6);
box-shadow: 0 14px 28px rgb(77 111 240 / 18%);
color: #fff;
}
.profile-avatar {
width: 54px;
height: 54px;
border: 2px solid rgb(255 255 255 / 64%);
background: rgb(255 255 255 / 20%);
color: #fff;
font-size: 22px;
}
.profile-identity {
min-width: 0;
flex: 1;
}
.profile-identity h2 {
overflow: hidden;
margin: 0;
font-size: 17px;
text-overflow: ellipsis;
white-space: nowrap;
}
.profile-identity p {
margin: 6px 0 0;
color: rgb(255 255 255 / 77%);
font-size: 11px;
}
.profile-arrow {
color: rgb(255 255 255 / 68%);
}
.profile-details {
margin-top: 17px;
padding: 4px 16px;
border: 1px solid #edf0f7;
border-radius: 17px;
background: #fff;
}
.detail-row {
display: flex;
min-width: 0;
min-height: 52px;
align-items: center;
justify-content: space-between;
gap: 12px;
border-bottom: 1px solid #f0f2f7;
font-size: 13px;
}
.detail-row:last-child {
border-bottom: 0;
}
.detail-row span {
flex: 0 0 auto;
color: #858fa3;
}
.detail-row strong {
overflow: hidden;
color: #27344d;
font-size: 12px;
font-weight: 550;
text-align: right;
text-overflow: ellipsis;
white-space: nowrap;
}
.logout-button {
height: 47px;
margin-top: 25px;
border: 1px solid #e8ebf2;
border-radius: 12px;
background: #fff;
color: #d64e58;
font-size: 14px;
line-height: 45px;
}
.logout-button:not(.weui-btn_disabled):active {
background: #fff7f7;
color: #bf3d47;
}
.bottom-nav {
position: sticky;
z-index: 5;
bottom: 0;
display: flex;
width: 100%;
min-height: 62px;
justify-content: space-around;
padding: 8px 24px max(8px, env(safe-area-inset-bottom));
border-top: 1px solid #edf0f5;
background: rgb(255 255 255 / 96%);
backdrop-filter: blur(12px);
}
.nav-item {
display: flex;
min-width: 76px;
flex-direction: column;
align-items: center;
gap: 3px;
color: #9ba4b5;
font-size: 10px;
}
.nav-item.active {
color: #4d6ff0;
}
.nav-item svg {
width: 21px;
height: 21px;
}
@media (max-width: 360px) {
.login-page {
padding-right: 18px;
padding-left: 18px;
}
.page-content {
padding-right: 16px;
padding-left: 16px;
}
.welcome-copy {
max-width: 76%;
}
.welcome-orbit {
right: -40px;
}
}

35
mobile-web/src/types.ts Normal file
View File

@ -0,0 +1,35 @@
export interface MobileUser {
id: number;
username?: string | null;
nickname?: string | null;
email?: string | null;
phone?: string | null;
avatar?: string | null;
}
export interface LoginResult {
token: string;
user: MobileUser;
}
export function readUser(): MobileUser | null {
try {
const stored = localStorage.getItem('packs_user');
return stored ? (JSON.parse(stored) as MobileUser) : null;
} catch {
return null;
}
}
export function getToken(): string {
return localStorage.getItem('packs_token') || '';
}
export function clearSession(): void {
localStorage.removeItem('packs_token');
localStorage.removeItem('packs_user');
}
export function getDisplayName(user: MobileUser | null): string {
return user?.nickname || user?.username || (user ? `用户 ${user.id}` : '访客');
}

View File

@ -0,0 +1,61 @@
<script setup lang="ts">
import { computed } from 'vue';
import BottomNav from '../components/BottomNav.vue';
import { getDisplayName, readUser } from '../types';
const user = readUser();
const nickname = computed(() => getDisplayName(user));
</script>
<template>
<div class="app-page">
<main class="page-content home-content">
<header class="home-header">
<div>
<p class="eyebrow">PACK SERVICE</p>
<h1>你好,{{ nickname }}</h1>
<p class="muted">今天也为你准备好了</p>
</div>
<div class="avatar-badge" aria-hidden="true">{{ nickname.slice(0, 1) }}</div>
</header>
<section class="welcome-card">
<div class="welcome-copy">
<span class="welcome-tag">移动工作台</span>
<h2>让服务更简单</h2>
<p>在这里查看你的账户与服务信息</p>
</div>
<div class="welcome-orbit" aria-hidden="true"><span>P</span></div>
</section>
<section class="section-block" aria-labelledby="quick-title">
<div class="section-heading">
<h2 id="quick-title">快捷入口</h2>
<span>QUICK ACCESS</span>
</div>
<RouterLink class="quick-card" to="/profile">
<span class="quick-icon account-icon" aria-hidden="true">
<svg viewBox="0 0 24 24">
<circle cx="12" cy="8" r="3.5" />
<path d="M4.5 21a7.5 7.5 0 0 1 15 0" />
</svg>
</span>
<span class="quick-copy">
<strong>个人中心</strong>
<small>查看和管理个人资料</small>
</span>
<span class="chevron" aria-hidden="true">›</span>
</RouterLink>
</section>
<section class="tip-card">
<span class="tip-dot" aria-hidden="true"></span>
<div>
<strong>温馨提示</strong>
<p>请妥善保管账号和密码,保护账户安全。</p>
</div>
</section>
</main>
<BottomNav />
</div>
</template>

View File

@ -0,0 +1,92 @@
<script setup lang="ts">
import { reactive, ref } from 'vue';
import { useRouter } from 'vue-router';
import type { LoginResult } from '../types';
const router = useRouter();
const form = reactive({ account: '', password: '' });
const busy = ref(false);
const error = ref('');
async function submit(): Promise<void> {
error.value = '';
if (!form.account.trim() || !form.password) {
error.value = '请输入账号和密码';
return;
}
busy.value = true;
try {
const response = await fetch('/api/web/auth/login', {
method: 'POST',
headers: { 'Content-Type': 'application/json' },
body: JSON.stringify({ account: form.account.trim(), password: form.password }),
});
const payload = (await response.json()) as {
ok: boolean;
data?: LoginResult;
message?: string;
};
if (!response.ok || !payload.ok || !payload.data?.token || !payload.data.user) {
throw new Error(payload.message || '登录失败,请检查账号和密码');
}
localStorage.setItem('packs_token', payload.data.token);
localStorage.setItem('packs_user', JSON.stringify(payload.data.user));
await router.replace('/home');
} catch (cause) {
error.value = cause instanceof Error ? cause.message : '网络异常,请稍后重试';
} finally {
busy.value = false;
}
}
</script>
<template>
<main class="login-page page-shell">
<div class="login-brand">
<div class="brand-mark" aria-hidden="true">P</div>
<p class="eyebrow">PACK SERVICE</p>
<h1>欢迎回来</h1>
<p class="muted">登录账号,继续使用 PackService</p>
</div>
<form class="login-card" @submit.prevent="submit">
<div class="weui-cells weui-cells_form login-fields">
<div class="weui-cell">
<div class="weui-cell__hd"><label class="weui-label" for="account">账号</label></div>
<div class="weui-cell__bd">
<input
id="account"
v-model="form.account"
class="weui-input"
autocomplete="username"
placeholder="用户名 / 手机号 / 邮箱"
required
/>
</div>
</div>
<div class="weui-cell">
<div class="weui-cell__hd"><label class="weui-label" for="password">密码</label></div>
<div class="weui-cell__bd">
<input
id="password"
v-model="form.password"
class="weui-input"
type="password"
autocomplete="current-password"
placeholder="请输入密码"
required
/>
</div>
</div>
</div>
<p v-if="error" class="form-error" role="alert">{{ error }}</p>
<button class="weui-btn weui-btn_primary login-button" type="submit" :disabled="busy">
{{ busy ? '正在登录…' : '登录' }}
</button>
</form>
<p class="login-footnote">安全登录 · 账号信息仅用于身份验证</p>
</main>
</template>

View File

@ -0,0 +1,57 @@
<script setup lang="ts">
import { useRouter } from 'vue-router';
import BottomNav from '../components/BottomNav.vue';
import { clearSession, getDisplayName, readUser } from '../types';
const router = useRouter();
const user = readUser();
function logout(): void {
clearSession();
void router.replace('/login');
}
</script>
<template>
<div class="app-page">
<main class="page-content profile-content">
<header class="page-title">
<p class="eyebrow">ACCOUNT</p>
<h1>我的</h1>
</header>
<section class="profile-card">
<div class="profile-avatar" aria-hidden="true">{{ getDisplayName(user).slice(0, 1) }}</div>
<div class="profile-identity">
<h2>{{ getDisplayName(user) }}</h2>
<p>PackService 用户</p>
</div>
<span class="profile-arrow" aria-hidden="true">›</span>
</section>
<section class="profile-details">
<div class="detail-row">
<span>用户名</span>
<strong>{{ user?.username || '未设置' }}</strong>
</div>
<div class="detail-row">
<span>手机号</span>
<strong>{{ user?.phone || '未绑定' }}</strong>
</div>
<div class="detail-row">
<span>邮箱</span>
<strong>{{ user?.email || '未绑定' }}</strong>
</div>
<div class="detail-row">
<span>用户编号</span>
<strong>{{ user?.id ?? '—' }}</strong>
</div>
</section>
<button class="weui-btn weui-btn_default logout-button" type="button" @click="logout">
退出登录
</button>
</main>
<BottomNav />
</div>
</template>

19
mobile-web/tsconfig.json Normal file
View File

@ -0,0 +1,19 @@
{
"compilerOptions": {
"target": "ES2022",
"useDefineForClassFields": true,
"module": "ESNext",
"lib": ["ES2022", "DOM", "DOM.Iterable"],
"skipLibCheck": true,
"moduleResolution": "Bundler",
"allowImportingTsExtensions": true,
"resolveJsonModule": true,
"isolatedModules": true,
"verbatimModuleSyntax": true,
"noEmit": true,
"strict": true,
"noUnusedLocals": true,
"noUnusedParameters": true
},
"include": ["src/**/*.ts", "src/**/*.vue"]
}

21
mobile-web/vite.config.ts Normal file
View File

@ -0,0 +1,21 @@
import { defineConfig } from 'vite';
import vue from '@vitejs/plugin-vue';
const backend = process.env.VITE_BACKEND || 'http://127.0.0.1:7300';
export default defineConfig({
plugins: [vue()],
server: {
host: '127.0.0.1',
port: Number(process.env.VITE_MOBILE_PORT || 7303),
strictPort: true,
proxy: {
'/api': { target: backend, changeOrigin: true },
},
},
preview: {
host: '127.0.0.1',
port: Number(process.env.VITE_MOBILE_PREVIEW_PORT || 7304),
strictPort: true,
},
});

759
tools/scan-web-viewer.ps1 Normal file
View File

@ -0,0 +1,759 @@
<#
.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
}