本文整理汇总了Python中scapy.packet方法的典型用法代码示例。如果您正苦于以下问题:Python scapy.packet方法的具体用法?Python scapy.packet怎么用?Python scapy.packet使用的例子?那么恭喜您, 这里精选的方法代码示例或许可以为您提供帮助。您也可以进一步了解该方法所在类scapy
的用法示例。
在下文中一共展示了scapy.packet方法的15个代码示例,这些例子默认根据受欢迎程度排序。您可以为喜欢或者感觉有用的代码点赞,您的评价将有助于系统推荐出更棒的Python代码示例。
示例1: apply
# 需要导入模块: import scapy [as 别名]
# 或者: from scapy import packet [as 别名]
def apply(self, pkt_list):
"""Fragment each IPv6 packet. See `Mod.apply` for more details."""
new_pl = PacketList()
for pkt in pkt_list:
if pkt.pkt.haslayer('IP'):
fragments = scapy.layers.inet.fragment(pkt.pkt, self.fragsize)
index = len(new_pl) - 1
for fragment in fragments:
new_pl.add_packet(fragment)
new_pl.edit_delay(index, pkt.delay)
else:
# Not IPv4 so no fragmentation
new_pl.add_packet(fragment, pkt.delay)
return new_pl
示例2: fragment6
# 需要导入模块: import scapy [as 别名]
# 或者: from scapy import packet [as 别名]
def fragment6(pkt, fragsize):
"""Fragment an IPv6 Scapy packet in fragments of size `fragsize`.
`scapy.layers.inet6.fragment6` is not sufficient alone since it requires
to already have a Fragment Extension Header in the packet (it used to
indicate to Scapy where to split the Extension Header chain). This function
inserts this Fragment Extension Header automatically according to the RFC
and fragments the packets.
Args:
pkt: The IPv6 Scapy packet to fragment
Returns:
A list of fragments (IPv6 packets) of size `fragsize`.
Examples:
>>> fragment6(IPv6()/IPv6ExtHdrRouting()/AH()/TCP()/"PLOP"*100, 30)
"""
return scapy.layers.inet6.fragment6(ipv6_insert_frag_hdr(pkt), fragsize)
示例3: ipv6_get_per_frag_hdr
# 需要导入模块: import scapy [as 别名]
# 或者: from scapy import packet [as 别名]
def ipv6_get_per_frag_hdr(pkt):
"""Returns the last 'Scapy layer' of the "Per-Fragment Headers" part of
the packet.
The "Per-Fragment Headers" part is the chain of IPv6 headers that is
repeated for every fragment because they are useful for routing and
defragmenting.
Args:
pkt: The Scapy packet to examine.
Returns:
A reference to the last 'Scapy layer' of the "Per-Fragment Headers".
Examples:
>>> get_per_frag_hdr(IPv6()/IPv6ExtHdrRouting()/AH()/TCP()/"PLOP")
<IPv6ExtHdrRouting nh=AH Header |<AH |<TCP |<Raw load='PLOP' |>>>>
"""
current = pkt
ret = current
while current is not scapy.packet.NoPayload():
if name(current) in IPV6_PROCESS_HEADERS:
ret = current
current = current.payload
return ret
示例4: verify_packet_in
# 需要导入模块: import scapy [as 别名]
# 或者: from scapy import packet [as 别名]
def verify_packet_in(self, exp_pkt, exp_in_port, timeout=2):
pkt_in_msg = self.get_packet_in(timeout=timeout)
in_port_ = stringify(exp_in_port, 2)
exp_pkt_in = p4runtime_pb2.PacketIn()
exp_pkt_in.payload = str(exp_pkt)
ingress_physical_port = exp_pkt_in.metadata.add()
ingress_physical_port.metadata_id = 0
ingress_physical_port.value = in_port_
tvutils.add_packet_in_expectation(self.tc, exp_pkt_in)
rx_in_port_ = pkt_in_msg.metadata[0].value
if in_port_ != rx_in_port_:
rx_inport = struct.unpack("!h", rx_in_port_)[0]
self.fail("Wrong packet-in ingress port, expected {} but received was {}"
.format(exp_in_port, rx_inport))
rx_pkt = Ether(pkt_in_msg.payload)
if not match_exp_pkt(exp_pkt, rx_pkt):
self.fail("Received packet-in is not the expected one\n" + format_pkt_match(rx_pkt, exp_pkt))
示例5: ipv6_insert_frag_hdr
# 需要导入模块: import scapy [as 别名]
# 或者: from scapy import packet [as 别名]
def ipv6_insert_frag_hdr(pkt):
"""Inserts a "Fragment Extension Header" in a packet just after the
"Per-Fragment Headers" part.
Args:
pkt: The packet to modify.
Returns:
The same packet with a well-placed Fragment Extension Header.
Examples:
>>> insert_frag_hdr(IPv6()/IPv6ExtHdrRouting()/AH()/TCP()/"PLOP")
<IPv6 nh=Routing Header |
<IPv6ExtHdrRouting nh=Fragment Header |
<IPv6ExtHdrFragment nh=AH Header |
<AH |
<TCP |
<Raw load='PLOP' |>>>>>>
"""
current = ipv6_get_per_frag_hdr(pkt)
current.payload = (
scapy.layers.inet6.IPv6ExtHdrFragment(nh=current.nh)
/ current.payload
)
try:
current.nh = IPV6_NH_FRAG
except AttributeError:
pass
return pkt
示例6: replace_exthdr
# 需要导入模块: import scapy [as 别名]
# 或者: from scapy import packet [as 别名]
def replace_exthdr(before, exthdr, after):
"""Rebuilds a packet from the three parts as in `slice_exthdr`.
It does not return the packet but instead modifies it directly.
This avoiding having the need to pass a reference to the first
layer.
Args:
before: The 'before the Extension Headers' part.
exthdr: The new chain of 'Extension Headers'.
after: The 'after the Extension Headers' part.
Examples:
>>> pkt = IPv6()/IPv6ExtHdrRouting()
>>> replace_exthdr(
... pkt,
... [IPv6ExtHdrRouting(), AH()],
... TCP()/"PLOP"
... )
>>> pkt
<IPv6 nh=Routing Header |
<IPv6ExtHdrRouting nh=AH Header |
<AH |
<TCP |
<Raw load='PLOP' |>>>>>
"""
if not exthdr:
return
new_chain = exthdr[0]
current = new_chain
i = 1
while i < len(exthdr):
current.payload = exthdr[i]
i += 1
current = current.payload
# Add the 'before' before the new chain of Extension Headers
before.payload = new_chain
# Add the 'after' after the last Extension Header
current.payload = after
示例7: apply
# 需要导入模块: import scapy [as 别名]
# 或者: from scapy import packet [as 别名]
def apply(self, pkt_list):
"""Mixes-up the order of the Extension Headers for each IPv6 packet.
See `Mod.apply` for more info."""
for pkt in pkt_list:
if pkt.pkt.haslayer('IPv6'):
before, chain, after = slice_exthdr(pkt.pkt)
random.shuffle(chain)
replace_exthdr(before, chain, after)
return pkt_list
示例8: format_pkt_match
# 需要导入模块: import scapy [as 别名]
# 或者: from scapy import packet [as 别名]
def format_pkt_match(received_pkt, expected_pkt):
# Taken from PTF dataplane class
stdout_save = sys.stdout
try:
# The scapy packet dissection methods print directly to stdout,
# so we have to redirect stdout to a string.
sys.stdout = StringIO()
print "========== EXPECTED =========="
if isinstance(expected_pkt, scapy.packet.Packet):
scapy.packet.ls(expected_pkt)
print '--'
scapy.utils.hexdump(expected_pkt)
print "========== RECEIVED =========="
if isinstance(received_pkt, scapy.packet.Packet):
scapy.packet.ls(received_pkt)
print '--'
scapy.utils.hexdump(received_pkt)
print "=============================="
return sys.stdout.getvalue()
finally:
sys.stdout.close()
sys.stdout = stdout_save # Restore the original stdout.
# Used to indicate that the gRPC error Status object returned by the server has
# an incorrect format.
示例9: get_packet_in
# 需要导入模块: import scapy [as 别名]
# 或者: from scapy import packet [as 别名]
def get_packet_in(self, timeout=2):
msg = self.get_stream_packet("packet", timeout)
if msg is None:
self.fail("Packet in not received")
else:
return msg.packet
示例10: send_packet_out
# 需要导入模块: import scapy [as 别名]
# 或者: from scapy import packet [as 别名]
def send_packet_out(self, packet):
packet_out_req = p4runtime_pb2.StreamMessageRequest()
packet_out_req.packet.CopyFrom(packet)
tvutils.add_packet_out_operation(self.tc, packet)
self.stream_out_q.put(packet_out_req)
示例11: ICMPExtension_post_dissection
# 需要导入模块: import scapy [as 别名]
# 或者: from scapy import packet [as 别名]
def ICMPExtension_post_dissection(self, pkt):
# RFC4884 section 5.2 says if the ICMP packet length
# is >144 then ICMP extensions start at byte 137.
lastlayer = pkt.lastlayer()
if not isinstance(lastlayer, conf.padding_layer):
return
if IP in pkt:
if (ICMP in pkt and
pkt[ICMP].type in [3, 11, 12] and
pkt.len > 144):
bytes = pkt[ICMP].build()[136:]
else:
return
elif scapy.layers.inet6.IPv6 in pkt:
if ((scapy.layers.inet6.ICMPv6TimeExceeded in pkt or
scapy.layers.inet6.ICMPv6DestUnreach in pkt) and
pkt.plen > 144):
bytes = pkt[scapy.layers.inet6.ICMPv6TimeExceeded].build()[136:]
else:
return
else:
return
# validate checksum
ieh = ICMPExtensionHeader(bytes)
if checksum(ieh.build()):
return # failed
lastlayer.load = lastlayer.load[:-len(ieh)]
lastlayer.add_payload(ieh)
示例12: test_hci_advertising_report_event_ad_data
# 需要导入模块: import scapy [as 别名]
# 或者: from scapy import packet [as 别名]
def test_hci_advertising_report_event_ad_data():
raw_data = binascii.unhexlify(
"043e2b020100016522c00181781f0201020303d9fe1409"
"506562626c652054696d65204c452037314536020a0cde")
packet = HCI_Hdr(raw_data)
assert(packet[EIR_Flags].flags == 0x02)
assert(packet[EIR_CompleteList16BitServiceUUIDs].svc_uuids == [0xfed9])
assert(packet[EIR_CompleteLocalName].local_name == 'Pebble Time LE 71E6')
assert(packet[EIR_TX_Power_Level].level == 12)
示例13: test_hci_advertising_report_event_scan_resp
# 需要导入模块: import scapy [as 别名]
# 或者: from scapy import packet [as 别名]
def test_hci_advertising_report_event_scan_resp():
raw_data = binascii.unhexlify(
"043e2302010401be5e0eb9f04f1716ff5401005f423331"
"3134374432343631fc00030c0000de")
packet = HCI_Hdr(raw_data)
raw_mfg_data = '\x00_B31147D2461\xfc\x00\x03\x0c\x00\x00'
assert(packet[EIR_Manufacturer_Specific_Data].data == raw_mfg_data)
assert(packet[EIR_Manufacturer_Specific_Data].company_id == 0x154)
示例14: m2i
# 需要导入模块: import scapy [as 别名]
# 或者: from scapy import packet [as 别名]
def m2i(self, pkt, x):
if len(x) == 0:
return conf.raw_layer(),b""
raise ASN1_Error("ASN1F_CHOICE: got empty string")
#if ord(x[0]) not in self.choice:
if (x[0]) not in self.choice:
return conf.raw_layer(x),b"" # XXX return RawASN1 packet ? Raise error
#raise ASN1_Error("Decoding Error: choice [%i] not found in %r" % (ord(x[0]), self.choice.keys()))
raise ASN1_Error("Decoding Error: choice [%i] not found in %r" % ((x[0]), self.choice.keys()))
#z = ASN1F_PACKET.extract_packet(self, self.choice[ord(x[0])], x)
z = ASN1F_PACKET.extract_packet(self, self.choice[(x[0])], x)
return z
示例15: tcp_segment
# 需要导入模块: import scapy [as 别名]
# 或者: from scapy import packet [as 别名]
def tcp_segment(pkt, size, overlap=None, overlap_before=False):
"""Segment a TCP packet to a certain size.
Args:
pkt: The packet to segment
size: The size of the TCP data after segmentation
overlap: A string of data at the beginning or the end that overlaps
the other fragments
overlap_before: Should the overlap data be added at the beginning.
Else it is added at the end. Default is False.
Returns:
A list of L2-packets with TCP segments
Examples:
>>> tcp_segment(IP()/TCP()/"PLOP", 3)
[
<IP len=None frag=0 proto=tcp chksum=None |
<TCP seq=0 chksum=None |
<Raw load='PLO' |>>>,
<IP len=None frag=0 proto=tcp chksum=None |
<TCP seq=3 chksum=None |
<Raw load='P' |>>>
]
"""
payload = bytes(pkt.getlayer('TCP').payload)
tcp_l = len(payload)
if not tcp_l: # Trivial case
return [pkt]
nb_segments = (tcp_l-1)//size + 1
segments = [payload[i*size:(i+1)*size] for i in range(nb_segments)]
ret = []
for i, segment in enumerate(segments):
new_pkt = pkt.copy()
if overlap is not None:
# Add some data that overlaps the previous/next fragment
if overlap_before and i != 0:
# All segments except the first one
segment = overlap + segment
elif not overlap_before and i == len(segments) - 1:
# All segments except the last one
segment = segment + overlap
new_pkt.getlayer('TCP').payload = scapy.packet.Raw(segment)
new_pkt.getlayer('TCP').chksum = None
new_pkt.getlayer('TCP').seq = pkt.getlayer('TCP').seq + i*size
if new_pkt.haslayer('IP'):
new_pkt.getlayer('IP').len = None
new_pkt.getlayer('IP').chksum = None
elif new_pkt.haslayer('IPv6'):
new_pkt.getlayer('IPv6').plen = None
new_pkt.getlayer('IPv6').chksum = None
ret.append(new_pkt)
return ret