3

I know of the library requests, and urllib, and logging. However, from the examples I've perused, I can only seem to find the example where you specify a specific example - e.g. - requests.get('https://httpbin.org/headers'). Is there any way to continuously and actively monitor all incoming/outgoing connections, regardless of HTTP verb?

(I believe wireshark or fiddler can do this, but I am writing a program in Python and do not want any sort of wireshark or fiddler python extension.)

TheRealFakeNews
  • 7,512
  • 16
  • 73
  • 114

2 Answers2

1

You may want to try pypcap:

Installation:

pip install pypcap

Usage 1 :

import pcap
sniffer = pcap.pcap(name=None, promisc=True, immediate=True, timeout_ms=50)
addr = lambda pkt, offset: '.'.join(str(ord(pkt[i])) for i in range(offset, offset + 4))
for ts, pkt in sniffer:
    print('%d\tSRC %-16s\tDST %-16s' % (ts, addr(pkt, sniffer.dloff + 12), addr(pkt, sniffer.dloff + 16)))

Usage 2:

import dpkt, pcap
pc = pcap.pcap()     # construct pcap object
pc.setfilter('icmp') # filter out unwanted packets
for timestamp, packet in pc:
    print dpkt.ethernet.Ethernet(packet)

Notes:

Pedro Lobito
  • 94,083
  • 31
  • 258
  • 268
0

I don't have sufficient reputation to comment, but the first code snippet didn't work for me on Python3. Maybe because I installed pypcap with the workaround here, I didn't need to invoke ord because the values in pkt were already integers. So my code was:

import pcap
sniffer = pcap.pcap(name=None, promisc=True, immediate=True, timeout_ms=50)
addr = lambda pkt, offset: '.'.join(str(pkt[i]) for i in range(offset, offset + 4))

for ts, pkt in sniffer:
    print('%d\tSRC %-16s\tDST %-16s' % (ts, addr(pkt, sniffer.dloff + 12), addr(pkt, sniffer.dloff + 16)))