<p>我曾评论过一种改进方法,但我决定制定一个更完整的解决方案。这将不会有星号数据包中断,而只是打印标题作为漂亮的印刷字典,所以这可能对你有用,也可能不,但你也可以自定义它,以满足你的需要。除了格式化,这似乎是目前为止关于这个问题的最有效的方法,您可以委托一个函数来添加格式化并进一步解构dict</p>
<pre><code>#!/usr/bin/env python2
import argparse
import pprint
import sys
# Suppress scapy warning if no default route for IPv6. This needs to be done before the import from scapy.
import logging
logging.getLogger("scapy.runtime").setLevel(logging.ERROR)
# Try to import sniff from scapy.all and show error w/ install instructions if it cannot be imported.
try:
from scapy.all import sniff
except ImportError:
sys.stderr.write("ERROR: You must have scapy installed.\n")
sys.stderr.write("You can install it by running: sudo pip install -U 'scapy>=2.3,<2.4'")
exit(1)
# Try to import scapy_http.http and show error w/ install instructions if it cannot be imported.
try:
import scapy_http.http
except ImportError:
sys.stderr.write("ERROR: You must have scapy-http installed.\n")
sys.stderr.write("You can install it by running: sudo pip install -U 'scapy>=1.8'")
exit(1)
if __name__ == "__main__":
# Parser command line arguments and make them available.
parser = argparse.ArgumentParser(
formatter_class=argparse.ArgumentDefaultsHelpFormatter,
description="Print HTTP Request headers (must be run as root or with capabilities to sniff).",
)
parser.add_argument("--interface", "-i", help="Which interface to sniff on.", default="eth0")
parser.add_argument("--filter", "-f", help='BPF formatted packet filter.', default="tcp and port 80")
parser.add_argument("--count", "-c", help="Number of packets to capture. 0 is unlimited.", type=int, default=0)
args = parser.parse_args()
# Sniff for the data and print it using lambda instead of writing a function to pretty print.
# There is no reason not to use a function you write for this but I just wanted to keep the example simply while
# demoing how to only match HTTP requests and to access the HTTP headers as pre-created dict's instead of
# parsing the data as a string.
sniff(iface=args.interface,
promisc=False,
filter=args.filter,
lfilter=lambda x: x.haslayer(scapy_http.http.HTTPRequest),
prn=lambda pkt: pprint.pprint(pkt.getlayer(scapy_http.http.HTTPRequest).fields, indent=4),
count=args.count
)
</code></pre>