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
730 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

What is SQL Server and how does it work?

The purpose of this paper is to provide you background on SQL Server. It’s your self-study guide for learning fundamentals. It includes both the history of SQL and its technical basics. Concepts and definitions will form the solid foundation of your future DBA expertise.

Question has a verified solution.

If you are experiencing a similar issue, please ask a related question

Suggested Solutions

Quality of Service (QoS) options are nearly endless when it comes to networks today. This article is merely one example of how it can be handled in a hub-n-spoke design using a 3-tier configuration.
Outsource Your Fax Infrastructure to the Cloud (And come out looking like an IT Hero!) Relative to the many demands on today’s IT teams, spending capital, time and resources to maintain physical fax servers and infrastructure is not a high priority.
Learn the basics of strings in Python: declaration, operations, indices, and slicing. Strings are declared with quotations; for example: s = "string": Strings are immutable.: Strings may be concatenated or multiplied using the addition and multiplic…
Learn the basics of lists in Python. Lists, as their name suggests, are a means for ordering and storing values. : Lists are declared using brackets; for example: t = [1, 2, 3]: Lists may contain a mix of data types; for example: t = ['string', 1, T…

867 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

25 Experts available now in Live!

Get 1:1 Help Now