Network sniffer in Python     (event-based)                  Jirka Vejražka (@JirkaV)                       @Pyvec - PyVo ...
Why?Because tcpdump was not right for the job               How?    pyevent + pypcap (by @dugsong)
The Code                 (Python 2.x)import pcapimport eventif_eth0 = pcap.pcap(‘eth0’) # needs rootpcap_file = get_PCAP_f...
Secret sauce? None!def get_PCAP_file():   pcap_f = open(‘packets.pcap’, ‘wb’)   pcap_f.write(PCAP_HEADER) # PCAP docs   re...
Filtering              (we don’t want it all)if_eth0 = pcap.pcap(‘eth0’)if_eth0.setfilter(‘icmp or tcp and port 80’)event....
Stopping It       (because a packet may never arrive)import signaldef stop_sniffing():   event.loop() # handle unprocessed...
Nice to Have                   (statistics)def print_stats(iface):   recvd, dropped, if_drops = iface.stats()   print ‘rec...
Questions?Kudos to @craigbalding for “rmmod perl && modprobepython” as well as the whole sniffer ideaThis presentation is ...
Upcoming SlideShare
Loading in …5
×

Python event based network sniffer

1,905 views

Published on

Presentation for @Pyvec #20

Published in: Technology
0 Comments
3 Likes
Statistics
Notes
  • Be the first to comment

No Downloads
Views
Total views
1,905
On SlideShare
0
From Embeds
0
Number of Embeds
60
Actions
Shares
0
Downloads
34
Comments
0
Likes
3
Embeds 0
No embeds

No notes for slide

Python event based network sniffer

  1. 1. Network sniffer in Python (event-based) Jirka Vejražka (@JirkaV) @Pyvec - PyVo #20
  2. 2. Why?Because tcpdump was not right for the job How? pyevent + pypcap (by @dugsong)
  3. 3. The Code (Python 2.x)import pcapimport eventif_eth0 = pcap.pcap(‘eth0’) # needs rootpcap_file = get_PCAP_file()event.read(if_eth0.fd, packets_handler, if_eth0)event.dispatch() # it all happens hereprint ‘All done, quitting’
  4. 4. Secret sauce? None!def get_PCAP_file(): pcap_f = open(‘packets.pcap’, ‘wb’) pcap_f.write(PCAP_HEADER) # PCAP docs return pcap_fdef packets_handler(iface): for timestamp, packet in iface.readpkts(): pcap_file.write(packet) return True
  5. 5. Filtering (we don’t want it all)if_eth0 = pcap.pcap(‘eth0’)if_eth0.setfilter(‘icmp or tcp and port 80’)event.dispatch()
  6. 6. Stopping It (because a packet may never arrive)import signaldef stop_sniffing(): event.loop() # handle unprocessed events event.abort()event.signal(signal.SIGTERM, stop_sniffing)event.signal(signal.SIGINT, stop_sniffing)
  7. 7. Nice to Have (statistics)def print_stats(iface): recvd, dropped, if_drops = iface.stats() print ‘received:’, recvd print ‘dropped:’, dropped return Trueevent.signal(signal.SIGUSR1, print_stats, if_eth0)event.timeout(60*15, print_stats, if_eth0)
  8. 8. Questions?Kudos to @craigbalding for “rmmod perl && modprobepython” as well as the whole sniffer ideaThis presentation is incredibly averagethanks to the Avería font from iotic.com/averia/

×