Advertisement
samicrusader

tarfuscate

May 8th, 2023
616
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
Python 2.24 KB | None | 0 0
  1. #!/usr/bin/env python3
  2.  
  3. import os
  4. import sys
  5. import hashlib
  6. import random
  7. import tarfile
  8. import shutil
  9. import subprocess
  10.  
  11. # Files by size (sorted ascending)
  12. filist = filter(lambda x: os.path.isfile(os.path.join(sys.argv[1], x)), os.listdir(sys.argv[1]))
  13. filist = sorted(filist, key=lambda x: os.stat(os.path.join(sys.argv[1], x)).st_size)
  14.  
  15. # Folders by size (sorted ascending)
  16. _fslist1 = filter(lambda x: os.path.isdir(os.path.join(sys.argv[1], x)), os.listdir(sys.argv[1]))
  17. _fslist2 = list()
  18. for dir in _fslist1:
  19.     path = os.path.join(sys.argv[1], dir)
  20.     total_size = 0
  21.     for dirpath, dirnames, filenames in os.walk(path): # walk directory for file sizes
  22.         for i in filenames:
  23.             total_size += os.path.getsize(os.path.join(dirpath, i))
  24.     _fslist2.append({'name': path, 'size': total_size})
  25. folist = list()
  26. for dirobj in list(sorted(_fslist2, key=lambda x: x['size'])):
  27.     folist.append(dirobj['name'])
  28.  
  29. # Totals
  30. files = list(filist) + list(folist)
  31.  
  32. try:
  33.     os.mkdir(sys.argv[1]+'_tar') # create dir if not exist
  34. except:
  35.     pass
  36.  
  37. for file in files:
  38.     bfn = os.path.join(sys.argv[1], file)
  39.     while True:
  40.         try: #generate random name
  41.             rb = random.getrandbits(256)
  42.             bytearray.fromhex('{:x}'.format(rb)).hex() + '.tar'
  43.         except: # this code can break but too lazy to fix it so just retry
  44.             continue
  45.         else:
  46.             fn = bytearray.fromhex('{:x}'.format(rb)).hex() + '.tar'
  47.             break
  48.     print(bfn)
  49.     ## Python-native tar
  50.     #with tarfile.open(os.path.join(sys.argv[1]+'_tar', fn), "w:") as tar:
  51.     #    tar.add(bfn, arcname=os.path.basename(bfn))
  52.     #    tar.close()
  53.     ## System tar (much faster)
  54.     try:
  55.         subprocess.check_output(['tar', 'cf', os.path.join(sys.argv[1]+'_tar', fn), '-C', sys.argv[1], os.path.basename(bfn)])
  56.     except subprocess.CalledProcessError as exc:
  57.         raise Exception(f'tar broke: {exc.returncode}: {exc.output}')
  58.     else:
  59.         if os.path.isfile(bfn) or os.path.islink(bfn):
  60.             os.remove(bfn)  # remove the file
  61.         elif os.path.isdir(bfn):
  62.             shutil.rmtree(bfn)  # nuke dir
  63.         else:
  64.             print(f'path {bfn} is not a file, dir or symlink, not deleting...')
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement