Azure Function中PowerShell下载Azure IP列表并提取IP范围的问题
在Azure Function App的PowerShell中获取Azure IP地址列表JSON
核心问题分析
你访问的链接是微软的下载详情页,并非直接的JSON文件地址,所以直接请求会返回HTML内容。要拿到目标JSON,需要先从详情页提取实际的下载链接,再完成后续的下载、解压和读取操作。
实现步骤与代码
以下是适配Azure Function App PowerShell环境的完整流程:
- 解析下载页面,提取ZIP包的直接下载链接
微软下载页会动态生成实际的下载地址,可通过正则匹配页面内容获取:
# 请求下载详情页 $downloadPage = Invoke-WebRequest -Uri "https://www.microsoft.com/en-us/download/details.aspx?id=56519" -UseBasicParsing # 从页面中匹配ZIP下载链接(适配当前页面结构) $zipUrlMatch = $downloadPage.Content | Select-String -Pattern 'https://download.microsoft.com/download/[^"]+\.zip' -AllMatches $zipUrl = $zipUrlMatch.Matches[0].Value
- 下载ZIP包并解压到临时目录
Azure Function提供临时存储,可将ZIP解压到临时路径:
# 定义临时存储路径 $tempDir = Join-Path $env:TEMP "AzureIPRanges" New-Item -Path $tempDir -ItemType Directory -Force | Out-Null # 下载ZIP包到临时文件 $zipPath = Join-Path $tempDir "AzureIPRanges.zip" Invoke-WebRequest -Uri $zipUrl -OutFile $zipPath -UseBasicParsing # 解压ZIP包 Expand-Archive -Path $zipPath -DestinationPath $tempDir -Force
- 读取JSON内容到变量
解压后会生成命名类似ServiceTags_Public_*.json的文件,匹配并读取:
# 定位解压后的JSON文件 $jsonFile = Get-ChildItem -Path $tempDir -Filter "ServiceTags_Public_*.json" | Select-Object -First 1 # 读取JSON内容到变量 $azureIpData = Get-Content -Path $jsonFile.FullName | ConvertFrom-Json
- 筛选所需IP范围示例
比如筛选"AzureCloud"服务标签的IP范围:
$azureCloudIps = $azureIpData.values | Where-Object { $_.name -eq "AzureCloud" } | Select-Object -ExpandProperty properties | Select-Object -ExpandProperty addressPrefixes # 输出筛选结果 $azureCloudIps
注意事项
- 若函数部署在虚拟网络中,需确保能访问
download.microsoft.com - 微软可能更新下载页结构,若正则匹配失效,需调整匹配规则
- 临时目录内容会在函数执行结束后自动清理,无需手动删除
内容的提问来源于stack exchange,提问作者dcvl
相关产品推荐
相关产品推荐

