Solved

Need a Python script that listens on an IP port and logs attempts to connect to a file

Posted on 2012-03-28
5
728 Views
Last Modified: 2012-04-01
We have recently decommissioned a machine that was acting as a DNS server.  Many of the computers in our large office used this as a DNS server.  We have tried to go to each machine and edit the DNS settings to point to our new DNS servers but we've missed some workstations / devices.

I'd like to setup a temporary computer to the old DNS server's IP address and run a little python script that will listen on port 53 for incoming packets and when encountered writes a line to a text file which indicates either the ip address of the requesting machine or the MAC address or both and simply drops the packet without responding.

For someone with the expertise (not me) this would probably be a 20 line script.

The reason I'd like to use python is the abilty to use the same script (slightly modified) for monitoring other ports and situations.  (e.g. if we move an SQL server we can listen on that port for incoming requests on the old server.  Log the requests and find which computers need to be updated with the new location.)

Ideally the script would have something like:

MonitoredPort = 53
LogFile = "DNS_Requests_log"

[some code to open the port and listen on it]
[code that writes date-time and IP address to LogFile when a packet arrives]

Any pointers would be appreciated.

Thanks,

-Kendall
0
Comment
Question by:kdugger
  • 3
  • 2
5 Comments
 
LVL 9

Expert Comment

by:zaghaghi
ID: 37785092
Hi,

You can use twisted library for python (http://twistedmatrix.com)

I think that this post may help you (http://ziade.org/2010/09/30/twisted-rocks/).
0
 
LVL 9

Accepted Solution

by:
zaghaghi earned 500 total points
ID: 37785217
I wrote this simple script. hope it helps!
from datetime import datetime
from twisted.internet import protocol, reactor

MonitoredPort = 1234
LogFileName = "DNS_Requests_log"


class Logger(protocol.Protocol):
    def dataReceived(self, data):
        LogString = str(datetime.utcnow()) + "\t"
        LogString += self.transport.client[0] + "\t"
        LogString += str(self.transport.client[1]) + "\n"

        with open(LogFileName, mode='a') as LogFile:
            LogFile.write(LogString)

class LogFactory(protocol.Factory):
    def buildProtocol(self, addr):
        return Logger()


reactor.listenTCP(MonitoredPort, LogFactory())
reactor.run()

Open in new window


note that reactor object has listenUDP method!
0
 

Author Closing Comment

by:kdugger
ID: 37785606
Thanks  zaghaghi.

Genius.  Clear easy to read code that can easily be modified to suit other tasks.

It took me a bit to figure out how to get Python installed, Twisted installed, easy_install and Zope.interface installed.  This page helped me with those steps.

http://stackoverflow.com/questions/4182419/unable-to-install-twisted-package-on-windows-machine

I'll test the script tomorrow, but it clearly is exactly what I was looking for.

Cheers,

-Kendall
0
 

Author Comment

by:kdugger
ID: 37789154
I ran the script exactly as it appears, except with:

MonitoredPort = 53
LogFileName = "DNS_Requests_log.txt"


It never created the .txt file and consequently never logged anything.  I even setup another computer to use this machine as it's dns server to see if it would log anything and it did not.

Thinking that it might need to be listenUDP rather than listenTCP, I altered that line and reran the script:

from datetime import datetime
from twisted.internet import protocol, reactor

MonitoredPort = 53
LogFileName = "DNS_Requests_log.txt"


class Logger(protocol.Protocol):
    def dataReceived(self, data):
        LogString = str(datetime.utcnow()) + "\t"
        LogString += self.transport.client[0] + "\t"
        LogString += str(self.transport.client[1]) + "\n"

        with open(LogFileName, mode='a') as LogFile:
            LogFile.write(LogString)

class LogFactory(protocol.Factory):
    def buildProtocol(self, addr):
        return Logger()

reactor.listenUDP(MonitoredPort, LogFactory())
reactor.run()

>>> Traceback (most recent call last):
  File "C:\Python27\Lib\site-packages\pythonwin\pywin\framework\scriptutils.py", line 326, in RunScript
    exec codeObject in __main__.__dict__
  File "C:\Users\Administrator.DBMSLAW\Desktop\PortLoggingScript.py", line 2, in <module>
    from twisted.internet import protocol, reactor
  File "C:\Python27\lib\site-packages\twisted\internet\protocol.py", line 18, in <module>
    from twisted.python import log, failure, components
  File "C:\Python27\lib\site-packages\twisted\python\log.py", line 663, in <module>
    logfile = StdioOnnaStick(0, getattr(sys.stdout, "encoding", None))
  File "C:\Python27\Lib\site-packages\pythonwin\pywin\mfc\object.py", line 23, in __getattr__
    raise win32ui.error("The MFC object has died.")
error: The MFC object has died.

It doesn't die when I use listenTCP.

Any thoughts?



-Kendall
0
 
LVL 9

Expert Comment

by:zaghaghi
ID: 37789308
Hi,
for listenUDP you don't need a factory, and Logger class should inherits DatagramProtocol.

for more examples about udp listening see twisted documentation here: http://twistedmatrix.com/documents/current/core/howto/udp.html

Anyway here is modified version of script:
from datetime import datetime
from twisted.internet import protocol, reactor

MonitoredPort = 1235
LogFileName = "DNS_Requests_log"


class Logger(protocol.DatagramProtocol):
    def datagramReceived(self, data, (host, port)):
        LogString = str(datetime.utcnow()) + "\t"
        LogString += host + "\t"
        LogString += port + "\n"

        with open(LogFileName, mode='a') as LogFile:
            LogFile.write(LogString)

reactor.listenUDP(MonitoredPort, Logger())
reactor.run()

Open in new window

0

Featured Post

Top 6 Sources for Identifying Threat Actor TTPs

Understanding your enemy is essential. These six sources will help you identify the most popular threat actor tactics, techniques, and procedures (TTPs).

Join & Write a Comment

Suggested Solutions

So, you're experiencing issues on your network and you've decided that you need to perform some tests to determine whether your cabling is good.  You're likely thinking that you may need to spend money which you probably don't have on hiring/purchas…
The purpose of this article is to demonstrate how we can use conditional statements using Python.
Get a first impression of how PRTG looks and learn how it works.   This video is a short introduction to PRTG, as an initial overview or as a quick start for new PRTG users.
Here's a very brief overview of the methods PRTG Network Monitor (https://www.paessler.com/prtg) offers for monitoring bandwidth, to help you decide which methods you´d like to investigate in more detail.  The methods are covered in more detail in o…

760 members asked questions and received personalized solutions in the past 7 days.

Join the community of 500,000 technology professionals and ask your questions.

Join & Ask a Question

Need Help in Real-Time?

Connect with top rated Experts

17 Experts available now in Live!

Get 1:1 Help Now