Go Premium for a chance to win a PS4. Enter to Win

x
  • Status: Solved
  • Priority: Medium
  • Security: Public
  • Views: 758
  • Last Modified:

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

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
kdugger
Asked:
kdugger
  • 3
  • 2
1 Solution
 
Hamed ZaghaghiCommented:
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
 
Hamed ZaghaghiCommented:
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
 
kduggerAuthor Commented:
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
 
kduggerAuthor Commented:
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
 
Hamed ZaghaghiCommented:
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

VIDEO: THE CONCERTO CLOUD FOR HEALTHCARE

Modern healthcare requires a modern cloud. View this brief video to understand how the Concerto Cloud for Healthcare can help your organization.

  • 3
  • 2
Tackle projects and never again get stuck behind a technical roadblock.
Join Now