Skip to content

Instantly share code, notes, and snippets.

@sh4t
Created August 27, 2015 01:45
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save sh4t/8a6bbc002ffcb5a4295e to your computer and use it in GitHub Desktop.
Save sh4t/8a6bbc002ffcb5a4295e to your computer and use it in GitHub Desktop.
Parse GMAIL via IMAP, within steam (label/folder) for emails containing IPv4 address and write to a file. My attempt to deal with brute forcing.
#!/usr/bin/env python
#
#
import sys
import imaplib
import getpass
import email
import email.header
import datetime
import re
import json
#from IPy import IP
#import BeautifulSoup
EMAIL_ACCOUNT = "my-account-here@gmail.com"
EMAIL_FOLDER = "steam"
def process_mailbox(M):
"""
Search through inbox/steam and find messages and print some
headers.
"""
counter=0
json_object = []
rv, data = M.search(None, "ALL")
if rv != 'OK':
print "No messages found!"
return
for num in data[0].split():
rv, data = M.fetch(num, '(RFC822)')
counter=counter+1;
if rv != 'OK':
print "ERROR getting message", num
return
msg = email.message_from_string(data[0][1])
#decode = email.header.decode_header(msg['Subject'])[0]
#subject = unicode(decode[0])
#body = msg.get_payload(1) #this is for html/mime
ip_pattern = re.compile('\d{1,3}\.\d{1,3}\.\d{1,3}\.\d{1,3}')
body = msg.get_payload(0) # just the plain-text version
date_tuple = email.utils.parsedate_tz(msg['Date'])
if date_tuple:
local_date = datetime.datetime.fromtimestamp(email.utils.mktime_tz(date_tuple))
ipv4 = re.findall(ip_pattern, body.as_string())
if ipv4:
entry = {'ip_address': ipv4, 'timestamp': local_date.strftime("%a, %d %b %Y %H:%M:%S")}
json_object.append(entry)
with open('steam.json', 'w') as outfile:
json.dump(json_object, outfile)
print "%s IPv4 addresses collected" % (counter)
M = imaplib.IMAP4_SSL('imap.gmail.com')
try:
rv, data = M.login(EMAIL_ACCOUNT, getpass.getpass())
except imaplib.IMAP4.error:
print "LOGIN FAILED!!! "
sys.exit(1)
print rv, data
rv, mailboxes = M.list()
# if rv == 'OK':
# print "Mailboxes:"
# print mailboxes
rv, data = M.select(EMAIL_FOLDER)
if rv == 'OK':
# print "Processing mailbox...\n"
process_mailbox(M)
M.close()
else:
print "ERROR: Unable to open mailbox ", rv
M.logout()
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment