@echo off
setlocal EnableDelayedExpansion
chcp 936 >nul 2>&1
title 网络检查与修复工具

:: ==============================
:: 管理员权限检查（不自动提权，避免闪退）
::                        By JingYang
:: ==============================
net session >nul 2>&1
if %errorlevel% neq 0 (
    echo ================================================
    echo  请以管理员身份运行本脚本
    echo ================================================
    echo.
    echo  操作方法：
    echo    1. 关闭本窗口
    echo    2. 右键点击本 .bat 文件
    echo    3. 选择“以管理员身份运行”
    echo.
    echo  按任意键退出...
    pause >nul
    exit /b
)

:: ==============================
:: 初始化
:: ==============================
set "LOG=%TEMP%\net_repair_log.txt"
set "HOSTS=%SystemRoot%\System32\drivers\etc\hosts"
set "needRepair="
set "hostsProblem="
set "probeDisabled="
set "proxyEnabled="

echo. >>"%LOG%"
echo ================================================ >>"%LOG%"
call :log "开始网络排查"

echo ================================================
echo  网络排查与修复工具
echo        By JingYang
echo ================================================
echo.
echo  日志文件: %LOG%
echo.
echo  按任意键显示当前网络配置 (ipconfig /all)...
pause >nul
echo.

:: ==============================
:: 开头完整输出 ipconfig /all
:: ==============================
echo ================================================
echo  当前网络配置 (ipconfig /all)
echo ================================================
echo.
ipconfig /all
echo.
echo ------------------------------------------------ >>"%LOG%"
echo [ipconfig /all] 修复前网络配置 >>"%LOG%"
ipconfig /all >>"%LOG%" 2>&1
echo ------------------------------------------------ >>"%LOG%"
echo.
echo  按任意键开始排查...
pause >nul
echo.

:: ==============================
:: 1. hosts 文件检查
:: ==============================
echo [排查 1/5] hosts 文件检查...
echo.

if not exist "%HOSTS%" (
    echo   [异常] hosts 文件不存在：%HOSTS%
    set "needRepair=1"
    set "hostsProblem=1"
    call :log "hosts 文件不存在"
    goto :check_probe
)

:: 用 PowerShell 检查是否屏蔽 Windows 探测域名
powershell -NoProfile -ExecutionPolicy Bypass -Command ^
  "$h='%HOSTS%'; $bad='msftconnecttest|msftncsi|captive\.apple|connectivitycheck';" ^
  "$lines = Get-Content -LiteralPath $h -ErrorAction SilentlyContinue;" ^
  "$blocked = $lines | Where-Object { $_ -match $bad -and $_ -notmatch '^\s*#' };" ^
  "if ($blocked) { Write-Host '  [异常] 发现屏蔽 Windows 探测域名的条目:'; $blocked | ForEach-Object { Write-Host ('    ' + $_) }; exit 1 } else { Write-Host '  [正常] 未发现屏蔽探测域名的条目'; exit 0 }"

if errorlevel 1 (
    set "needRepair=1"
    set "hostsProblem=1"
    call :log "hosts 存在屏蔽条目"
)

echo.
echo   hosts 中的自定义条目（非注释）:
powershell -NoProfile -ExecutionPolicy Bypass -Command ^
  "$h='%HOSTS%'; $c = Get-Content -LiteralPath $h -ErrorAction SilentlyContinue | Where-Object { $_ -match '^\s*[^#\s]' };" ^
  "if ($c) { $c | ForEach-Object { Write-Host ('    ' + $_) } } else { Write-Host '    （无）' }"
echo.

:check_probe
:: ==============================
:: 2. 系统主动探测开关
:: ==============================
echo [排查 2/5] 系统主动探测开关 (EnableActiveProbing)...
echo.

reg query "HKLM\SYSTEM\CurrentControlSet\Services\NlaSvc\Parameters\Internet" /v EnableActiveProbing >nul 2>&1
if errorlevel 1 (
    echo   [正常] 注册表项不存在（系统使用默认值=启用）
) else (
    set "probeVal="
    for /f "tokens=3" %%a in ('reg query "HKLM\SYSTEM\CurrentControlSet\Services\NlaSvc\Parameters\Internet" /v EnableActiveProbing 2^>nul ^| findstr /i "EnableActiveProbing"') do set "probeVal=%%a"
    if /i "!probeVal!"=="0x0" (
        echo   [异常] 系统主动探测已关闭 → 认证页面永远不会自动弹出
        set "needRepair=1"
        set "probeDisabled=1"
        call :log "EnableActiveProbing=0"
    ) else (
        echo   [正常] 系统主动探测已开启 (!probeVal!)
    )
)
echo.

:: ==============================
:: 3. 代理设置
:: ==============================
echo [排查 3/5] 系统/浏览器代理设置...
echo.

reg query "HKCU\Software\Microsoft\Windows\CurrentVersion\Internet Settings" /v ProxyEnable >nul 2>&1
if errorlevel 1 (
    echo   [正常] 未找到代理配置
) else (
    set "proxyVal="
    for /f "tokens=3" %%a in ('reg query "HKCU\Software\Microsoft\Windows\CurrentVersion\Internet Settings" /v ProxyEnable 2^>nul ^| findstr /i "ProxyEnable"') do set "proxyVal=%%a"
    if /i "!proxyVal!"=="0x1" (
        echo   [异常] 系统代理已启用 → 浏览器不会走网关，无法跳认证页
        reg query "HKCU\Software\Microsoft\Windows\CurrentVersion\Internet Settings" /v ProxyServer 2>nul | findstr /i "ProxyServer"
        set "needRepair=1"
        set "proxyEnabled=1"
        call :log "系统代理已启用"
    ) else (
        echo   [正常] 系统代理未启用
    )
)
echo.

:: ==============================
:: 4. DNS 服务器配置
:: ==============================
echo [排查 4/5] DNS 服务器配置...
echo.
for /f "tokens=2 delims=:" %%a in ('ipconfig /all ^| findstr /i "DNS Servers DNS 服务器"') do (
    echo    DNS: %%a
)
echo.

:: ==============================
:: 5. 基础连通性
:: ==============================
echo [排查 5/5] 基础连通性...
echo.

echo   [5.1] 本机回环...
ping -n 2 127.0.0.1 >nul 2>&1
if errorlevel 1 (
    echo         [异常] 本机回环失败
    set "needRepair=1"
) else (
    echo         [正常]
)

echo   [5.2] 默认网关...
set "GW="
for /f "tokens=3" %%a in ('route print 0.0.0.0 2^>nul ^| findstr /r /c:"^ *0\.0\.0\.0 "') do (
    if not defined GW set "GW=%%a"
)
if defined GW (
    echo         网关: !GW!
    ping -n 2 !GW! >nul 2>&1
    if errorlevel 1 (
        echo         [异常] 网关不可达
        set "needRepair=1"
    ) else (
        echo         [正常]
    )
) else (
    echo         [提示] 未检测到默认网关
)

echo   [5.3] DNS 解析...
nslookup www.baidu.com >nul 2>&1
if errorlevel 1 (
    echo         [异常] DNS 解析失败
    set "needRepair=1"
) else (
    echo         [正常]
)

echo   [5.4] Portal 探测域名 (仅提示，ping 不通是正常的)...
ping -n 2 www.msftconnecttest.com >nul 2>&1
if errorlevel 1 (
    echo         [提示] 无法 ping 通（通常正常，网关会拦截）
) else (
    echo         [正常] 可达
)
echo.

:: ==============================
:: 汇总与修复
:: ==============================
echo ================================================
echo  排查结果
echo ================================================
echo.
if defined hostsProblem  echo   * hosts 文件存在屏蔽条目
if defined probeDisabled echo   * 系统主动探测已关闭
if defined proxyEnabled  echo   * 系统代理已启用
if not defined needRepair echo   * 未发现明显问题
echo.

if defined needRepair (
    set "ans="
    set /p "ans=是否立即执行修复？(Y=修复，其他=跳过): "
    if /i "!ans!"=="Y" (
        call :repair
    ) else (
        echo 已跳过修复。
    )
) else (
    echo.
    echo 如果认证页面仍不弹出，请在浏览器中手动访问：
    echo    dh.qmsou.cn
    echo    www.gov.cn
    echo 若仍无效，问题可能出在网关/Portal 服务器侧，请联系 IT。
)

echo.
echo 日志文件: %LOG%
echo.
echo 按任意键退出...
pause >nul
exit /b

:: ==============================
:: 修复子程序
:: ==============================
:repair
echo.
echo ================================================
echo  开始修复...
echo ================================================
echo.

if defined hostsProblem (
    echo [修复 1/4] 清理 hosts 文件中的屏蔽条目...
    powershell -NoProfile -ExecutionPolicy Bypass -Command ^
      "$h='%HOSTS%'; $bad='msftconnecttest|msftncsi|captive\.apple|connectivitycheck';" ^
      "$bak = $h + '.bak_' + (Get-Date -Format 'yyyyMMdd_HHmmss');" ^
      "Copy-Item -LiteralPath $h -Destination $bak -Force;" ^
      "$lines = Get-Content -LiteralPath $h;" ^
      "$new = $lines | Where-Object { -not ($_ -match $bad -and $_ -notmatch '^\s*#') };" ^
      "Set-Content -LiteralPath $h -Value $new -Encoding ASCII;" ^
      "Write-Host ('    已清理，原文件备份为: ' + $bak)"
    call :log "已清理 hosts"
)

if defined probeDisabled (
    echo [修复 2/4] 重新开启系统主动探测...
    reg add "HKLM\SYSTEM\CurrentControlSet\Services\NlaSvc\Parameters\Internet" /v EnableActiveProbing /t REG_DWORD /d 1 /f >nul 2>&1
    echo     已设置为 1
    call :log "EnableActiveProbing=1"
)

if defined proxyEnabled (
    echo [修复 3/4] 关闭系统代理...
    reg add "HKCU\Software\Microsoft\Windows\CurrentVersion\Internet Settings" /v ProxyEnable /t REG_DWORD /d 0 /f >nul 2>&1
    echo     已关闭（浏览器可能需要重启）
    call :log "关闭系统代理"
)

echo [修复 4/4] 网络协议栈修复...
echo     - 刷新 DNS 缓存...
ipconfig /flushdns >nul 2>&1
echo     - 重置 Winsock...
netsh winsock reset >nul 2>&1
echo     - 重置 WinHTTP 代理...
netsh winhttp reset proxy >nul 2>&1
echo     （跳过 TCP/IP 重置，避免影响静态 IP 配置）
call :log "网络协议栈修复完成"

:: ==============================
:: 修复后再次完整输出 ipconfig /all
:: ==============================
echo.
echo ================================================
echo  修复后网络配置 (ipconfig /all)
echo ================================================
echo.
ipconfig /all
echo.
echo ------------------------------------------------ >>"%LOG%"
echo [ipconfig /all] 修复后网络配置 >>"%LOG%"
ipconfig /all >>"%LOG%" 2>&1
echo ------------------------------------------------ >>"%LOG%"

echo.
echo 修复完成。
echo.
echo 建议按以下顺序测试：
echo   1. 重启计算机
echo   2. 打开浏览器访问：http://www.msftconnecttest.com
echo   3. 如果弹出认证页面，正常认证即可
echo   4. 如果仍不弹出，请把日志文件发给 IT 部门
echo.
echo 日志文件: %LOG%
echo.
echo 按任意键返回...
pause >nul
exit /b

:: ==============================
:: 日志子程序
:: ==============================
:log
echo [%date% %time%] %~1 >>"%LOG%"
exit /b