Skip to content

Commit

Permalink
export
Browse files Browse the repository at this point in the history
export to csv,xml,txt
  • Loading branch information
maldevel committed Dec 15, 2015
1 parent 1c23c59 commit fd5e8f7
Show file tree
Hide file tree
Showing 3 changed files with 160 additions and 3 deletions.
39 changes: 36 additions & 3 deletions ip2geolocation.py
Original file line number Diff line number Diff line change
Expand Up @@ -25,6 +25,7 @@
import argparse, sys
from argparse import RawTextHelpFormatter
from geolocation.IpGeoLocationLib import IpGeoLocationLib
from utilities.FileExporter import FileExporter
import webbrowser
from urllib.parse import urlparse
import os.path
Expand All @@ -41,12 +42,24 @@ def checkProxy(url):
return url_checked


def checkFile(filename):
def checkFileRead(filename):
"""Check if file exists and we have access to read it"""
if os.path.isfile(filename) and os.access(filename, os.R_OK):
return filename
else:
raise argparse.ArgumentTypeError("Invalid {} file (File does not exist, cannot be read or it's not a file).".format(filename))
raise argparse.ArgumentTypeError("Invalid {} file (File does not exist, insufficient permissions or it's not a file).".format(filename))


def checkFileWrite(filename):
"""Check if we can write to file"""
if os.path.isfile(filename):
raise argparse.ArgumentTypeError("File {} already exists.".format(filename))
elif os.path.isdir(filename):
raise argparse.ArgumentTypeError("Folder provided. Please provide a valid filename.")
elif os.access(os.path.dirname(filename), os.W_OK):
return filename
else:
raise argparse.ArgumentTypeError("Cannot write to {} file (Insufficient permissions).".format(filename))


if __name__ == '__main__':
Expand All @@ -59,9 +72,12 @@ def checkFile(filename):
parser.add_argument('-t', '--target', metavar='Host', help='The IP Address or Domain to be analyzed.')
parser.add_argument('-u', '--useragent', metavar='User-Agent', default='IP2GeoLocation {}'.format(VERSION), help='Set the User-Agent request header (default: IP2GeoLocation {}).'.format(VERSION))
parser.add_argument('-r', help='Pick User Agent strings randomly.', action='store_true')
parser.add_argument('-l', metavar='User-Agent list', type=checkFile, dest='user_agent_list', help='Provide a User-Agent file list. Each User-Agent string should be in a new line.')
parser.add_argument('-l', metavar='User-Agent list', type=checkFileRead, dest='user_agent_list', help='Please provide a User-Agent file list. Each User-Agent string should be in a new line.')
parser.add_argument('-x', '--proxy', metavar='Proxy', type=checkProxy, help='Setup proxy server (example: http://127.0.0.1:8080).')
parser.add_argument('-g', help='Open IP location in Google maps with default browser.', action='store_true')
parser.add_argument('--csv', metavar='Filename', type=checkFileWrite, help='Please provide a file to export results in CSV format.')
parser.add_argument('--xml', metavar='Filename', type=checkFileWrite, help='Please provide a file to export results in XML format.')
parser.add_argument('-e', '--txt', metavar='Filename', type=checkFileWrite, help='Please provide a file to export results.')

args = parser.parse_args()

Expand All @@ -81,6 +97,23 @@ def checkFile(filename):
webbrowser.open('http://www.google.com/maps/place/{0},{1}/@{0},{1},16z'.
format(IpGeoLocObj.Latitude, IpGeoLocObj.Longtitude))


if args.csv:
fileExporter = FileExporter()
if not fileExporter.ExportToCSV(IpGeoLocObj, args.csv):
print('Saving results to {} csv file failed.'.format(args.csv))

if args.xml:
fileExporter = FileExporter()
if not fileExporter.ExportToXML(IpGeoLocObj, args.xml):
print('Saving results to {} xml file failed.'.format(args.xml))

if args.txt:
fileExporter = FileExporter()
if not fileExporter.ExportToTXT(IpGeoLocObj, args.txt):
print('Saving results to {} txt file failed.'.format(args.txt))


print("""
IPGeoLocation {} - Results
Expand Down
104 changes: 104 additions & 0 deletions utilities/FileExporter.py
Original file line number Diff line number Diff line change
@@ -0,0 +1,104 @@
#!/usr/bin/env python3
# encoding: UTF-8

"""
IPGeoLocation - Retrieve IP Geolocation information
Powered by http://ip-api.com
Copyright (C) 2015 @maldevel
This program is free software: you can redistribute it and/or modify
it under the terms of the GNU General Public License as published by
the Free Software Foundation, either version 3 of the License, or
(at your option) any later version.
This program is distributed in the hope that it will be useful,
but WITHOUT ANY WARRANTY; without even the implied warranty of
MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
GNU General Public License for more details.
You should have received a copy of the GNU General Public License
along with this program. If not, see <http://www.gnu.org/licenses/>.
"""

__author__ = 'maldevel'

import csv
from xml.etree import ElementTree as etree
from collections import OrderedDict

class FileExporter:

def __init__(self):
pass


def ExportToCSV(self, ipGeoLocObj, filename):
try:
with open(filename, 'w', newline='') as csvfile:
writer = csv.writer(csvfile, delimiter=';', quoting=csv.QUOTE_MINIMAL)
writer.writerow(['Results', 'IPGeolocation'])
writer.writerow(['IP', ipGeoLocObj.IP])
writer.writerow(['ASN', ipGeoLocObj.ASN])
writer.writerow(['City', ipGeoLocObj.City])
writer.writerow(['Country', ipGeoLocObj.Country])
writer.writerow(['Country Code', ipGeoLocObj.CountryCode])
writer.writerow(['ISP', ipGeoLocObj.ISP])
writer.writerow(['Latitude', ipGeoLocObj.Latitude])
writer.writerow(['Longtitude', ipGeoLocObj.Longtitude])
writer.writerow(['Organization', ipGeoLocObj.Organization])
writer.writerow(['Region', ipGeoLocObj.Region])
writer.writerow(['Region Name', ipGeoLocObj.RegionName])
writer.writerow(['Timezone', ipGeoLocObj.Timezone])
writer.writerow(['Zip', ipGeoLocObj.Zip])
return True
except:
return False


def ExportToXML(self, ipGeoLocObj, filename):
try:
data = {'IP':ipGeoLocObj.IP, 'ASN':ipGeoLocObj.ASN, 'City':ipGeoLocObj.City, 'Country':ipGeoLocObj.Country,
'Country Code':ipGeoLocObj.CountryCode, 'ISP':ipGeoLocObj.ISP, 'Latitude':str(ipGeoLocObj.Latitude),
'Longtitude':str(ipGeoLocObj.Longtitude), 'Organization':ipGeoLocObj.Organization,
'Region':ipGeoLocObj.Region, 'Region Name':ipGeoLocObj.RegionName, 'Timezone':ipGeoLocObj.Timezone,
'Zip':ipGeoLocObj.Zip
}
orderedData = OrderedDict(sorted(data.items()))

root = etree.Element('Results')
self.__add_items(etree.SubElement(root, 'IPGeolocation'),
((key.replace(' ', ''), value) for key, value in orderedData.items()))
tree = etree.ElementTree(root)
tree.write(filename, xml_declaration=True, encoding='utf-8')
return True
except:
return False


def ExportToTXT(self, ipGeoLocObj, filename):
try:
with open(filename, 'w') as txtfile:
txtfile.write('Results IPGeolocation\n')
txtfile.write('IP: {}\n'.format(ipGeoLocObj.IP))
txtfile.write('ASN: {}\n'.format(ipGeoLocObj.ASN))
txtfile.write('City: {}\n'.format(ipGeoLocObj.City))
txtfile.write('Country: {}\n'.format(ipGeoLocObj.Country))
txtfile.write('Country Code: {}\n'.format(ipGeoLocObj.CountryCode))
txtfile.write('ISP: {}\n'.format(ipGeoLocObj.ISP))
txtfile.write('Latitude: {}\n'.format(ipGeoLocObj.Latitude))
txtfile.write('Longtitude: {}\n'.format(ipGeoLocObj.Longtitude))
txtfile.write('Organization: {}\n'.format(ipGeoLocObj.Organization))
txtfile.write('Region: {}\n'.format(ipGeoLocObj.Region))
txtfile.write('Region Name: {}\n'.format(ipGeoLocObj.RegionName))
txtfile.write('Timezone: {}\n'.format(ipGeoLocObj.Timezone))
txtfile.write('Zip: {}\n'.format(ipGeoLocObj.Zip))
return True
except:
return False


def __add_items(self, root, items):
for name, text in items:
elem = etree.SubElement(root, name)
elem.text = text

20 changes: 20 additions & 0 deletions utilities/__init__.py
Original file line number Diff line number Diff line change
@@ -0,0 +1,20 @@
"""
IPGeoLocation - Retrieve IP Geolocation information
Powered by http://ip-api.com
Copyright (C) 2015 @maldevel
This program is free software: you can redistribute it and/or modify
it under the terms of the GNU General Public License as published by
the Free Software Foundation, either version 3 of the License, or
(at your option) any later version.
This program is distributed in the hope that it will be useful,
but WITHOUT ANY WARRANTY; without even the implied warranty of
MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
GNU General Public License for more details.
You should have received a copy of the GNU General Public License
along with this program. If not, see <http://www.gnu.org/licenses/>.
"""

__author__ = 'maldevel'

0 comments on commit fd5e8f7

Please sign in to comment.