Skip to content

Instantly share code, notes, and snippets.

@dhondta

dhondta/README.md

Last active Apr 23, 2021
Embed
What would you like to do?
Tinyscript tool for getting IP locations from an email (EML file)

Get Email Origin

This can be installed using:

$ pip install -r requirements.txt
$ wget https://gist.githubusercontent.com/dhondta/9a8027062ff770b2aa5d8422ddd78b57/raw/get-email-origin.py && chmod +x get-email-origin.py && sudo mv get-email-origin.py /usr/bin/get-email-origin
#!/usr/bin/python3
# -*- coding: UTF-8 -*-
import ipaddress
import mailparser
from geolite2 import geolite2
from tinyscript import *
__author__ = "Alexandre D'Hondt"
__version__ = "1.2"
__copyright__ = "A. D'Hondt"
__license__ = "agpl-3.0"
__doc__ = """
This tool loads an email and parses the receivers, indicating where the found IP addesses originate from.
"""
__examples__ = ["message.eml"]
IP_REGEX = re.compile(r'\d{1,3}\.\d{1,3}\.\d{1,3}\.\d{1,3}')
MMDDB = geolite2.reader()
def parse_eml(eml):
ips = []
found = False
logger.debug("Parsing receivers...")
for receiver in eml.received:
for addr in IP_REGEX.findall(receiver.get('raw', "")):
addr = ipaddress.ip_address(addr)
if str(addr) in ips:
continue
ips.append(str(addr))
logger.debug("Found: {}{}".format(addr, ["", " (private)"][addr.is_private]))
if not addr.is_private:
s, found = str(addr), True
d = MMDDB.get(s)
for f in ["city", "country", "continent"]:
i = d.get(f, {}).get('names', {}).get('en')
if i:
s += "\n{: <9}: {}".format(f.capitalize(), i)
l = d.get('location')
if l:
s += "\nLocation : Lat {} Lon {}".format(l['latitude'], l['longitude'])
try:
s += " ({})".format(l['time_zone'])
except:
pass
logger.info(s)
def valid_eml(filename):
try:
with open(filename) as f:
eml = mailparser.parse_from_file_obj(f)
return eml
except:
raise argparse.ArgumentTypeError
if __name__ == '__main__':
parser.add_argument("eml", type=valid_eml, help="email file")
initialize()
parse_eml(args.eml)
ipaddress
mail_parser
maxminddb-geolite2
tinyscript
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment