Still celebrating National IT Professionals Day with 3 months of free Premium Membership. Use Code ITDAY17

x
?
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
Medium Priority
?
749 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 2000 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

Are You Ready for GDPR?

With the GDPR deadline set for May 25, 2018, many organizations are ill-prepared due to uncertainty about the criteria for compliance. According to a recent WatchGuard survey, a staggering 37% of respondents don't even know if their organization needs to comply with GDPR. Do you?

Question has a verified solution.

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

Article by: Swadhin
Introduction of Lists in Python: There are six built-in types of sequences. Lists and tuples are the most common one. In this article we will see how to use Lists in python and how we can utilize it while doing our own program. In general we can al…
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.
Monitoring a network: why having a policy is the best policy? Michael Kulchisky, MCSE, MCSA, MCP, VTSP, VSP, CCSP outlines the enormous benefits of having a policy-based approach when monitoring medium and large networks. Software utilized in this v…
Monitoring a network: how to monitor network services and why? Michael Kulchisky, MCSE, MCSA, MCP, VTSP, VSP, CCSP outlines the philosophy behind service monitoring and why a handshake validation is critical in network monitoring. Software utilized …

688 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