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
745 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
[X]
Welcome to Experts Exchange

Add your voice to the tech community where 5M+ people just like you are talking about what matters.

  • Help others & share knowledge
  • Earn cash & points
  • Learn & ask questions
  • 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

Do you have a plan for Continuity?

It's inevitable. People leave organizations creating a gap in your service. That's where Percona comes in.

See how Pepper.com relies on Percona to:
-Manage their database
-Guarantee data safety and protection
-Provide database expertise that is available for any situation

Question has a verified solution.

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

Join Greg Farro and Ethan Banks from Packet Pushers (http://packetpushers.net/podcast/podcasts/pq-show-93-smart-network-monitoring-paessler-sponsored/) and Greg Ross from Paessler (https://www.paessler.com/prtg) for a discussion about smart network …
PRTG Network Monitor lets you monitor your bandwidth usage, so you know who is using up your bandwidth, and what they're using it for.
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.
This video gives you a great overview about bandwidth monitoring with SNMP and WMI with our network monitoring solution PRTG Network Monitor (https://www.paessler.com/prtg). If you're looking for how to monitor bandwidth using netflow or packet s…

626 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