筆記整理6——用python實現IP流量分析


一.主要思路
(1).通過ip獲取地理位置
主要是通過ip從我們獲取的數據庫中查詢相應信地理位置信息
程序實現中已經將數據庫下載到本地

(2).對經過dpkt解析的對象pcap獲取ip及其位置
將經過dpkt.pcap.Reader(g)方法解析的pcap對象進行拆分解析
這個pcap對象中含有一個[timestamp,packet]類數據的數組,我們將每個層
分成以太網層和ip層兩部分,通過socket讀取ip,讀取后利用第一部分的函數進行
地理位置信息的獲取。

(3).通過ip獲取信息並返回一個kml格式文檔
首先是鏈接數據庫獲取位置信息,其次建立一個空集合存儲相應格式的
地理信息,(格式為kml)主要注意變量和對應輸出的關系。

(4).對dpkt打開的pcap包獲取ip並獲取相應kml文檔
獲取一個pcap包,遍歷所有的緩沖區pcap數據包,提取以太網幀,
從該幀中獲取ip信息,得到ip后通過構造的函數獲取相應的kml文檔

3.總結與思考
(1).主要模塊獲取
書中很多信息其實過時了,程序中用到模塊和數據庫獲取方法

pygeoip模塊:
{
https://github.com/appliedsec/pygeoip
kali下使用git clone 下載
或者通過apt-get install pygeoip下載(蕞方便)
(書中用的數據庫后綴為dat,該模塊恰好能使用dat類型的該數據庫)
dat版本數據庫(csdn上有dat版本留存)
https://download.csdn.net/psearch/0/10/0/2/1/geoip.dat
}
替代方法:
{
替代模塊
pip install python-geoip-geolite2 -i https://pypi.douban.com/simple
pip install geoip2
(官網數據庫geoip為mmdb類型,用新的方法打開,如下)
geoip2(python)使用文檔:
https://geoip2.readthedocs.io/en/latest/
GeoliteCity(geoip2)開源數據庫位置
https://dev.maxmind.com/zh-hans/geoip/geoip2/geolite2/#IP
}
數據庫分享
鏈接: https://pan.baidu.com/s/1s4FgYu--r6r0IhkGbHoErQ
提取碼:0r8c
(2).生成kml文檔后,如何使用google地球?(google地球網址: https://earth.google.com/web/)

(3).陌生模塊與方法
***socket.inet_ntop(address_family, packed_ip)
Convert a packed IP address (a string of some number of characters) to its standard, family-specific string representation (for example, '7.10.0.5' or '5aef:2b::8') inet_ntop() is useful when a library or network protocol returns an object of type struct in_addr (similar to inet_ntoa()) or struct in6_addr.

***# Unpack the Ethernet frame (mac src/dst, ethertype)
eth = dpkt.ethernet.Ethernet(buf)
print 'Ethernet Frame: ', mac_addr(eth.src), mac_addr(eth.dst), eth.type

***dpkt.pcap.Reader(f)
dpkt.pcap.Reader(f) implements an iterator. Each iteration returns a tuple which is a timestamp and a buffer. The timestamp contains a time as a floating point number. The buffer is a complete packet. For example:
dpkt官方文檔介紹
http://www.commercialventvac.com/dpkt.html
4.遭遇問題
(1).其中的pcap包實際用的是書中例子,在網上沒有找到pcap流量包,(也可自行構造)數據樣本不足
最終得google地球上僅僅有幾個點
google語法找到的攻防練習樣例
https://www.netresec.com/?page=pcapfiles
二.代碼
1.用pygeoip關聯ip和物理位置

#!/usr/bin/python
# coding: utf-8

import pygeoip
import dpkt
import socket

f = open('Location.txt','w')
gi = pygeoip.GeoIP('/mnt/hgfs/temp/temp/python/exercise/GeoLiteCity.dat')

#通過ip得到相應地理位置
def retGeoLocation(ip):
    try:
        rec = gi.record_by_name(ip)
        city = rec['city']
        country = rec['country_name']
        if city:
            location = country+"/"+city
        else:
            location = country
        return location
    except Exception,e:
        print e
        return 'No Location'


#對pcap包解析得到ip及其地理位置的來源和去向
def printPcap(pcap):
    for (ts,buf) in pcap:
        try:

            eth = dpkt.ethernet.Ethernet(buf)
            ip = eth.data
            src = socket.inet_ntoa(ip.src)
            dst = socket.inet_ntoa(ip.dst)
            print >> f,'[+] Src: '+src+' --> Dst: '+dst
            print >> f,'[+] '+retGeoLocation(src)+' --> '+retGeoLocation(src)+'\n'
        except Exception,e:
            print e
            pass


#輸出地理ip相關的地理位置(詳細)
def printLocation(ip):
    rec = gi.record_by_name(ip)

    city = rec['city']
    region = rec['time_zone']
    country = rec['country_name']
    long = rec['longitude']
    lat = rec['latitude']
    print '[*] Target: '+ip
    print '[+] '+str(city)+', '+str(region)+', '+str(country)
    print '[+] Latitude: '+str(lat)+', Longitude: '+str(long)+'\n'
 


def main():
    g = open('geotest.pcap')

    pcap = dpkt.pcap.Reader(g)  #dpkt打開pcap包后的對象
    print >> f,'---------------------------location-------------------------' 
    printPcap(pcap)


if __name__ == '__main__':
    main()


2.用python由ip畫google地球

#!/usr/bin/python
# coding: utf-8

import dpkt
import socket
import pygeoip

gi = pygeoip.GeoIP('/mnt/hgfs/temp/temp/python/exercise/GeoLiteCity.dat')

def retKML(ip):
    rec = gi.record_by_name(ip)
    try:
        longitude = rec['longitude']
        latitude = rec['latitude']
        kml = (
            '<Placemark>\n'
            '<name>%s</name>\n'
            '<Point>\n'
            '<coordinates>%6f,%6f</coordinates>\n'
            '</Point>\n'
            '</Placemark>\n'
        )%(ip,longitude,latitude)
        return kml
    except Exception,e:
        print e
        return ''


def plotIP(pcap):
    kmlPlot = ''
    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)
            kmlPlot = kmlPlot+srcKML+dstKML
        except Exception,e:
            print e
            pass
    return kmlPlot


def main():
    
    f = open('location.kml','w')
    g = open('test1.pcap')
    pcap = dpkt.pcap.Reader(g)
    kmlheader = '<?xml version="1.0" encoding="UTF-8"?>\n'\
            +'<kml xmlns="http://www.opengis.net/kml/2.2">\n<Document>\n'
    kmlfooter = '</Document>\n</kml>\n'
    kmldoc = kmlheader + plotIP(pcap)+ kmlfooter
    f.write(kmldoc)
    f.close()


if __name__ == '__main__':
    main()



免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM