这种输出长的,咱们用老办法,生成json后我上传到我的网站,然后给你文件链接去查看
gcloud compute firewall-rules list --project=analytical-poet-512206-q0 --filter="name~deny-au" --format="table(name,direction,priority,network,targetTags,disabled)"
gcloud compute firewall-rules describe deny-au-10 --project=analytical-poet-512206-q0 --format=json | Out-File -FilePath "$env:USERPROFILE\Desktop\deny-au-10.json" -Encoding utf8
gcloud compute firewall-rules describe deny-au-egress-10 --project=analytical-poet-512206-q0 --format=json | Out-File -FilePath "$env:USERPROFILE\Desktop\deny-au-egress-10.json" -Encoding utf8
sudo python3 - <<'PY'
import json
from pathlib import Path
p = Path("/etc/cidr-firewall-updater/update.py.candidate")
out = Path("/tmp/au-updater-full-review.json")
out.write_text(json.dumps({
"file": str(p),
"content": p.read_text()
}, ensure_ascii=False, indent=2) + "\n")
print(f"已生成:{out}")
print(f"文件大小:{out.stat().st_size} 字节")
PY
sudo chmod 644 /tmp/au-updater-review.json
sudo python3 - <<'PY'
import json
import urllib.request
from pathlib import Path
url = (
"http://metadata.google.internal/computeMetadata/v1/"
"instance/service-accounts/default/token"
)
req = urllib.request.Request(url, headers={"Metadata-Flavor": "Google"})
with urllib.request.urlopen(req, timeout=10) as r:
token = json.load(r)["access_token"]
api = (
"https://compute.googleapis.com/compute/v1/projects/"
"analytical-poet-512206-q0/global/firewalls"
)
req = urllib.request.Request(
api, headers={"Authorization": "Bearer " + token}
)
with urllib.request.urlopen(req, timeout=30) as r:
data = json.load(r)
result = []
for rule in data.get("items", []):
name = rule.get("name", "")
if name.startswith("deny-au-"):
direction = rule.get("direction")
field = (
"sourceRanges" if direction == "INGRESS"
else "destinationRanges"
)
ranges = rule.get(field, [])
result.append({
"name": name,
"direction": direction,
"priority": rule.get("priority"),
"network": rule.get("network"),
"targetTags": rule.get("targetTags", []),
"disabled": rule.get("disabled", False),
"cidr_field": field,
"cidr_count": len(ranges) if isinstance(ranges, list) else None,
"cidrs": ranges,
})
result.sort(key=lambda x: (x["direction"], x["name"]))
out = Path("/tmp/au-current-distribution.json")
out.write_text(
json.dumps(result, indent=2, ensure_ascii=False) + "\n",
encoding="utf-8",
)
print(f"已生成:{out}")
print(f"规则数量:{len(result)}")
print(f"文件大小:{out.stat().st_size} 字节")
PY
sudo python3 - <<'PY'
from pathlib import Path
p = Path("/etc/cidr-firewall-updater/update.py.candidate")
source = p.read_text()
old = "range(1, 11)"
new = "range(1, 12)"
count = source.count(old)
print(f"找到待修改表达式:{count} 处")
if count != 6:
raise SystemExit(
f"停止:预期 6 处,实际 {count} 处;文件未写入"
)
updated = source.replace(old, new)
try:
compile(updated, str(p), "exec")
except SyntaxError as exc:
raise SystemExit(
f"语法检查失败,文件未写入:第 {exc.lineno} 行:{exc.msg}"
)
p.write_text(updated)
print("修改成功:6 处 AU 规则范围已扩展到 11 条。")
print("尚未创建防火墙规则,也没有执行 PATCH。")
PY
gcloud config get-value project
gcloud auth list
$project = "analytical-poet-512206-q0"
# 再次确认目标规则不存在
gcloud compute firewall-rules describe deny-au-11 `
--project=$project --format="value(name)" 2>$null
if ($LASTEXITCODE -eq 0) {
Write-Host "deny-au-11 已存在,停止操作。"
} else {
# 单独读取一个 CIDR
$cidr = gcloud compute firewall-rules describe deny-au-10 `
--project=$project `
--format="value(sourceRanges[0])"
if ($LASTEXITCODE -ne 0 -or [string]::IsNullOrWhiteSpace($cidr)) {
throw "读取 deny-au-10 的 CIDR 失败,停止操作。"
}
# 创建规则
gcloud compute firewall-rules create deny-au-11 `
--project=$project `
--direction=INGRESS `
--priority=900 `
--network=default `
--action=deny `
--rules=all `
--source-ranges=$cidr `
--target-tags=wateryaml-country-block `
--no-enable-logging
}
$project = "analytical-poet-512206-q0"
gcloud compute firewall-rules describe deny-au-egress-11 `
--project=$project --format="value(name)" 2>$null
if ($LASTEXITCODE -eq 0) {
Write-Host "deny-au-egress-11 已存在,停止操作。"
} else {
$cidr = gcloud compute firewall-rules describe deny-au-egress-10 `
--project=$project `
--format="value(destinationRanges[0])"
if ($LASTEXITCODE -ne 0 -or [string]::IsNullOrWhiteSpace($cidr)) {
throw "读取 deny-au-egress-10 的 destinationRanges 失败,停止操作。"
}
gcloud compute firewall-rules create deny-au-egress-11 `
--project=$project `
--direction=EGRESS `
--priority=900 `
--network=default `
--action=deny `
--rules=all `
--destination-ranges=$cidr `
--target-tags=wateryaml-country-block `
--no-enable-logging
}
$project = "analytical-poet-512206-q0"
$checks = @(
@{ Old = "deny-au-10"; New = "deny-au-11"; Field = "sourceRanges"; Direction = "INGRESS" },
@{ Old = "deny-au-egress-10"; New = "deny-au-egress-11"; Field = "destinationRanges"; Direction = "EGRESS" }
)
foreach ($c in $checks) {
$oldText = gcloud compute firewall-rules describe $c.Old `
--project=$project --format=json
if ($LASTEXITCODE -ne 0) { throw "读取 $($c.Old) 失败,停止。" }
$old = $oldText | ConvertFrom-Json
$newText = gcloud compute firewall-rules describe $c.New `
--project=$project --format=json
if ($LASTEXITCODE -ne 0) { throw "读取 $($c.New) 失败,停止。" }
$new = $newText | ConvertFrom-Json
$oldCidrs = @($old.($c.Field))
$newCidrs = @($new.($c.Field))
$overlap = @($newCidrs | Where-Object { $oldCidrs -contains $_ })
if ($old.direction -ne $c.Direction -or $new.direction -ne $c.Direction) {
throw "$($c.Old) 或 $($c.New) 的方向不符合预期,停止。"
}
if ($old.network -ne $new.network -or $old.priority -ne $new.priority) {
throw "$($c.Old) 与 $($c.New) 的网络或优先级不一致,停止。"
}
if ((-not $old.disabled) -ne (-not $new.disabled)) {
throw "$($c.Old) 与 $($c.New) 的启用状态不一致,停止。"
}
if ($overlap.Count -ne 1 -or $newCidrs.Count -ne 1) {
throw "$($c.New) 并非恰好只有一个与旧规则重复的 CIDR,停止。"
}
[pscustomobject]@{
OldRule = $c.Old
OldCIDRCount = $oldCidrs.Count
NewRule = $c.New
NewCIDRCount = $newCidrs.Count
CIDRToTransfer = $overlap[0]
Direction = $c.Direction
Priority = $new.priority
Network = $new.network
TargetTags = ($new.targetTags -join ",")
Disabled = $new.disabled
} | Format-List
}
$project = "analytical-poet-512206-q0"
$cidrToMove = "203.219.44.0/23"
$jobs = @(
@{ Old = "deny-au-10"; New = "deny-au-11"; Field = "sourceRanges"; Flag = "--source-ranges" },
@{ Old = "deny-au-egress-10"; New = "deny-au-egress-11"; Field = "destinationRanges"; Flag = "--destination-ranges" }
)
$plans = @()
# 先完成两组预检;任意一组不符合预期,都不执行修改
foreach ($job in $jobs) {
$oldText = gcloud compute firewall-rules describe $job.Old `
--project=$project --format=json
if ($LASTEXITCODE -ne 0) { throw "读取 $($job.Old) 失败,未执行修改。" }
$old = $oldText | ConvertFrom-Json
$newText = gcloud compute firewall-rules describe $job.New `
--project=$project --format=json
if ($LASTEXITCODE -ne 0) { throw "读取 $($job.New) 失败,未执行修改。" }
$new = $newText | ConvertFrom-Json
$oldRanges = @($old.($job.Field))
$newRanges = @($new.($job.Field))
if (@($oldRanges | Where-Object { $_ -eq $cidrToMove }).Count -ne 1) {
throw "$($job.Old) 中该 CIDR 不恰好出现一次;未执行修改。"
}
if ($newRanges.Count -ne 1 -or $newRanges[0] -ne $cidrToMove) {
throw "$($job.New) 的 CIDR 与预期不符;未执行修改。"
}
if ($old.disabled -or $new.disabled) {
throw "$($job.Old) 或 $($job.New) 已禁用;未执行修改。"
}
if ($old.priority -ne 900 -or $new.priority -ne 900) {
throw "优先级与预期不符;未执行修改。"
}
$remaining = @($oldRanges | Where-Object { $_ -ne $cidrToMove })
if ($remaining.Count -ne ($oldRanges.Count - 1) -or $remaining.Count -eq 0) {
throw "$($job.Old) 的剩余 CIDR 数量不符合预期;未执行修改。"
}
$plans += [pscustomobject]@{
Old = $job.Old
New = $job.New
Flag = $job.Flag
Remaining = $remaining
}
}
# 只更新旧规则的 CIDR 字段;新规则始终保留该 CIDR
foreach ($plan in $plans) {
$rangeArg = $plan.Flag + "=" + ($plan.Remaining -join ",")
Write-Host "正在更新 $($plan.Old),保留 $($plan.Remaining.Count) 个网段……"
gcloud compute firewall-rules update $plan.Old `
--project=$project `
$rangeArg
if ($LASTEXITCODE -ne 0) {
throw "$($plan.Old) 更新失败。新规则仍保留原 CIDR,请先核实状态再继续。"
}
Write-Host "$($plan.Old) 更新成功。"
}
sudo python3 /etc/cidr-firewall-updater/update.py.candidate