获取数据包的源地址和端口号-Scapy脚本 [英] Fetch source address and port number of packet - Scapy script

查看:509
本文介绍了获取数据包的源地址和端口号-Scapy脚本的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在嗅探网络,并尝试获取每个tcp数据包上的ip地址和端口号.

I am doing a sniffing of the network and trying to get ip address and port number on every tcp packet.

我将scapy与python一起使用,可以成功嗅探数据包,并且在回调函数中甚至可以打印数据包摘要.但是我想做更多的事情,例如仅获取源的IP地址及其端口号.我该怎么做呢?下面是我的代码:

I used scapy with python and could successfully sniff packets and in a callback function could even print the packet summary. But I would want to do more, like fetching only the IP address of the source and its port number. How can i accomplish it? Below is my code:

#!/usr/bin/evn python
from scapy.all.import.*
def print_summary(pkt):
    packet = pkt.summary()
    print packet
sniff(filter="tcp",prn=packet_summary)

请提出一种仅打印每个数据包的源IP地址的方法.

Please suggest a method to print only the source IP address of every packet.

谢谢.

推荐答案

这不是很困难.尝试以下代码:

It is not very difficult. Try the following code:

#!/usr/bin/env python
from scapy.all import *
def print_summary(pkt):
    if IP in pkt:
        ip_src=pkt[IP].src
        ip_dst=pkt[IP].dst
    if TCP in pkt:
        tcp_sport=pkt[TCP].sport
        tcp_dport=pkt[TCP].dport

        print " IP src " + str(ip_src) + " TCP sport " + str(tcp_sport) 
        print " IP dst " + str(ip_dst) + " TCP dport " + str(tcp_dport)

    # you can filter with something like that
    if ( ( pkt[IP].src == "192.168.0.1") or ( pkt[IP].dst == "192.168.0.1") ):
        print("!")

sniff(filter="ip",prn=print_summary)
# or it possible to filter with filter parameter...!
sniff(filter="ip and host 192.168.0.1",prn=print_summary)

享受!

这篇关于获取数据包的源地址和端口号-Scapy脚本的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆