安装scapy
apt install -y python3-scapy
1. 发送dhcp discover广播报文
2. sniff抓包,收到dhcp offer广播报文
3. 发送dhcp request广播报文
4. sniff抓包,收到dhcp ack广播报文
import threading
from scapy.all import *
from scapy.layers.l2 import Ether
def send_dhcp_discover(mac):
xid = 1111
eth = Ether(src = mac, dst = "FF:FF:FF:FF:FF:FF")
ip = scapy.all.IP(proto = 17, src ="0.0.0.0", dst = "255.255.255.255")
udp = scapy.all.UDP(sport = 68, dport = 67)
bootp = scapy.all.BOOTP(op = 1, xid = xid, htype = 1, hlen = 6, chaddr = mac)
dhcp = scapy.all.DHCP(options=[("message-type","discover"), "end"])
discover_pkt = eth/ip/udp/bootp/dhcp
sendp(discover_pkt, iface="ens33", verbose=False)
def send_dhcp_request(xid, mac, dhcp_offer_ip, dhcp_server_ip):
eth = Ether(src = mac, dst = "FF:FF:FF:FF:FF:FF")
ip = scapy.all.IP(proto = 17, src ="0.0.0.0", dst = "255.255.255.255")
udp = scapy.all.UDP(sport = 68, dport = 67)
bootp = scapy.all.BOOTP(op = 1, htype = 1, hlen = 6, hops = 0, xid = xid)
dhcp = scapy.all.DHCP(options=[("message-type", "request"), ("requested_addr", dhcp_offer_ip), ("server_id", dhcp_server_ip), "end"])
request_pkt = eth/ip/udp/bootp/dhcp
sendp(request_pkt, iface="ens33", verbose=False)
class HandlePktThread(threading.Thread):
def __init__(self):
super().__init__()
def run(self):
def handle_offer_pkt(pkt):
if pkt.getlayer("DHCP").options[0][1] == 2:
print("get dhcp offer")
xid = pkt["BOOTP"].xid
mac = pkt["BOOTP"].chaddr
dhcp_offer_ip = pkt["BOOTP"].yiaddr
dhcp_server_ip = pkt["BOOTP"].siaddr
send_dhcp_request(xid, mac, dhcp_offer_ip, dhcp_server_ip)
elif pkt.getlayer("DHCP").options[0][1] == 5:
print("get dhcp ack")
sniff(prn=handle_offer_pkt, iface="ens33", filter="udp and (port 68 or port 67)", timeout=3)
if __name__ == "__main__":
mac = "01:02:03:04:05:06"
handle = HandlePktThread()
handle.start()
send_dhcp_discover(mac)
标签:xid,pkt,Python,ip,scapy,FF,dhcp From: https://www.cnblogs.com/WJQ2017/p/18064424