Reputation: 174
I'm reading a pcap file and trying to write it to a csv file with necessary data. I used Scapy to read Pcap and could successfully fetch the package data, Now i'm trying to write to a csv file but endingup only with one data. Below is my code.
pkts = rdpcap('example.pcap')
for pkt in pkts:
if IP in pkt:
ip_src=pkt[IP].src
ip_dst=pkt[IP].dst
if TCP in pkt:
tcp_dport=pkt[TCP].dport
if ip_src == '10.116.206.114' and ip_dst == '10.236.138.184':
print (str(ip_src) + str(ip_dst) + str(tcp_dport))
csv_header = "IP_src,IP_drc,dst_port\n"
s = ""
for scr in str(ip_src):
s+=str(scr)
csv_header += s + ','
s_ = ''
for dst in str(ip_dst) :
s_+=str(dst)
csv_header += s_ + ','
s_1 = ''
for dst_tcp in str(tcp_dport):
s_1 += str(dst_tcp)
csv_header += s_1
f = open("Pcap/test.csv", "w")
f.write(csv_header)
Now i'm getting only one output in csv
if i print to check i get all output in log but not in csv, Please suggest me the proper way append the data into csv
Thanks!
Upvotes: 0
Views: 1188
Reputation: 61
As @HampusLarsson commented, you are opening the file every iteration of the for loop. You should open the file before the loop. This is the fixed code:
pkts = rdpcap('example.pcap')
with open("Pcap/test.csv", "w") as f:
for pkt in pkts:
if IP in pkt:
ip_src=pkt[IP].src
ip_dst=pkt[IP].dst
if TCP in pkt:
tcp_dport=pkt[TCP].dport
if ip_src == '10.116.206.114' and ip_dst == '10.236.138.184':
print (str(ip_src) + str(ip_dst) + str(tcp_dport))
csv_header = "IP_src,IP_drc,dst_port\n"
s = ""
for scr in str(ip_src):
s+=str(scr)
csv_header += s + ','
s_ = ''
for dst in str(ip_dst) :
s_+=str(dst)
csv_header += s_ + ','
s_1 = ''
for dst_tcp in str(tcp_dport):
s_1 += str(dst_tcp)
csv_header += s_1
f.write(csv_header)
Note that we are using a context-manager (with open(...) as ...:
), so the file will automatically close at the end of the scope, or in case an exception is raised.
Upvotes: 2