import operator
import shutil
import struct
import sys,os
import time
# https://wiki.wireshark.org/Development/LibpcapFileFormat
def read_pkt_from_binary_file(f, pkt_len, list_data):
for i in range(0, pkt_len):
b = f.read(1)
list_data.append('0x%.2x' % ord(b))
def my_cmp(list1, list2):
if sys.version_info[0] >= 3: # Python 3
return operator.eq(list1, list2)
else: # Python 2
if (0 == cmp(list1, list2)):
return True
else:
return False
def _search_hex(list_to_be_found, last_list, cur_list, pkt_cnt, hdr):
list_len = len(list_to_be_found)
last_list_len = len(last_list)
ts_sec, ts_usec, incl_len, orig_len = struct.unpack('IIII', hdr)
### transfer to UTC from timestamp
utc = time.asctime(time.localtime(int(ts_sec)))
index = utc.rfind(' ')
utc = utc[0:index] # skip the year YYYY
for i in range(0, incl_len - list_len + 1):
if (True == my_cmp(list_to_be_found, cur_list[i:(i + list_len)])):
print(str(pkt_cnt) + ' ' + utc + '.' + str(ts_usec) + ' ' \
+ str(incl_len) + ' ' + str(orig_len) + ' offset = ' \
+ str(hex(i)))
new_list = last_list + cur_list
for i in range(0, len(new_list) - list_len + 1):
if ((True == my_cmp(list_to_be_found, new_list[i:(i + list_len)])) and \
(i < last_list_len) and ((i + list_len) > last_list_len)): # across border
print(str(pkt_cnt) + ' ' + utc + '.' + str(ts_usec) + ' ' \
+ str(incl_len) + ' ' + str(orig_len) + ' offset = ' \
+ str(hex(i)) + '---TCP sticky with last line')
def search_hex(file_name, list_to_be_found):
last_list = []
pkt_cnt = 1;
### skip the global header
offset = 24
f = open(file_name, 'rb')
while f:
f.seek(offset, os.SEEK_SET)
### packet header
hdr = f.read(16)
if len(hdr) == 0:
f.close()
break
offset += 16
ts_sec, ts_usec, incl_len, orig_len = struct.unpack('IIII', hdr)
### packet data
f.seek(offset, os.SEEK_SET)
cur_list = []
read_pkt_from_binary_file(f, incl_len, cur_list)
_search_hex(list_to_be_found, last_list, cur_list, pkt_cnt, hdr)
# save current packet as last for next comparing
last_list = cur_list
pkt_cnt += 1
offset += incl_len
def main():
arg0_proc_name = sys.argv[0]
if sys.argv[0].rfind(os.path.sep) > 0 :
index = sys.argv[0].rfind(os.path.sep)
arg0_proc_name = sys.argv[0][index+1:]
if len(sys.argv) < 3:
print('\nUsage: python ' + arg0_proc_name + ' \n')
print('python ' + arg0_proc_name + \
' 0x01 0x01 0x90 0x02\n')
sys.exit(0)
list_to_be_found = []
for i in range(2, len(sys.argv)):
list_to_be_found.append(sys.argv[i])
search_hex(sys.argv[1], list_to_be_found)
if __name__ == '__main__':
main()
原文链接:https://blog.csdn.net/zoosenpin/article/details/76104054