Skip to content

Instantly share code, notes, and snippets.

@ak1ra-komj
Last active January 24, 2022 05:44
Show Gist options
  • Save ak1ra-komj/36db2449db75493932dfc14f925d4e0d to your computer and use it in GitHub Desktop.
Save ak1ra-komj/36db2449db75493932dfc14f925d4e0d to your computer and use it in GitHub Desktop.
# Author: ak1ra
# Date: 2022-01-23
# 自动添加访问特定域名时使用 OpenVPN 网关作为下一条的路由
# 配置命令行选项
Param(
[string]$Action = "add",
[string]$Domain = "cloud.tencent.com",
[Parameter(Mandatory=$false)][Int32]$InterfaceIndex,
[string]$InterfaceDescription = "TAP-Windows Adapter V9",
[string]$InterfaceAlias = "OpenVPN",
[string]$DestinationPrefix = "10.0.0.0/9"
)
# 配置临时文件保存域名解析记录
$ResolveResultSaved = "${Env:TEMP}\resolve_${Domain}.txt"
# 根据 InterfaceDescription 获取网卡
$TapNetAdapter = Get-NetAdapter -InterfaceDescription $InterfaceDescription
if ($PSBoundParameters.ContainsKey('InterfaceIndex')) {
# 直接使用命令行参数传入的 InterfaceIndex
$InterfaceIndex = $InterfaceIndex
} elseif (($TapNetAdapter | Measure-Object).Count -eq 1) {
# 通过 InterfaceDescription 获取网卡, 可能出现多个对象
# 因此仅当存在 1 个 TAP 网卡时才使用此方法
$InterfaceIndex = $TapNetAdapter.ifIndex
} else {
# 也直接传入 TAP 网卡名称, 默认值为 OpenVPN
$InterfaceIndex = (Get-NetAdapter -InterfaceAlias $InterfaceAlias).ifIndex
}
# 获取 OpenVPN 下发路由的下一跳地址
$NextHop = (Get-NetRoute -ifIndex $InterfaceIndex -DestinationPrefix $DestinationPrefix ).NextHop
# 查询 $Domain 的 A 记录并保存到文件(保存状态), 然后再读取循环添加路由
if ($Action -eq "Add") {
$ResolveResult = (Resolve-DnsName -Type A $Domain).ipAddress | Tee-Object -FilePath $ResolveResultSaved
$ResolveResult | ForEach-Object -Process {
New-NetRoute -DestinationPrefix "$_/32" -NextHop $NextHop -InterfaceIndex $InterfaceIndex
}
} elseif ($Action -match "(Del(ete)?|Remove)") {
$ResolveResult = Get-Content -Path $ResolveResultSaved
$ResolveResult | ForEach-Object -Process {
Remove-NetRoute -DestinationPrefix "$_/32" -NextHop $NextHop -InterfaceIndex $InterfaceIndex -Confirm:$false
}
Remove-Item -Path $ResolveResultSaved
} else {
Get-NetRoute -ifIndex $InterfaceIndex
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment