目标:
解析数据包,按照IP地址进行分类,将data存入不同的dat文件中,比如192.168.0.3源ip的数据存入1.dat中,我现在写的有点晕了,请教一下大家
代码如下:
```python
import dpkt
import time
import os
import socket
# 源文件路径
fileRoute = 'srcData'
# ip池
ipList = [
'192.168.0.3',
'192.168.0.4',
'192.168.0.5',
'192.168.0.6',
'192.168.0.7',
'192.168.0.8',
'192.168.0.9',
'192.168.0.10',
'192.168.0.11',
'192.168.0.12',
'192.168.0.13',
'192.168.0.14',
'192.168.0.15',
'192.168.0.16',
'192.168.0.17',
'192.168.0.18',
'192.168.0.19',
'192.168.0.20'
]
# 输出文件名
fileName1 = "outputDat/1.dat"
fileName2 = "outputDat/2.dat"
fileName3 = "outputDat/3.dat"
fileName4 = "outputDat/4.dat"
fileName5 = "outputDat/5.dat"
fileName6 = "outputDat/6.dat"
fileName7 = "outputDat/7.dat"
fileName8 = "outputDat/8.dat"
fileName9 = "outputDat/9.dat"
fileName10 = "outputDat/10.dat"
fileName11 = "outputDat/11.dat"
fileName12 = "outputDat/12.dat"
fileName13 = "outputDat/13.dat"
fileName14 = "outputDat/14.dat"
fileName15 = "outputDat/15.dat"
fileName16 = "outputDat/16.dat"
fileName17 = "outputDat/17.dat"
fileName18 = "outputDat/18.dat"
# 获取文件夹下的pcap文件
def getFiles(rootDir):
files = []
for lists in os.listdir(rootDir):
path = os.path.join(rootDir, lists)
files.append(path)
# print(path)
if os.path.isdir(path):
getFiles(path)
return files
def transForm():
files = getFiles(fileRoute)
for file in files:
f = open(file, 'rb')
pacpFile = dpkt.pcap.Reader(f)
for ts, buf in pacpFile:
# eth = dpkt.ethernet.Ethernet(buf)
eth = dpkt.sll.SLL(buf)
ip = eth.data
srcIP = socket.inet_ntoa(ip.src)
pos = ipList.index(srcIP)
print(srcIP)
udpdata = ip.udp.data
with open('outputDat/' + srcIP + '.dat', 'ab+') as data_file:
data_file.write(udpdata)
f.close()
if __name__ == '__main__':
timeBegin = time.clock()
transForm()
timeEnd = time.clock()
timeAll = timeEnd - timeBegin
print(timeAll)
# # 1.7463044
# # 1.3005846
# # 1.0944584
```
每个IP起一个进程来监听,写入对应文件,