Su's Blog

Kratos
专注于用户阅读体验的响应式博客主题
  1. Main page
  2. Uncategorized
  3. Main content

add record to hosts file

April 1, 2026 5hotness 0likes 0comments

@echo off
setlocal enabledelayedexpansion

:: ===== 自动提权 =====
net session >nul 2>&1
if %errorlevel% neq 0 (
powershell -Command "Start-Process cmd -ArgumentList '/c %~f0' -Verb RunAs"
exit
)

:: ===== hosts 文件 =====
set "HOST_FILE=%SystemRoot%\System32\drivers\etc\hosts"
set "TMP_FILE=%HOST_FILE%.tmp"

:: ===== 去掉只读 =====
attrib -r "%HOST_FILE%"

:: ===== 拷贝原 hosts 到临时文件 =====
copy /Y "%HOST_FILE%" "%TMP_FILE%" >nul

:: ===== 要添加/更新的记录 =====
(
echo 127.0.0.1 www.2brightsparks.com
echo 127.0.0.1 dbinternal.2brightsparks.com
) > "%HOST_FILE%.list"

:: ===== 处理每条记录 =====
for /f "usebackq tokens=1,* delims= " %%i in ("%HOST_FILE%.list") do (
set "IP=%%i"
set "DOMAIN=%%j"

set "FOUND=0"
set "NEW_TMP=%TMP_FILE%.new"
if exist "!NEW_TMP!" del /f /q "!NEW_TMP!"

:: 遍历原临时文件
for /f "usebackq delims=" %%L in ("%TMP_FILE%") do (
set "LINE=%%L"
echo !LINE! | findstr /R /C:"[ ]!DOMAIN!" >nul
if !errorlevel! EQU 0 (
echo !IP! !DOMAIN!>>"!NEW_TMP!"
set "FOUND=1"
) else (
echo !LINE!>>"!NEW_TMP!"
)
)

:: 如果没有找到域名,追加
if !FOUND! EQU 0 (
echo !IP! !DOMAIN!>>"!NEW_TMP!"
)

move /Y "!NEW_TMP!" "%TMP_FILE%" >nul
echo Added/Updated !IP! !DOMAIN!
)

:: ===== 写回 hosts =====
move /Y "%TMP_FILE%" "%HOST_FILE%" >nul

:: ===== 删除临时 list =====
del /f /q "%HOST_FILE%.list"

:: ===== 恢复只读 =====
:: attrib +r "%HOST_FILE%"

:: ===== 刷新 DNS =====
ipconfig /flushdns

echo ==== Done ====
pause

Tag: Nothing
Last updated:April 1, 2026

Su

This person is a lazy dog and has left nothing

Like
< Last article

COPYRIGHT © 2024 Su's Blog. ALL RIGHTS RESERVED.

Theme Kratos Made By Seaton Jiang

We use cookies to ensure that we give you the best experience on our website. If you continue to use this site we will assume that you are happy with it.