Windows环境下,使用bat脚本配置本地域名解析(含新增、修改、清理)

适用场景:
1.内部不存在DNS服务器的客户;
2.客户电脑不知道前期是否过某域名的本地解析。

整体思路:
1.备份原始hosts配置文件;
2.将hosts配置文件中包含xxxxxxxxxx.com域名的解析清空;
3.写入正确的解析到hosts配置文件。

保存及运行:
保存时编码格式需设置为:ANSI
在这里插入图片描述
运行时,需要适用右键-以管理员身份运行

@echo off
setlocal enabledelayedexpansion
chcp 65001

set "DATE=%date:~3,4%%date:~8,2%%date:~11,2%"
set "HOUR=%time:~0,2%"
rem 处理1~9点时间显示一位问题
if "%time:~0,1%"==" " set HOUR=0%time:~1,1%
set "MINUTE=%time:~3,2%"
set "SECOND=%time:~6,2%"
set "DATE_TIME=%DATE%%HOUR%%MINUTE%%SECOND%"

xcopy C:\Windows\system32\drivers\etc\hosts C:\Windows\system32\drivers\etc\hosts-%DATE_TIME%.bak\ /d /c /i /y
:: 备份hhosts文件

set "input_file=C:\Windows\System32\drivers\etc\hosts"
set "output_file=C:\Windows\System32\drivers\etc\temp.txt"

if exist "%output_file%" del "%output_file%"
:: 如果已存在temp.txt则删除

:: 核心代码,判断是否包含域名,包含则将该行清空
for /f "tokens=* delims=" %%a in ('type "%input_file%"') do (
    set "line=%%a"
	echo !line! | findstr /i "xxxxxxxxxx.com">nul &&(
		set "line="
	)
    echo(!line!>>"%output_file%"
)
:: 核心代码,判断是否包含域名,包含则将该行清空

move /y "%output_file%" "%input_file%"
:: 用temp.txt替换原hosts文件
if exist "%output_file%" del "%output_file%"
:: 清理创建的临时文件
endlocal
:: 释放变量

:: 重新写入本地域名解析
echo 211.139.xx.xxx oazt.xxxxxxxxxx.com oa.xxxxxxxxxx.com >> C:\Windows\System32\drivers\etc\hosts
:: 刷新DNS缓存
ipconfig /flushdns
exit
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值