[英]Scapy: Alerting when known source ip found
我正在尝试用 python 编写一个脚本来嗅探网络上的每个数据包。 我对 Scapy 相当陌生,但我已经阅读了一些关于sniff
函数的文章,尤其是它的参数prn
。
我发现使用具有指定count
的sniff
功能将捕获那么多数据包。 并且prn
参数允许我对捕获的每个数据包运行自定义函数。 利用这些知识,我编写了以下代码。
#!/usr/bin/python3
from scapy.all import *
whitelist_src = []
def alert_me(pkt):
if IP in pkt:
ip_src=pkt[IP].src
ip_dst=pkt[IP].dst
with open('uniq_sources.txt') as f:
for line in f:
line = line.rstrip('\n')
whitelist_src.append(line)
if ip_src in whitelist_src:
print("We found a match.\n")
sniff(filter="ip", prn=alert_me, count=100)
当在 whitelist_src 中找到 ip 时,我期待以下输出:
We found a match.
不幸的是,我收到了这些错误,我无法理解它们。
Traceback (most recent call last):
File "./alert_me.py", line 20, in <module>
sniff(filter="ip", prn=alert_me, count=100)
File "/home/me/.local/lib/python3.8/site-packages/scapy/sendrecv.py", line 1036, in sniff
sniffer._run(*args, **kwargs)
File "/home/me/.local/lib/python3.8/site-packages/scapy/sendrecv.py", line 906, in _run
sniff_sockets[L2socket(type=ETH_P_ALL, iface=iface,
File "/home/me/.local/lib/python3.8/site-packages/scapy/arch/linux.py", line 398, in __init__
self.ins = socket.socket(socket.AF_PACKET, socket.SOCK_RAW, socket.htons(type)) # noqa: E501
File "/usr/lib/python3.8/socket.py", line 231, in __init__
_socket.socket.__init__(self, family, type, proto, fileno)
PermissionError: [Errno 1] Operation not permitted
我也在用 python 学习。 我希望我提供了适当数量的信息。
您的代码看起来不错,但调用sniff
函数需要 root 权限。 这就是引发异常的原因。 以 root 身份调用脚本应该可以解决问题。
编辑。 附带说明一下,我不知道这是不是有意为之,但是每次您收到数据包时,您的whitelist_src
都会随着文本文件中的 IP 增长。 此外,每次收到数据包时打开和读取文件也很耗时。 因此,我建议将您的with
语句移到alert_me
函数之外。 当然,如果您的文本文件可以在您的脚本运行时更新,这将不起作用。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.