How to do it...

In this recipe, you will use UPX to pack a directory of files.

  1. Place upx.exe in a directory, A, and place a collection of samples in a directory, B, in A. For this example, B is Benign PE Samples UPX.
  2.  List the files of directory B:
import osfiles_path = "Benign PE Samples UPX/"files = os.listdir(files_path)file_paths = [files_path+x for x in files]
  1. Run upx against each file in B:
from subprocess import Popen, PIPEcmd = "upx.exe"for path in file_paths:    cmd2 = cmd+" \""+path+"\""    res = Popen(cmd2, stdout=PIPE).communicate()    print(res)
  1. Whenever an error occurs in packing, remove the original sample:
    if "error" in str(res[0]):        print(path)        os.remove(path)

Get Machine Learning for Cybersecurity Cookbook now with the O’Reilly learning platform.

O’Reilly members experience books, live events, courses curated by job role, and more from O’Reilly and nearly 200 top publishers.