http://dev.maxmind.com/geoip/legacy/geolite/
!/usr/bin/python
coding=utf-8
import dpkt
import socket
import pygeoip
import optparse
gi = pygeoip.GeoIP('GeoLiteCity.dat')
查詢數(shù)據(jù)庫(kù)相關(guān)的城市信息并輸出
def printRecord(tgt):
rec = gi.record_by_name(tgt)
city = rec['city']
# 原來(lái)的代碼為 region = rec['region_name'],已棄用'region_name'
region = rec['region_code']
country = rec['country_name']
long = rec['longitude']
lat = rec['latitude']
print '[*] Target: ' + tgt + ' Geo-located. '
print '[+] '+str(city)+', '+str(region)+', '+str(country)
print '[+] Latitude: '+str(lat)+ ', Longitude: '+ str(long)
def printPcap(pcap):
# 遍歷[timestamp, packet]記錄的數(shù)組
for (ts, buf) in pcap:
try:
# 獲取以太網(wǎng)部分?jǐn)?shù)據(jù)
eth = dpkt.ethernet.Ethernet(buf)
# 獲取IP層數(shù)據(jù)
ip = eth.data
# 把存儲(chǔ)在inet_ntoa中的IP地址轉(zhuǎn)換成一個(gè)字符串
src = socket.inet_ntoa(ip.src)
dst = socket.inet_ntoa(ip.dst)
print '[+] Src: ' + src + ' --> Dst: ' + dst
print '[+] Src: ' + retGeoStr(src) + '--> Dst: ' + retGeoStr(dst)
except:
pass
返回指定IP地址對(duì)應(yīng)的物理位置
def retGeoStr(ip):
try:
rec = gi.record_by_name(ip)
city = rec['city']
country = rec['country_code3']
if city != '':
geoLoc = city + ', ' + country
else:
geoLoc = country
return geoLoc
except Exception, e:
return 'Unregistered'
def main():
parser = optparse.OptionParser('[*]Usage: python geoPrint.py -p <pcap file>')
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)
printPcap(pcap)
if name == 'main':
main()