1

次の csv ファイルには、脆弱性のタイトル、脆弱性の重大度レベル、脆弱性の名前、脆弱性のレベル、およびその脆弱性を持つ IP アドレスを示すアセット IP アドレスの 3 つのフィールドがあります。その隣の列の重大度に脆弱性をリストし、その脆弱性を持つ IP アドレスの最後の列のリストを表示するレポートを印刷しようとしています。

Vulnerability Title Vulnerability Severity Level    Asset IP Address
TLS/SSL Server Supports RC4 Cipher Algorithms (CVE-2013-2566)   4   10.103.64.10
TLS/SSL Server Supports RC4 Cipher Algorithms (CVE-2013-2566)   4   10.103.64.10
TLS/SSL Server Supports RC4 Cipher Algorithms (CVE-2013-2566)   4   10.103.65.10
TLS/SSL Server Supports RC4 Cipher Algorithms (CVE-2013-2566)   4   10.103.65.164
TLS/SSL Server Supports RC4 Cipher Algorithms (CVE-2013-2566)   4   10.103.64.10
TLS/SSL Server Supports RC4 Cipher Algorithms (CVE-2013-2566)   4   10.10.30.81
TLS/SSL Server Supports RC4 Cipher Algorithms (CVE-2013-2566)   4   10.10.30.81
TLS/SSL Server Supports RC4 Cipher Algorithms (CVE-2013-2566)   4   10.10.50.82
TLS/SSL Server Supports Weak Cipher Algorithms  6   10.103.65.164
Weak Cryptographic Key  3   10.103.64.10
Unencrypted Telnet Service Available    4   10.10.30.81
Unencrypted Telnet Service Available    4   10.10.50.82
TLS/SSL Server Supports Anonymous Cipher Suites with no Key Authentication  6   10.103.65.164
TLS/SSL Server Supports The Use of Static Key Ciphers   3   10.103.64.10
TLS/SSL Server Supports The Use of Static Key Ciphers   3   10.103.65.10
TLS/SSL Server Supports The Use of Static Key Ciphers   3   10.103.65.100
TLS/SSL Server Supports The Use of Static Key Ciphers   3   10.103.65.164
TLS/SSL Server Supports The Use of Static Key Ciphers   3   10.103.65.164
TLS/SSL Server Supports The Use of Static Key Ciphers   3   10.103.64.10
TLS/SSL Server Supports The Use of Static Key Ciphers   3   10.10.30.81

脆弱性タイトル タブをキーとして使用し、脆弱性重大度レベルと呼ばれる 2 番目のタブを作成する csv ファイルを再作成したいと思います。最後のタブには、脆弱性を持つすべての IP アドレスが含まれます。

import csv
from pprint import pprint
from collections import defaultdict
import glob
x= glob.glob("/root/*.csv")

d = defaultdict()
n = defaultdict()
for items in x:
        with open(items, 'rb') as f:
                reader = csv.DictReader(f, delimiter=',')
                for row in reader:
                        a = row["Vulnerability Title"]
                        b = row["Vulnerability Severity Level"], row["Asset IP Address"]
                        c = row["Asset IP Address"]
        #               d = row["Vulnerability Proof"]
                        d.setdefault(a, []).append(b)
        f.close()
pprint(d)
with open('results/ipaddress.csv', 'wb') as csv_file:
        writer = csv.writer(csv_file)
        for key, value in d.items():
                for x,y in value:
                        n.setdefault(y, []).append(x)
#                       print x
                        writer.writerow([key,n])

with open('results/ipaddress2.csv', 'wb') as csv2_file:
        writer = csv.writer(csv2_file)
        for key, value in d.items():
             n.setdefault(value, []).append(key)
             writer.writerow([key,n])

うまく説明できないので。単純化してみましょう

次のcsvがあるとしましょう

Car model   owner
Honda   Blue    James
Toyota  Blue    Tom
Chevy   Green   James
Chevy   Green   Tom

このcsvを次のように作成しようとしています:

Car model   owner
Honda   Blue    James
Toyota  Blue    Tom
Chevy   Green   James,Tom

どちらのソリューションも正しいです。ここに私の最終的なスクリプトもあります

import csv
import pandas as pd

df = pd.read_csv('test.csv', names=['Vulnerability Title', 'Vulnerability Severity Level','Asset IP Address'])
#print df
grouped = df.groupby(['Vulnerability Title','Vulnerability Severity Level'])

groups = grouped.groups
#print groups
new_data = [k + (v['Asset IP Address'].tolist(),) for k, v in grouped]
new_df = pd.DataFrame(new_data, columns=['Vulnerability Title' ,'Vulnerability Severity Level', 'Asset IP Address'])

print new_df
new_df.to_csv('final.csv')

ありがとうございました

4

2 に答える 2

1

Answer considering your car example. Essentially, I am creating a dictionary which has the car brand as the key, and a two element tuple. The first element of the tuple is the color and the second, a list of owners.):

import csv

car_dict = {}
with open('<file_to_read>', 'rb') as fi:
    reader = csv.reader(fi)
    for f in reader:
        if f[0] in car_dict:
            car_dict[f[0]][1].append(f[2]) 
        else:
            car_dict[f[0]] = (f[1], [f[2]])

with open('<file_to_write>', 'wb') as ou:
    for k in car_dict:
        out_string ='{}\t{}\t{}\n'.format(k, car_dict[k][0], ','.join(car_dict[k][1]))
        ou.write(out_string)
于 2016-09-21T21:03:22.067 に答える
1

構造化された日付、特に大規模なデータ セットを操作する場合。pandasを使用することをお勧めします。

あなたの問題について、解決策としてパンダの groupby 機能の例を示します。次のデータがあるとします。

data = [['vt1', 3, '10.0.0.1'], ['vt1', 3, '10.0.0.2'], 
        ['vt2', 4, '10.0.10.10']]

日付を操作するパンダは非常に気まぐれです:

import pandas as pd

df = pd.DataFrame(data=data, columns=['title', 'level', 'ip'])
grouped = df.groupby(['title', 'level'])

それで

groups = grouped.groups

ほとんど必要な辞書になります。

print(groups)
{('vt1', 3): [0, 1], ('vt2', 4): [2]}

[0,1]行ラベルを表します。実際には、これらのグループを繰り返し処理して、必要な操作を適用できます。たとえば、csv ファイルに保存する場合は、次のようにします。

new_data = [k + (v['ip'].tolist(),) for k, v in grouped]
new_df = pd.DataFrame(new_data, columns=['title', 'level', 'ips'])

new_df とは何かを見てみましょう:

  title  level                   ips
0   vt1      3  [10.0.0.1, 10.0.0.2]
1   vt2      4          [10.0.10.10]

それが必要です。最後に、ファイルに保存します。

new_df.to_csv(filename)

パンダのデータ操作を学ぶことを強くお勧めします。その方がはるかに簡単でクリーンであることがわかるかもしれません。

于 2016-09-21T21:12:22.537 に答える