Last active
November 29, 2023 10:19
-
-
Save jinmiaoluo/6a8eb9176bac7f06eaf6fa8ba6866a37 to your computer and use it in GitHub Desktop.
Windows NRPT PowerShell 管理脚本,用于实现 Windows 平台的 DNS 分流
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
# 作用: | |
# | |
# 将特定的域名及其所有子域名的 DNS 解析请求,通过指定的 DNS 服务器进行解析,即 DNS 分流 | |
# | |
# 请在 PowerShell 管理员权限下运行,用法如下: | |
# | |
# 将脚本保存为 nrpt.ps1 文件 | |
# | |
# 在脚本所在目录内创建 domains.txt 文件,将需要分流的域名,每个域名一行添加到文件内,比如 | |
# | |
# example-01.com | |
# example-02.com | |
# example-03.com | |
# | |
# 更新本地 NRPT 规则(你可能需要改动脚本中指定的 DNS 服务器 IP 地址) | |
# .\nrpt.ps1 | |
# | |
# 下面是一些其他的用法(如果你只是为了配置 NRPT 规则,到这里就可以了) | |
# | |
# 查看本地 NRPT 规则 | |
# .\nrpt.ps1 -Action Get | |
# | |
# 指定 NameServer 地址(而不是使用脚本中默认的 192.168.188.1) | |
# .\nrpt.ps1 -NameServer "10.0.0.2" | |
# | |
# 指定文件地址(而不是使用脚本中默认的 .\domains.txt 文件) | |
# .\nrpt.ps1 -FilePath ".\another-domains.txt" | |
# | |
# 清除所有规则(恢复默认的状态) | |
# .\nrpt.ps1 -Action Clean | |
param ( | |
[string]$Action = "Add", # 默认动作是添加规则,可以是 Add 或 Clean 或 Get | |
[string]$FilePath = ".\domains.txt", # 包含域名的文件路径 | |
[string]$NameServer = "192.168.188.1" # 分流将使用的 DNS 服务器地址 | |
) | |
function Manage-NrptRuleFromFile { | |
param ( | |
[string]$Action, | |
[string]$FilePath, | |
[string]$NameServer | |
) | |
# 读取文件中的域名,添加前缀 '.' | |
$fileNamespaces = Get-Content $FilePath | Where-Object { $_.Trim() -ne '' } | ForEach-Object { "." + $_ } | |
switch ($Action) { | |
"Get" { | |
$rules = Get-DnsClientNrptRule | |
if ($rules) { | |
Write-Host "Current NRPT rules:" | |
$rules | Format-Table -Property Namespace, NameServers | |
} else { | |
Write-Host "No NRPT rules found" | |
} | |
} | |
"Add" { | |
# 获取当前所有的NRPT规则 | |
$currentRules = Get-DnsClientNrptRule | |
# 添加或更新规则 | |
foreach ($ns in $fileNamespaces) { | |
$rule = $currentRules | Where-Object { $_.Namespace -eq $ns } | |
if ($rule) { | |
if ($rule.NameServers -ne $NameServer) { | |
Set-DnsClientNrptRule -Name $rule.Name -NameServers $NameServer | |
Write-Host "Updated NRPT rule for $ns" | |
} | |
} else { | |
Add-DnsClientNrptRule -Namespace $ns -NameServers $NameServer | |
Write-Host "Added NRPT rule for $ns" | |
} | |
} | |
# 清除不在文件中的规则 | |
$currentRules | Where-Object { $fileNamespaces -notcontains $_.Namespace } | ForEach-Object { | |
Remove-DnsClientNrptRule -Name $_.Name | |
Write-Host "Removed NRPT rule for $($_.Namespace)" | |
} | |
} | |
"Clean" { | |
Get-DnsClientNrptRule | Remove-DnsClientNrptRule -Force | |
Write-Host "Cleaned all NRPT rules" | |
} | |
default { | |
Write-Host "Invalid action: $Action" | |
} | |
} | |
} | |
# 调用 Manage-NrptRuleFromFile 函数 | |
Manage-NrptRuleFromFile -Action $Action -FilePath $FilePath -NameServer $NameServer |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment