【问题标题】:Python - Using re to search for a pattern in the value of an imported csv for an if statementPython - 使用 re 在导入的 csv 值中搜索 if 语句的模式
【发布时间】:2023-04-02 22:00:01
【问题描述】:

首先,我很抱歉在这方面是个菜鸟。我有以下代码可以打开一个 CSV 文件并读取它。我试图只返回在名为“源 IP / 详细信息”的字段中包含公共 IP 地址的行以及我知道正在工作的行 [“状态”] 字段。我有我认为是正确的正则表达式,但我不确定我是否正确地进行搜索。另外,我不确定我是否在以下 for 语句中正确设置了变量。

ipRegex = '\b(?!(10)|192\.168|172\.(2[0-9]|1[6-9]|3[0-2]))[0-9]{1,3}\.[0-9]{1,3}\.[0-9]{1,3}\.[0-9]{1,3}'

with open('whois.csv') as csvDataFile:
csvReader = csv.DictReader(csvDataFile)
rows = [row for row in csvReader if row['Status'] != "Closed" and row['Status'] != "Resolved"] and row['Source IP / Details'] == re.search(ipRegex, row['Source IP / Details'])]

for row in rows:
    case = row['Case Number']
    ipaddr = row['Source IP / Details']

这是我的数据示例:

Case Number,Status,Date/Time Opened,_BATCH_ID_,_BATCH_LAST_RUN_,Alert Source,Alert Subtype,Source IP / Details,
2926,Closed,2015-10-29T11:54:00,2130,2017-10-30T22:48:02,Sophos,[MEDIUM] Alert for Sophos Cloud: A computer does not comply with its Cloud po...,,
7733,Closed,2015-11-18T13:46:00,2130,2017-10-30T22:48:02,Dell SecureWorks,Malicious Network Activity,216.30.178.102,
7818,Closed,2015-11-18T20:58:00,2130,2017-10-30T22:48:02,Dell SecureWorks,Application-Specific Exploits GNU Bash Environment Variable Code Injection attempt(s),,
7850,Closed,2015-11-18T21:47:00,2130,2017-10-30T22:48:02,Dell SecureWorks,Vulnerability Scanning,173.166.95.81,

【问题讨论】:

  • 请提供几行whois.csv 并通过editing your question 更正您的缩进。此外,您的正则表达式与 IP 地址不匹配(请参阅此处:regex101.com/r/uzRthC/1),$ 之后的最后一个 ) 会产生模式错误。
  • 谢谢,我要更正正则表达式。

标签:
python
regex
csv