Python 使用 Scapy 获取 TCP 标志
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/20429674/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
Get TCP Flags with Scapy
提问by auino
I'm parsing a PCAP file and I need to extract TCP flags (SYN, ACK, PSH, URG, ...).
I'm using the packet['TCP'].flagsvalue to obtain all the flags at once.
我正在解析 PCAP 文件,我需要提取 TCP 标志(SYN、ACK、PSH、URG 等)。我正在使用该packet['TCP'].flags值一次获取所有标志。
pkts = PcapReader(infile)
for p in pkts:
F = bin(p['TCP'].flags)
print F, bin(F), p.summary()
# manual flags extraction from F
Is there a way to obtain a single TCP flag without manually extract it from packet['TCP'].flagsvalue?
有没有办法在不从packet['TCP'].flags值中手动提取它的情况下获取单个 TCP 标志?
采纳答案by Paulo Bu
Normally, the usual way to handle FLAGS is with a bitmap and bitwise operators. If your Packetclass doesn't have specific method to test for flags, the best thing you can do IMHO is to:
通常,处理 FLAGS 的常用方法是使用位图和按位运算符。如果您的Packet班级没有特定的方法来测试标志,恕我直言,您可以做的最好的事情是:
FIN = 0x01
SYN = 0x02
RST = 0x04
PSH = 0x08
ACK = 0x10
URG = 0x20
ECE = 0x40
CWR = 0x80
And test them like this:
并像这样测试它们:
F = p['TCP'].flags # this should give you an integer
if F & FIN:
# FIN flag activated
if F & SYN:
# SYN flag activated
# rest of the flags here
Sadly, python doesn't have a switchstatement to make this more elegant but it doesn't really matter much.
可悲的是,python 没有switch声明使这更优雅,但这并不重要。
Hope this helps!
希望这可以帮助!
回答by Pierre
You can use the Packet.sprintf()method:
您可以使用以下Packet.sprintf()方法:
>>> p = IP()/TCP(flags=18)
>>> p.sprintf('%TCP.flags%')
'SA'
If you want the "long" names, use a dictinstead of a long if...elif... expression (dictare often used in Python when you would use a switchin other languages):
如果您想要“长”名称,请使用 adict而不是 long if... elif... 表达式(dict当您switch在其他语言中使用 a 时,通常在 Python 中使用):
>>> flags = {
'F': 'FIN',
'S': 'SYN',
'R': 'RST',
'P': 'PSH',
'A': 'ACK',
'U': 'URG',
'E': 'ECE',
'C': 'CWR',
}
>>> [flags[x] for x in p.sprintf('%TCP.flags%')]
['SYN', 'ACK']
回答by Pierre
Another option, for the record, which did not exist by the time this question was asked. It works with current Scapy development version (the first release including this change will be 2.4.0; 2.4.0rc* also include it).
另一种选择,作为记录,在提出这个问题时还不存在。它适用于当前的 Scapy 开发版本(包含此更改的第一个版本将是 2.4.0;2.4.0rc* 也包含它)。
You can now use str()on the flag value:
您现在可以str()在标志值上使用:
>>> p = IP()/TCP(flags=18)
>>> p[TCP].flags
<Flag 18 (SA)>
>>> str(p[TCP].flags)
'SA'
回答by Dragonborn
This also works.
这也有效。
if packet[TCP].flags.F:
print('FIN received')

