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

PowerShell正则脚本无法同时提取IP地址与端口的问题求助

问题分析与解决方案

为什么原正则无法提取端口

你的正则(\d{1,3}\.\d{1,3}\.\d{1,3}\.\d{1,3})(\,\d+)假设IP地址后直接跟,数字,但实际CSV数据里,IP和端口是被双引号包裹的,且两者之间是","分隔符(比如"178.128.23.9","4125"),原正则的\,\d+无法匹配这种带引号的结构,所以只能捕获IP,拿不到端口。

修正正则方案

调整正则来匹配CSV中带引号的IP和端口结构:

"(\d{1,3}\.\d{1,3}\.\d{1,3}\.\d{1,3})","(\d+)"
  • 分组1:捕获被双引号包裹的IP地址
  • 分组2:捕获被双引号包裹的端口号

在PowerShell中可以这样使用:

$csvContent = Get-Content "your_file.csv"
$matches = $csvContent | Select-String -Pattern '"(\d{1,3}\.\d{1,3}\.\d{1,3}\.\d{1,3})","(\d+)"' -AllMatches
foreach ($match in $matches.Matches) {
    $ip = $match.Groups[1].Value
    $port = $match.Groups[2].Value
    "$ip : $port" | Out-File -Append "output.txt"
    # 添加防火墙规则示例
    New-NetFirewallRule -DisplayName "Block $ip : $port" -Direction Inbound -RemoteAddress $ip -RemotePort $port -Action Block -Protocol TCP
}

更高效的PowerShell CSV处理方式

其实PowerShell原生支持CSV解析,不需要正则,更可靠且易维护:

# 导入CSV文件,指定列名(如果CSV没有表头)
$csvData = Import-Csv "your_file.csv" -Header "Timestamp", "IP", "Port", "Status", "LastSeen", "Malware"
foreach ($entry in $csvData) {
    $ip = $entry.IP
    $port = $entry.Port
    "$ip : $port" | Out-File -Append "output.txt"
    New-NetFirewallRule -DisplayName "Block $ip : $port" -Direction Inbound -RemoteAddress $ip -RemotePort $port -Action Block -Protocol TCP
}

这种方式直接通过列名提取数据,避免了正则匹配可能出现的边界问题,比如IP格式不规范或者CSV格式变化的情况。

内容的提问来源于stack exchange,提问作者Carey Shupe

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.07.16 20:12:43