6.12 筆記法實例 (storage.py)

import os

def store_sample(file_object):
    sha256 = file_object.sha256
    
    folder = os.path.join('binaries', sha256[0], sha256[1], sha256[2], sha256[3])
    if not os.path.exists(folder):
        os.makedirs(folder, 0750)

    file_path = os.path.join(folder, sha256)

    if not os.path.exists(file_path):
        with open(file_path, 'wb') as stored:
            for chunk in file_object.get_chunks():
                stored.write(chunk)
    
    return file_path

def get_sample_path(sha256):
    path = os.path.join('binaries', sha256[0], sha256[1], sha256[2], sha256[3], sha256)
    if not os.path.exists(path):
        return None
    return path
主要兩個 function。

1. store_sample 
2. get_sample_path

store_sample 中,主要用 os.path.join 建立權限為 0750 的資料夾
資料夾共有五層
第一層:binaries
第二層至第五層,則以樣本 sha256 值的前四字母或數字為資料夾名稱。

隨後再用 sha256 為檔名,將檔案寫入資料夾中。

get_sample_path 中,功能是將 sample 的 path 回傳。

Last updated

Was this helpful?