Network Security Internet Technology Development Database Servers Mobile Phone Android Software Apple Software Computer Software News IT Information

In addition to Weibo, there is also WeChat

Please pay attention

WeChat public account

Shulou

How to use Scapy, a sharp tool for sending and receiving packets in Python

2025-03-30 Update From: SLTechnology News&Howtos shulou NAV: SLTechnology News&Howtos > Development >

Share

Shulou(Shulou.com)06/03 Report--

This article will explain in detail how to use Scapy, a sharp tool in Python, to send and receive packages. The content of the article is of high quality, so the editor will share it with you for reference. I hope you will have a certain understanding of the relevant knowledge after reading this article.

Today, we are talking about the module used by Python to send and receive network packets-scapy.

Preface

As we all know, we have a lot of data packets to send on the Internet every day, and then deal with the process of receiving and sending, which is a cyclic process.

This shows the sending and receiving data of many packets. So, what is a bag? Let's take a look.

Packet (packet) is a data unit in network communication transmission, which is generally called data packet, which is mainly composed of source address, destination address and net load data. Including Baotou and Baobao body, Baotou is a fixed length, the length of Baotou body is unchanged. A brief understanding of the definition of the next package, let's take a look at the use of scapy, a sharp tool for sending packets. (source: Baidu Encyclopedia-data package)

I. Common commands

1. Ls (): displays all supported packet objects, with or without parameters, and the parameters can be any specific packet.

As you can see, it contains all the contents. If we want to take a detailed look at the contents of a module, for example, I want to check ARP and tcp, we can do this:

What I want to tell you here is that we have to pay attention to case, ls (ARP) so that we can get the right result, and ls (arp) is wrong.

2. Lsc (): list all functions

The screen is full of English, the editor, my head is big, I do not know what kind of mood everyone is at this moment, ha.

3. Hide_defaults (): used to delete some items provided by users that are the same as default value.

A=IP () print (a.hide_defaults ())

4.display (): you can simply view the values of each parameter of the current packet.

A=IP () a.display ()

5. More commands

Command action show_interfaces () displays network card information str (pkt) assembly packet hexdump (pkt) hexadecimal dump ls (pkt) shows a list of field values pkt.summary ( ) A line of summary pkt.show () shows the aggregated packets (for example, the expanded view pkt.show2 () of the packet Calculated checksum) pkt.sprintf () fill the format string pkt.decode_payload_as () with packet fields change the decode mode of payload pkt.psdump () draw an explanatory PostScript chart pkt.pdfdump () draw an explanatory PDF pkt.command () Return the Scapy command nsummary () that can generate packets as above But specify the number of packets conversations () displays a session chart filter () returns a list of lambda filtered packets hexdump () returns a hexdump import_hexcap () for all packets to re-import hexdump into Scapy hexraw () Hexdump padding () that returns all packets Raw layer returns a hexdump nzpadding () with populated packets returns a hexdump plot () with non-zero padding packets () plans a lambda function applied to the packet list make table () according to the lambda function Display the table traceroute ("baidu.com") to view the traceroute function of the IP path export_object () packets are converted into base64-encoded Python data structures import_object () can re-import the output into save_session () save all session variables load_session () read guarantee The stored session fuzz () changes some default values that are not calculated (such as checksum checksums) The changed value is random, but matches the value of the field. 2. Sniffing packets from scapy.all import * pkt = sniff (iface = "Realtek PCIe GBE Family Controller", count = 3, filter='tcp',prn = lambda x: x.sprintf ('{IP:%IP.src%- >% IP.dst%\ n} {Raw:%Raw.load%\ n}') filter: filter condition iface: Nic interface name count: number of packets prn: callback function Usually in conjunction with lambda, the sprintf () function is used to control the input information to grab the tcp message with the source address of 192.168.3.3 and port 80: sniff (filter= "ip src 192.168.3.3 and tcp and tcp port 80", prn=lambda x:x.summary ()) grabs the packet with the destination address of 192.168.3.3 and tcp and tcp port 24: sniff (filter= "dst net 192.168"). Prn=lambda x:x.summary () grabs non-ICMP messages: sniff (filter= "not icmp", prn=lambda x:x.summary ()) prints out the summary of the crawled messages: sniff (filter= "icmp", prn=lambda x:x.summary (), count=10) prints out the source addresses of all IP messages: sniff (filter= "icmp", prn=lambda x: X [IP] .src) Count=10) III. Construct the packet pkt= Ether () / IP (dst='192.168.1.2') / TCP (dport=80)

When it comes to data packets, we have to talk about various protocols, and when we mention protocols, we naturally think of the OSI seven-layer model.

OSI seven-layer network model TCP/ IP four-layer conceptual model corresponds to network protocol application layer (Application) application layer HTTP, TFTP, FTP, NFS, WAIS, SMTP presentation layer (Presentation) application layer Telnet, Rlogin, SNMP, Gopher session layer (Session) application layer SMTP, DNS transport layer (Transport) transport layer TCP, UDP network layer (Network) network layer IP, ICMP, ARP, RARP, AKP, UUCP data link layer (Data Link) data link layer FDDI, Ethernet, Arpanet, PDN, SLIP, PPP Physical layer (Physical) data link layer IEEE 802.1A, IEEE 802.2 to IEEE 802.11

The above is the corresponding osi model of each network protocol, so what is the usage of each protocol? let's take a look at it.

IV. Usage of each protocol

1. Construct an IP package and pass in some parameters

# construct an IP packet and pass some parameters pkt = IP (dst= "192.168.1.2", ttl=10) ls (pkt) version: version number ihl: header length tos: service type len:IP packet length id: identifier flags: tag flag: slice offset ttl: lifetime proto: protocol type chksum: header check src: source IP address dst: destination IP address options: optional

2. Construct ARP package

# construct ARP package ARP (op=1, hwdst= "ff:ff:ff:ff:ff:ff", pdst=ip_address) # list of constructors of class arp: ls (ARP) hwtype: XShortField = (1) A value of 1 indicates an Ethernet address, others may also indicate a token ring address ptype: XShortEnumField = (2048) 0x0800 represents an IP address, and others may be in an ICMP/IGMP hwlen: ByteField = (6) ARP message Its value is 6 plen: ByteField = (4) in the ARP message, its value is 4 op: ShortEnumField = (1) the value is 1 or 2, representing the ARP request or response packet. 1.ARP request, 2.ARP reply, 3.RARP request, 4.RARP reply hwsrc: ARPSourceMACField = (None) the sender's Mac address. Psrc: SourceIPField = (None) sender IP address. Hwdst: MACField = ('00 Mac address.) destination Mac address. Pdst: IPField = ('0.0.0.0') destination IP address.

3. Construct Ether

# construct Ether Ether (dst= "ff:ff:ff:ff:ff:ff") ls (Ether) dst: DestMACField = (None) destination MAC src: SourceMACField = (None) source MAC type: XShortEnumField = (36864) to construct an Ethernet packet, you usually need to specify the destination and source MAC address. If not specified, the broadcast packet ff:ff:ff:ff:ff:ff is sent by default.

4. Construct TCP package

# construct TCP package sport: ShortEnumField = 20 (20) destination port dport: ShortEnumField = 80 (80) source port seq: IntField = 0 (0) ack: IntField = 0 (0) dataofs: BitField (4 bits) = None (None) reserved: BitField (3 bits) = 0 (0) flags: FlagsField (9 bits) = () window: ShortField = 8192 (8192) chksum: XShortField = None (None) urgptr: ShortField = 0 (0) options: TCPOptionsField = [] (baked') 5. Send a package Pick up the bag

It can be divided into two situations, and the usage is as follows:

1. Only send but not receive

Send (pkt, inter=0, loop=0, count=1, iface=N) pkt: packet inter: time interval between sending packets count: number of packets sent iface: network card interface name send (), sending packets in the third layer, without receiving function; send (IP (dst= "www.baidu.com", ttl=2) / ICMP () sendp (), sending packets in the second layer, without receiving function. Sr (Ether () / IP (dst= "www.baidu.com"))

2. Send and receive the package

Both sr () and sr1 () send packets at the third layer, and sr1 indicates that only the first reply is received. Sr (IP (dst= "www.baidu.com", ttl= (1pr 4)) / TCP (dport= [21 dst= 23 www.baidu.com 80], flags= "S") returns two values sr1 (IP (dst= "www.baidu.com", ttl= (1pr 4)) / ICMP () srloop (IP (dst= "www.baidu.com", ttl=1) / ICMP ()) # non-stop ping Baidu srloop (IP (dst= "www.baidu.com", ttl=1) / ICMP (), inter=3,count=2) # every 3 seconds ping A total of # inter indicates the interval. The number of count records srp () and srp1 () are both sent packets based on the second layer. Srp1 indicates that only the first reply srp (Ether () / IP (dst= "www.baidu.com")) srp1 (Ether () / IP (dst= "www.baidu.com")) is received. 6. SYN semi-open scan

When the TCP link specifies a port, the flags parameter is set to S for semi-open scanning. If the port is listening, return syn/ack, otherwise return rst/ack.

Sr1 (IP (dst= "192.168.1.2") / TCP (dport=80,flags= "S") VII. Packet serialization, deserialization

Serialization: save the packet object as a pcap file

Deserialization: reading the contents of pcap files

Pkt= Ether () / IP (dst='192.168.1.2') / TCP (dport=80) # writes the sniffed packet contents to the pcap file wrpcap ("hw.pcap", pkt) # reads the pcap file. Read=rdpcap ('hw.pcap') print (read [1]) # print sniffed packet data VIII, packet and string conversion

More intuitive and clear analysis of data.

Zfc= str (pkts [0]) z = Ether (zfc) IX. Import and export base64 codes

A method invented to make it easier for us to encrypt data.

If we capture the packet, how can it be parsed without being connected to the Internet?

Now you can use our offline packets to analyze the data:

Sniff (offline = "hw.pcap") # offline packet

Through the above study, we have a basic understanding of scapy, scapy is indeed very powerful, a few simple lines of command can achieve package delivery and collection, greatly saving our development time. If you study each of its commands in depth, you will find more interesting things, of course, such a powerful tool should not be used to do bad things!

On how to use the sharp tool Scapy in Python to share here, I hope the above content can be of some help to you, can learn more knowledge. If you think the article is good, you can share it for more people to see.

Welcome to subscribe "Shulou Technology Information " to get latest news, interesting things and hot topics in the IT industry, and controls the hottest and latest Internet news, technology news and IT industry trends.

Views: 0

*The comments in the above article only represent the author's personal views and do not represent the views and positions of this website. If you have more insights, please feel free to contribute and share.

Share To

Development

Wechat

© 2024 shulou.com SLNews company. All rights reserved.

12
Report