$ErrorActionPreference = 'Stop'
$ipText = @"
10.10.103.31
10.10.103.61
"@
[string[]]$ipArry = $ipText.Split([char[]]"`r`n") | % { $_.Trim() } | ? { $_.Length -gt 0 }
# $ips = $ipTxt.Split([char[]]"`r`n") | % { $_.Trim() } | ? { $_.Length -gt 0 }
Write-Output "共有待处理 ip 数: $($ipArry.Length)"
Import-Module powershell-yaml
class YamlParser {
$yamlObject = $null
[void] load($filePath) {
$yamlContent = Get-Content -Path $filePath -Raw
$this.yamlObject = ConvertFrom-Yaml -Yaml $yamlContent
}
# 根据组名找出该组下的所有节点名称
[string[]] findProxyNamesByGroupName([string] $groupName) {
[array]$groups = $this.yamlObject['proxy-groups']
for ($idx = 0; $idx -lt $groups.Count; $idx++) {
$group = $groups[$idx]
# $name = $group['name']
if ($group['name'] -eq $groupName) {
$proxies = $group.proxies
return $proxies
}
}
return @()
}
[string] parseGroupName([string] $rule) {
# SRC-IP-CIDR,10.10.103.36/32,Relay-us-int-home-8
# 使用 , 进行拆分,然后取最后一个值
if ([string]::IsNullOrWhiteSpace($rule)) {
return $null
}
$ruleArray = $rule.Split(',')
$groupName = $ruleArray[-1]
return $groupName
}
[string] findRuleByIp([string] $ip) {
# 初始化结果变量
$result = $null
# 遍历 rules 部分
foreach ($rule in $this.yamlObject.rules) {
# 检查规则是否包含目标 IP 地址
if ($rule -match $ip) {
$result = $rule
break
}
}
# 输出结果
if ($result) {
Write-Output "找到匹配的规则: $result"
}
else {
Write-Output "未找到匹配的规则。"
}
return $result
}
}
$yamlFilePath = 'config.yml'
$parser = [YamlParser]::new()
$parser.load($yamlFilePath)
foreach ($ip in $ipArry) {
$rule = $parser.findRuleByIp($ip)
$group = $parser.parseGroupName($rule)
$proxies = $parser.findProxyNamesByGroupName($group)
$proxies = $proxies | ? { $_ -ne 'Gateway' }
$proxyNems = $proxies -join ','
# Write-Output "$ip 找到规则 $rule, 组名 $group, 节点名 $proxyNems"
Write-Output "$ip $group $($proxyNems)"
}