2016-09-21 6 views
1

취약점 이름, 취약성 수준 및 취약점이있는 IP 주소를 표시하는 취약성 제목, 취약성 심각도 수준, 자산 IP 주소 의 세 가지 필드가있는 다음 CSV 파일이 있습니다. 취약점은 열 심각도 옆에 과 그 취약점이있는 IP 주소의 마지막 열 목록에 나열된 보고서를 인쇄하려고합니다.Python을 사용하여 CSV 구문 분석

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 

내가 취약점을 모두 IP 주소를 포함하는 것 취약점 심각도 수준과 마지막 탭라는 두 번째 탭을 키로 취약점 제목 탭을 사용하여 생성하는 CSV 파일을 다시하고 싶은

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]) 

아주 잘 설명 할 수 없기 때문에.

솔루션의
Car model owner 
Honda Blue James 
Toyota Blue Tom 
Chevy Green James,Tom 

모두가 올바른지 : 나를

을 단순화 해보자 것은 내가 나는 다음과 같은이 CSV를 만들려고하고있는 다음 CSV

Car model owner 
Honda Blue James 
Toyota Blue Tom 
Chevy Green James 
Chevy Green 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') 

는 당신에게 당신의 차의 예를 고려

+0

예를 들어, 생성하려고하는 최종 CSV의 구조를 알려주시겠습니까? 그게 정말 도움이 될거야 –

+0

고맙습니다. 더 자세한 내용으로 질문을 편집 했습니까? 더 많은 정보를 추가해야하는지 알려주세요. –

+0

당신은 환영합니다, 특히 마지막 편집은 중대합니다. 감사. –

답변

1

구조화 된 날짜, 특히 큰 데이터 세트를 조작 할 때. pandas을 사용하라고 제안합니다.

문제는 판다 그룹의 기능을 솔루션으로 제시 할 것입니다. 당신은 데이터가 있다고 가정 :

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

팬더 날짜를 운영하는 것은 매우 fensy입니다 :

import pandas as pd 

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

그런 다음

groups = grouped.groups 

거의 당신이 필요 DICT 될 것입니다.

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) 

팬더 데이터 조작법을 배우는 것이 좋습니다. 그 것이 훨씬 쉽고 청결하다는 것을 알 수 있습니다.

1

답변 감사합니다 나의 마지막 스크립트입니다. 본질적으로, 저는 자동차 브랜드를 핵심으로하는 사전과 두 요소 튜플을 만들고 있습니다. 튜플의 첫 번째 요소는 색상이고 두 번째 요소는 소유자 목록입니다.) :

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) 
+0

수입 CSV 수입 팬더 DF = pd.read_csv ('test.csv'이름 = [ '취약점 제목', '취약점 심각도 수준', '자산 IP 주소']) 그룹화 df라고 #print = df.groupby ([취약성 제목, '취약점 심각도 수준]) groups = grouped.groups # 인쇄 그룹 new_data = [k + (v ['자산 IP 주소 ']. tolist(),) for (취약성 제목, '취약성 심각도', '자산 IP 주소')) new_df = new_df =) –

관련 문제