簡體   English   中英

使用BPF過濾器時python腳本的CPU利用率

[英]CPU utilization of python script when I used BPF filters

我從這里得到代碼。

from binascii import hexlify
from ctypes import create_string_buffer, addressof
from socket import socket, AF_PACKET, SOCK_RAW, SOL_SOCKET
from struct import pack, unpack

sniff_interval=120
# A subset of Berkeley Packet Filter constants and macros, as defined in
# linux/filter.h.

# Instruction classes
BPF_LD = 0x00
BPF_JMP = 0x05
BPF_RET = 0x06

# ld/ldx fields
BPF_H = 0x08
BPF_B = 0x10
BPF_ABS = 0x20

# alu/jmp fields
BPF_JEQ = 0x10
BPF_K = 0x00

def bpf_jump(code, k, jt, jf):
    return pack('HBBI', code, jt, jf, k)

def bpf_stmt(code, k):
    return bpf_jump(code, k, 0, 0)


# Ordering of the filters is backwards of what would be intuitive for
# performance reasons: the check that is most likely to fail is first.
filters_list = [
    # Must have dst port 67. Load (BPF_LD) a half word value (BPF_H) in
    # ethernet frame at absolute byte offset 36 (BPF_ABS). If value is equal to
    # 67 then do not jump, else jump 5 statements.
    bpf_stmt(BPF_LD | BPF_H | BPF_ABS, 36),
    bpf_jump(BPF_JMP | BPF_JEQ | BPF_K, 5201, 0, 5),

    # Must be UDP (check protocol field at byte offset 23)
    bpf_stmt(BPF_LD | BPF_B | BPF_ABS, 23),
    bpf_jump(BPF_JMP | BPF_JEQ | BPF_K, 0x06, 0, 3),

    # Must be IPv4 (check ethertype field at byte offset 12)
    bpf_stmt(BPF_LD | BPF_H | BPF_ABS, 12),
    bpf_jump(BPF_JMP | BPF_JEQ | BPF_K, 0x0800, 0, 1),

    bpf_stmt(BPF_RET | BPF_K, 0x0fffffff), # pass
    bpf_stmt(BPF_RET | BPF_K, 0), # reject
]

# Create filters struct and fprog struct to be used by SO_ATTACH_FILTER, as
# defined in linux/filter.h.
filters = ''.join(filters_list)
b = create_string_buffer(filters)
mem_addr_of_filters = addressof(b)
fprog = pack('HL', len(filters_list), mem_addr_of_filters)

# As defined in asm/socket.h
SO_ATTACH_FILTER = 26

# Create listening socket with filters
s = socket(AF_PACKET, SOCK_RAW, 0x0800)
s.setsockopt(SOL_SOCKET, SO_ATTACH_FILTER, fprog)
s.bind(('eth0', 0x0800))

while True:
    data, addr = s.recvfrom(65565)
    #print "*****"
    print 'got data from', addr, ':', hexlify(data) #Have to print data, then only the CPU is 2%

我正在使用iperf3進行測試,通過以太網電纜將另一台筆記本電腦傳輸到我的筆記本電腦。 服務器(“我的筆記本電腦”)在5021上列出,而客戶端(“另一台筆記本電腦”)正在發送數據。

  • 如果我注釋print 'got data from', addr, ':', hexlify(data)並運行腳本,則該腳本的CPU使用率將提高30%,在100MB流量的情況下將提高40%。
  • 如果我取消注釋print 'got data from', addr, ':', hexlify(data)並再次運行,則在存在相同流量的情況下,CPU會降低到2% 我檢查了htop

那么,這里的內容是什么?

我敢打賭hexlify()或最有可能的print (因為它必須與STDOUT同步)正在給您的主線程一個非常需要的休息時間和一個喘氣的空間,而不是僅僅在無窮大的while沖擊套接字的讀數環

嘗試添加time.sleep(0.05) (當然,首先要導入time )而不是print語句,然后再次檢查CPU使用率。

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM