turtle02
turtle02

Reputation: 613

Syslog data parsing using RE in python

I am dumping syslog data from my firewall and want to match connections going to a specific IP at my house. I am using this below code. The below code works as far a collecting all of the data but my IF statement never matches. I have tried without the unicode u'192.168.1.1' and without, if I just print the extracted IP's it does show up - see output below. using Python 2.7

 #!/usr/bin/env python

## Tiny Syslog Server in Python.
##
## This is a tiny syslog server that is able to receive UDP based syslog
## entries on a specified port and save them to a file.
## That's it... it does nothing else...
## There are a few configuration parameters.

LOG_FILE = 'youlogfile2.log'
HOST, PORT = "192.168.1.2", 514

#
# NO USER SERVICEABLE PARTS BELOW HERE...
#

import logging
import SocketServer
import re
server = u'192.168.1.254'

logging.basicConfig(level=logging.INFO, format='%(message)s', datefmt='', filename=LOG_FILE, filemode='a')

class SyslogUDPHandler(SocketServer.BaseRequestHandler):

    def handle(self):

        data = bytes.decode(self.request[0].strip())
        socket = self.request[1]
        ipDST = re.compile(r'dst=([0-9]+\.[0-9]+\.[0-9]+\.[0-9]+)')
        ipDSTExtracted = ipDST.findall(data)
        #print (ipDSTExtracted)
        if ipDSTExtracted == server:
            print (ipDSTExtracted)

        #print( "%s : " % self.client_address[0], str(data))
        logging.info(str(data))

if __name__ == "__main__":
    try:
        server = SocketServer.UDPServer((HOST,PORT), SyslogUDPHandler)
        server.serve_forever(poll_interval=0.5)
    except (IOError, SystemExit):
        raise
    except KeyboardInterrupt:
        print ("Crtl+C Pressed. Shutting down.") 

}

I got lots of matches in this output but im not sure if its maybe the brackets

[u'8.8.8.8']
[u'8.8.8.8']
[u'192.168.1.254']
[u'8.8.8.8']
[u'8.8.8.8']
[u'8.8.8.8']
[u'192.168.1.254']
[u'8.8.8.8']
[u'192.168.1.209']
[u'8.8.8.8']
[u'192.168.1.26']
[u'8.8.8.8']
[u'8.8.8.8']

I have tested in idle to see and the string version and unicode version will match each other but it does not seem to work in this setup.

Upvotes: 0

Views: 741

Answers (1)

larsks
larsks

Reputation: 311615

findall returns a list. If you compare a list (the result of findall) with a string (I'm assuming this is the content of your mediasite variable) then of course the comparison will always be false.

You probably want to compare your variable against each element return by findall. Something like:

for ip in ipDST.findall(data)
    if ip == mediasite:
        print (ipDSTExtracted)

Upvotes: 1

Related Questions