单独使用 Python 或 jsonata 从 CSV 文件中切出行

问题描述 投票:0回答:3

我正在使用 C2Intel Feeds 来查找特定的可观察值,当我这样做时,我想提取/切出该行。

示例: https://raw.githubusercontent.com/drb-ra/C2IntelFeeds/master/feeds/domainC2swithURLwithIP-filter-abused.csv

如果您转到链接/CSV 文件,我可以找到特定的 IP,即 - 54.161.191.72。

我想切掉整行:

www.e-enroll-benefits.com,可能的 Cobalt Strike C2 域名,/enrollmentinfo/,54.161.191.72

由于每一行都不同,我不确定如何进行此过程。 我想过找到长度,但我不知道该怎么做,因为它各不相同。

这是我当前的代码:

ip_address = "54.161.191.72"
lines = "https://raw.githubusercontent.com/drb-ra/C2IntelFeeds/master/feeds/domainC2swithURLwithIP-filter-abused.csv"
for line in lines:
    if re.match("ip_address", line):
        values_slice = line.split(": ")[-1]#not sure how you get the whole row?

感谢任何帮助或指导。预先感谢!

python csv extract slice
3个回答
0
投票

我尝试了更简单的方法,它对我有用。 我没有访问 URL,而是将 csv 文件下载到本地文件夹,最好是运行 python 脚本以保存“os.chdir”步骤的同一文件夹。 请看下面:

import os
os.chdir('/Users/***/***/') # please update this path to where your csv file downloaded is
ip_address = '54.161.191.72'
lines = open('domainC2swithURLwithIP-filter-abused.csv')
for line in lines:
    if ip_address in line:
        print(line)

以下是我得到的输出: output 很高兴回答您的任何问题。干杯!


0
投票

您的代码在使用文件之前没有获取该文件。另外,您已经在

line
中拥有整行,您只需打印它即可。
这是一个更新版本,每次都会获取链接并打印包含给定 IP 地址的行。

import requests

URL = "https://raw.githubusercontent.com/drb-ra/C2IntelFeeds/master/feeds/domainC2swithURLwithIP-filter-abused.csv"
ip_address = "54.161.191.72"

c2list = requests.get(URL).text
for line in c2list.split("\n"):
    if ip_address in line:
        print(line)

此代码将响应分成几行,并检查每一行是否有指定的 IP 地址。
正则表达式不需要仅仅过滤掉一行。
当需要更高级的模式匹配时,请使用

if re.search(<regex_string>, line):

我希望这能解决您的问题!


0
投票

不完全确定“切片行”是什么意思,所以我假设您只想找到具有特定值的行(行)。

您的数据是 CSV 格式,那么为什么不使用内置的 csv 模块呢?毕竟,这就是它的用途。

试试这个:

import csv
import requests

url = "https://raw.githubusercontent.com/drb-ra/C2IntelFeeds/master/feeds/domainC2swithURLwithIP-filter-abused.csv"
ip = "54.161.191.72"

with requests.get(url) as response:
    response.raise_for_status() # check HTTP response
    lines = response.text.splitlines()[1:] # split text (CSV) response into lines skipping the first row (column headings)
    reader = csv.reader(lines) # construct the reader 
    for i, row in enumerate(reader): # enumerate the reader
        if row[-1] == ip: # check last column
            print(lines[i])
            break

输出:

www.e-enroll-benefits.com,Possible Cobalt Strike C2 Domain,/enrollmentinfo/,54.161.191.72
© www.soinside.com 2019 - 2024. All rights reserved.