官术网_书友最值得收藏!

How to do it...

In the following steps, we will collect notable portions of the PE header:

  1. Import pefile and modules for enumerating our samples:
import pefile
from os import listdir
from os.path import isfile, join

directories = ["Benign PE Samples", "Malicious PE Samples"]
  1. We define a function to collect the names of the sections of a file and preprocess them for readability and normalization:
def get_section_names(pe):
"""Gets a list of section names from a PE file."""
list_of_section_names = []
for sec in pe.sections:
normalized_name = sec.Name.decode().replace("\x00", "").lower()
list_of_section_names.append(normalized_name)
return list_of_section_names
  1. We define a convenience function to preprocess and standardize our imports:
def preprocess_imports(list_of_DLLs):
"""Normalize the naming of the imports of a PE file."""
return [x.decode().split(".")[0].lower() for x in list_of_DLLs]
  1. We then define a function to collect the imports from a file using pefile:
def get_imports(pe):
"""Get a list of the imports of a PE file."""
list_of_imports = []
for entry in pe.DIRECTORY_ENTRY_IMPORT:
list_of_imports.append(entry.dll)
return preprocess_imports(list_of_imports)
  1. Finally, we prepare to iterate through all of our files and create lists to store our features:
imports_corpus = []
num_sections = []
section_names = []
for dataset_path in directories:
samples = [f for f in listdir(dataset_path) if isfile(join(dataset_path, f))]
for file in samples:
file_path = dataset_path + "/" + file
try:
  1. In addition to collecting the preceding features, we also collect the number of sections of a file:
            pe = pefile.PE(file_path)
imports = get_imports(pe)
n_sections = len(pe.sections)
sec_names = get_section_names(pe)
imports_corpus.append(imports)
num_sections.append(n_sections)
section_names.append(sec_names)
  1. In case a file's PE header cannot be parsed, we define a try-catch clause:
        except Exception as e:
print(e)
print("Unable to obtain imports from " + file_path)

主站蜘蛛池模板: 四平市| 富阳市| 滕州市| 云浮市| 鹰潭市| 高阳县| 铜鼓县| 天水市| 八宿县| 克拉玛依市| 湖南省| 涞水县| 呼伦贝尔市| 台中县| 东海县| 呼图壁县| 扶沟县| 渝中区| 广河县| 双鸭山市| 呈贡县| 吴堡县| 石屏县| 赤峰市| 沭阳县| 甘南县| 宁陵县| 东源县| 三门峡市| 浮山县| 铜陵市| 东乌珠穆沁旗| 大关县| 崇左市| 英德市| 张北县| 西和县| 仁化县| 怀宁县| 沿河| 漯河市|