python 根据ip生成地理位置的kml文件,在谷歌地图上展示

!/usr/bin/python

coding=utf-8

import dpkt
import socket
import pygeoip
import optparse

gi = pygeoip.GeoIP('GeoLiteCity.dat')

通过IP地址的经纬度构建kml结构

def retKML(ip):
rec = gi.record_by_name(ip)
try:
longitude = rec['longitude']
latitude = rec['latitude']
kml = (
'\n'
'%s\n'
'\n'
'%6f,%6f\n'
'
\n'
'
\n'
) %(ip,longitude, latitude)
return kml
except:
return ' '

def plotIPs(pcap):
kmlPts = ''
for (ts, buf) in pcap:
try:
eth = dpkt.ethernet.Ethernet(buf)
ip = eth.data
src = socket.inet_ntoa(ip.src)
srcKML = retKML(src)
dst = socket.inet_ntoa(ip.dst)
dstKML = retKML(dst)
kmlPts = kmlPts + srcKML + dstKML
except:
pass
return kmlPts

def main():
parser = optparse.OptionParser('[*]Usage: python googleearthPrint.py -p ')
parser.add_option('-p', dest='pcapFile', type='string', help='specify pcap filename')
(options, args) = parser.parse_args()
if options.pcapFile == None:
print parser.usage
exit(0)
pcapFile = options.pcapFile
f = open(pcapFile)
pcap = dpkt.pcap.Reader(f)

kmlheader = '\
\n\n\n'
kmlfooter = '\n\n'
kmldoc = kmlheader + plotIPs(pcap) + kmlfooter
# print kmldoc
with open('googleearthPrint.kml', 'w') as f:
    f.write(kmldoc)
    print "[+]Created googleearthPrint.kml successfully"

if name == 'main':
main()

把生成的KML放到谷歌地图上

https://www.google.com/earth/

你可能感兴趣的:(python 根据ip生成地理位置的kml文件,在谷歌地图上展示)