0

I have two CSV files, one with IOC hits and a second that is a watchfile. The watchfile adds an @ to the file along with the IOC domain and last seen date. I'm trying to send one email when an IOC hit for that day, but I can't seem to get my loop right. Currently it emails every time, even though the @ is present in the watchfile.csv. I've printed the values for val and emailed and they show up in the correct format, but it still emails every time the script is ran.

finIOChit.csv last: 2017-01-17 query: rabbitons.pw,

watchfile.csv last: 2017-01-17 query: @ rabbitons.pw,

import smtplib
import csv
import os
import re
from datetime import *

today = date.today()
today = datetime.combine(today, datetime.min.time())

# Setup email alerting
sender = 'server@company.com'
receivers = ['user@company.com']

patn = re.compile('20\d{2}-\d{2}-\d{2}')

watchfile = open('watchfile.csv', 'r+w')
alreadyemailed = re.compile('@')

with open('finalIOChit.csv') as finalhit:
    for hit in finalhit:
        for line in watchfile:
            emailed = alreadyemailed.findall(line)
        for match in patn.findall(hit):
            val = datetime.strptime(match, '%Y-%m-%d')
        if val == today and emailed != '@':
            hit = re.sub('query: ','query: @ ',hit)
            watchfile.write(hit)
            message = """From:server <server@comapny.com>
                        To: user <user@company.com>
                        Subject: Passive DNS hit 
                        """
            subject = ' ' + str(hit)
            messagefull = message + subject 
            try:
                smtpObj = smtplib.SMTP('emailserver')
                smtpObj.sendmail(sender, receivers, messagefull)
            except SMTPException:
                print "Error: unable to send email"
obdnanr
  • 9
  • 2
  • are you sure that your regex is doing what you expect it to do? You can check it easily with this tool: https://regex101.com/ – matyas Jan 17 '17 at 16:07
  • 1
    Fixed the indentation for you. Check if its correct. From next time format your code properly. Use 4 spaces/1 tab and not 8 spaces/2 tabs. – Mohammad Yusuf Jan 17 '17 at 16:13
  • Did you check what `alreadyemailed.findall('2017-01-17 query: @ rabbitons.pw,')` returns? – Stop harming Monica Jan 17 '17 at 21:18
  • I'm sure the regex is working. Here's the output of printing my regex match and the @ sign. 2017-01-17 00:00:00 ['@'] 2017-01-17 00:00:00 ['@'] – obdnanr Jan 17 '17 at 21:47
  • Could you add small samples of your CSV files which recreate the problem? – Martin Evans Jan 18 '17 at 08:04
  • last: 2017-01-17 query: rabbitons.pw (finalIOChit.csv). last: 2017-01-17 query: @ rabbitons.pw (watchlist.csv). – obdnanr Jan 18 '17 at 13:41

0 Answers0