简体   繁体   中英

Using python to collect all inbound TCP traffic

I am trying to create a python linux script that listens for all inbound traffic. I do not want to listen to all traffic on one port. Any instructions or a pointer in the right direction would be highly appreciated. Thanks a ton!

This is only one option for capturing packets with python. While this example is short, it does demonstrate that you can capture packets destined for your system and save it to a PCAP. You could do much more to further filter/manipulate those packets but for demonstration purposes, it should be enough to get you started. Also, I'm installing this into a virtual environment instead of installing to my main system. This causes some complications with permissions but for demonstration purposes, I'll be executing my script as sudo . I would not do this in production.

Lets start by creating a virtual environment for our project:

python -m venv venv

Now lets activate it:

source venv/bin/activate

Now lets install scapy:

pip install scapy

Now that scapy is installed, lets write a sample script to capture a few packets destined for my computer at 10.1.10.127:

#! ./venv/bin/python
from scapy.all import sniff, PcapWriter

pkts = sniff(filter="dst 10.1.10.127", count=10)
my_pcap = PcapWriter('capture.pcap')
my_pcap.write(pkts)
my_pcap.close()

We'll save this in a file called sniff_it.py . The sniff function will capture the first 10 packets destined for my IP address on any interface. It will take those packets and write them to a PCAP file called capture.pcap . Again, you could easily add extra filtering/manipulation of the packets. You could also build a loop to put every 1000 packets in a different PCAP. Lets test it out.

chmod u+x sniff_it.py
sudo ./sniff_it.py

Once 10 packets have been captured, they should be written to capture.pcap .

tshark -r capture.pcap | head -n 5
1   0.000000 XXX.XXX.XXX.XXX → 10.1.10.127  QUIC 83 Payload (Encrypted), PKN: 38913
2   1.020419 XXX.XXX.XXX.XXX → 10.1.10.127  TCP 68 5228 → 46064 [ACK] Seq=1 Ack=1 Win=248 Len=0 TSval=1894173688 TSecr=2911532757
3   1.634172 XXX.XXX.XXX.XXX → 10.1.10.127  TCP 68 443 → 45268 [ACK] Seq=1 Ack=1 Win=36 Len=0 TSval=145613895 TSecr=3189134159
4   4.921444 XXX.XXX.XXX.XXX → 10.1.10.127  TCP 68 443 → 55626 [ACK] Seq=1 Ack=1 Win=325 Len=0 TSval=751056060 TSecr=3131256344
5   4.921498 XXX.XXX.XXX.XXX → 10.1.10.127  TCP 68 443 → 55626 [ACK] Seq=1 Ack=1397 Win=331 Len=0 TSval=751056060 TSecr=3131256349

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM