scapy)如何将ls()输出重定向到文件的值?

问题描述 投票:1回答:1
  • 问题:我想将ls()的stdout重定向为'out'的值。怎么做?下面是用于此的代码:
from scapy.all import *
import io
from contextlib import redirect_stdout
import sys

l3 = IP()
l4 = TCP()
packet = l3/l4

f = io.StringIO()
with redirect_stdout(f):
    packet.show()
out = f.getvalue()
print(out) 
scapy
1个回答
0
投票

您非常接近将ls输出重定向到变量。只需在with块中使用ls([pkt])

# print_packet.py
from scapy.all import *
import io
from contextlib import redirect_stdout

l3 = IP()
l4 = TCP()
packet = l3/l4

f = io.StringIO()
with redirect_stdout(f):
    ls(packet)
out = f.getvalue()
print("Packet Listing:", out, sep="\n\n")

运行它,我们得到

$ python print_packet.py
mbp:pcaptk rj$ python temp.py
Packet Listing:

version    : BitField (4 bits)                   = 4               (4)
ihl        : BitField (4 bits)                   = None            (None)
tos        : XByteField                          = 0               (0)
len        : ShortField                          = None            (None)
id         : ShortField                          = 1               (1)
flags      : FlagsField (3 bits)                 = <Flag 0 ()>     (<Flag 0 ()>)
frag       : BitField (13 bits)                  = 0               (0)
ttl        : ByteField                           = 64              (64)
proto      : ByteEnumField                       = 6               (0)
chksum     : XShortField                         = None            (None)
src        : SourceIPField                       = '127.0.0.1'     (None)
dst        : DestIPField                         = '127.0.0.1'     (None)
options    : PacketListField                     = []              ([])
--
sport      : ShortEnumField                      = 20              (20)
dport      : ShortEnumField                      = 80              (80)
seq        : IntField                            = 0               (0)
ack        : IntField                            = 0               (0)
dataofs    : BitField (4 bits)                   = None            (None)
reserved   : BitField (3 bits)                   = 0               (0)
flags      : FlagsField (9 bits)                 = <Flag 2 (S)>    (<Flag 2 (S)>)
window     : ShortField                          = 8192            (8192)
chksum     : XShortField                         = None            (None)
urgptr     : ShortField                          = 0               (0)
options    : TCPOptionsField                     = []              (b'')

您也可以删除未使用的sys导入。

© www.soinside.com 2019 - 2024. All rights reserved.