You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

如何用PowerShell从ngrok日志提取特定地址并保存到新文件

提取ngrok日志中的隧道地址并保存

问题背景

有一个ngrok生成的日志文件,需要从中提取特定格式的隧道地址(格式为(1-99的数字).tcp.(ap/au/eu/in/jp/sa/us).ngrok.io:(10000-99999的数字)),原脚本会保存包含地址的整行内容,需求是仅提取地址本身并保存到新文件。

日志示例:

t=2023-07-05T16:17:15+0300 lvl=info msg="no configuration paths supplied"
t=2023-07-05T16:17:15+0300 lvl=info msg="using configuration at default config path" path=C:\\Users\\***\\AppData\Local/ngrok/ngrok.yml
t=2023-07-05T16:17:15+0300 lvl=info msg="open config file" path=C:\\Users\\***\\AppData\\Local\\ngrok\\ngrok.yml err=nil
t=2023-07-05T16:17:15+0300 lvl=info msg="starting web service" obj=web addr=127.0.0.1:4040 allow_hosts=[]
t=2023-07-05T16:17:15+0300 lvl=info msg="tunnel session started" obj=tunnels.session
t=2023-07-05T16:17:15+0300 lvl=info msg="client session established" obj=csess
t=2023-07-05T16:17:15+0300 lvl=info msg="started tunnel" obj=tunnels name=command_line addr=//localhost:8865 url=tcp://4.tcp.eu.ngrok.io:10355
t=2023-07-05T16:17:16+0300 lvl=info msg="update available" obj=updater

原脚本问题:保存的是包含地址的整行,而非仅目标地址。

修改后的PowerShell脚本

$logPath = "C:\ngrok_log.txt"
$savePath = "C:\final_ip.txt"

# 匹配符合格式的ngrok隧道地址
$pattern = '(\d{1,2}\.tcp\.(ap|au|eu|in|jp|sa|us)\.ngrok\.io:\d{5})'

# 从日志中提取匹配的地址
$matchResult = Select-String -Path $logPath -Pattern $pattern -List

if (-not $matchResult) {
    Write-Host "ERROR - 日志文件中未找到符合格式的隧道地址"
}
else {
    # 提取捕获组中的地址内容
    $targetAddress = $matchResult.Matches.Groups[1].Value
    Write-Host "SUCCESS - 提取到隧道地址:$targetAddress"
    # 将地址写入文件
    $targetAddress | Out-File -Path $savePath -Encoding utf8
}

Write-Host "操作完成"

关键修改说明

  • 正则表达式优化:调整后的$pattern精准匹配目标地址格式:
    • \d{1,2}:匹配1-99的数字前缀
    • (ap|au|eu|in|jp|sa|us):匹配指定的区域后缀
    • \d{5}:匹配10000-99999的端口号
  • 提取匹配组:通过$matchResult.Matches.Groups[1].Value直接获取正则表达式括号捕获的地址部分,而非整行内容
  • 简化逻辑:去掉不必要的循环(单个文件无需遍历),直接处理目标日志文件

内容的提问来源于stack exchange,提问作者Ray Plays

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.07.16 05:02:34