2011-05-03 72 views
3

我已經能夠基於這個例子中發現使用代碼的興趣分組:充分利用Python的TCP數據包有效負載和impacket

How can I filter a pcap file by specific protocol using python?

從TCP數據包中的下一個孩子是實際的數據:

if isinstance(child1, TCP): 
     if child1.get_th_dport() == 80: 
      x = child1.child() 
      print x 

這打印出像電線鯊魚一樣的數據包數據並顯示十六進制和ASCII碼版本。不過,至今我一直無法找到簡單獲取十六進制內容的方法。我知道我可以操縱可打印的輸出,但我認爲必須有一種方法來獲取十六進制格式的數據...

我已經瀏覽了示例,但似乎沒有人這樣做。任何人都知道正確的方法?

回答

2

您可以使用packet.get_data_as_string()來獲取原始字節,然後按照您的喜好顯示它。我複製了由print child產生的「十六進制列」輸出。應該很容易調整產生ASCII列,以及:

def display_hex(pkt, cols=8): 
    size = cols * 4 
    data = ''.join('%02x' % ord(b) for b in pkt.get_data_as_string()) 
    for i in range(0, len(data), size): 
     for j in range(0, size, 4): 
      print data[i+j:i+j+4], 
     print 

if isinstance(child, TCP): 
    display_hex(child) 

輸出:

1703 0103 b0b1 9387 be4e fe00 9230 6192 
e3bb 217e c1cb 8511 556f f986 4f31 542d 
15c6 f42e f3bb 93d5 cf33 f126 c174 dbc4 
... snip ... 
8b1d 8707 96d6 7a18 2aab fd0b 48ee c4eb 
b7d8 a67f 8bc0 597d 1044 a076 1a9e 24ba 
959b fda3 1adb 2384 669c e6c8 c3b5 bef4 
1189 eda8 3e 
+0

這是偉大的感謝。我需要的只是一個帶有十六進制數據的字符串,而不是格式化爲打印:) – PeterM 2011-05-03 03:35:32

+0

@PeterM酷 - 如果你需要它,它就是它。 :-) – samplebias 2011-05-03 03:39:48