Error unsupported pyinstaller version or not a pyinstaller archive

pyinstxtractor

ashclapz

[!] Error : Missing cookie, unsupported pyinstaller version or not a pyinstaller archive

im having a error [!] Error : Missing cookie, unsupported pyinstaller version or not a pyinstaller archive does anyone have a fix for this?

extremecoders-re

Can take a look if you attach the file in question.

ashclapz

sure
image

extremecoders-re

Hi, there can be many reasons. The screenshot is not enough to know why it didn’t work. Quite possible that its using a modified/custom pyinstaller.

ashclapz

basically im trying to get the source code of this file C:UsersuserAppDataRoamingPythonPython310Scriptspyinstaller.exe
the src of pyinstaller and whenever i use pyinstxtractor.py it wont work

extremecoders-re

EXE files in «Python/scripts» aren’t pyinstaller executables in general. They are script wrappers generated by setuptools and the likes during installation of a Python package.

ashclapz

Recommend Projects

  • React photo

    React

    A declarative, efficient, and flexible JavaScript library for building user interfaces.

  • Vue.js photo

    Vue.js

    🖖 Vue.js is a progressive, incrementally-adoptable JavaScript framework for building UI on the web.

  • Typescript photo

    Typescript

    TypeScript is a superset of JavaScript that compiles to clean JavaScript output.

  • TensorFlow photo

    TensorFlow

    An Open Source Machine Learning Framework for Everyone

  • Django photo

    Django

    The Web framework for perfectionists with deadlines.

  • Laravel photo

    Laravel

    A PHP framework for web artisans

  • D3 photo

    D3

    Bring data to life with SVG, Canvas and HTML. 📊📈🎉

Recommend Topics

  • javascript

    JavaScript (JS) is a lightweight interpreted programming language with first-class functions.

  • web

    Some thing interesting about web. New door for the world.

  • server

    A server is a program made to process requests and deliver data to clients.

  • Machine learning

    Machine learning is a way of modeling and interpreting data that allows a piece of software to respond intelligently.

  • Visualization

    Some thing interesting about visualization, use data art

  • Game

    Some thing interesting about game, make everyone happy.

Recommend Org

  • Facebook photo

    Facebook

    We are working to build community through open source technology. NB: members must have two-factor auth.

  • Microsoft photo

    Microsoft

    Open source projects and samples from Microsoft.

  • Google photo

    Google

    Google ❤️ Open Source for everyone.

  • Alibaba photo

    Alibaba

    Alibaba Open Source for everyone

  • D3 photo

    D3

    Data-Driven Documents codes.

  • Tencent photo

    Tencent

    China tencent open source team.

pyinstall пакет python3.7.1 exe декомпиляция

  Из-за EXE-файла, упакованного pyinstall, 360 считает, что это может быть вирус троянского коня.Прежде всего, есть подозрение, что компьютерная система является ядовитой. С помощью антивируса 360 было исследовано и обработано более десятка вирусов. Человек, не очень разбирающийся в компьютерах, может только следовать инструкциям 360. В результате горячие клавиши многих приложений теряются, а система дает сбой. , Переделал систему, случайно потерял исходные файлы python и потратил более полумесяца на тяжелую работу (я только что изучил python). К счастью, на компьютере устройства есть EXE-файл, и возникает идея декомпиляции.
     Я использую python 3.7.1, который немного отличается от информации, представленной в Интернете.Я проверяю информацию ежемесячно, практикуюсь, улучшаю и исследую, и в основном восстанавливаю исходные файлы python. Практический процесс выглядит следующим образом:
     Шаг 1. Декомпилируйте EXE в файл pyc.
                             Согласно информации, представленной в Интернете, я выбрал два файла archive_viewer.py и pyinstxtractor.py для декомпиляции exe (из-за декомпилированных файлов archive_viewer.py exe не удалось декомпилировать в PY в конце), и процесс работы не записывается Вверх.
       pyinstxtractor.py        
"""
PyInstaller Extractor v1.9 (Supports pyinstaller 3.3, 3.2, 3.1, 3.0, 2.1, 2.0)
Author : Extreme Coders
E-mail : extremecoders(at)hotmail(dot)com
Web    : https://0xec.blogspot.com
Date   : 29-November-2017
Url    : https://sourceforge.net/projects/pyinstallerextractor/

For any suggestions, leave a comment on
https://forum.tuts4you.com/topic/34455-pyinstaller-extractor/

This script extracts a pyinstaller generated executable file.
Pyinstaller installation is not needed. The script has it all.

For best results, it is recommended to run this script in the
same version of python as was used to create the executable.
This is just to prevent unmarshalling errors(if any) while
extracting the PYZ archive.

Usage : Just copy this script to the directory where your exe resides
        and run the script with the exe file name as a parameter

C:pathtoexe>python pyinstxtractor.py <filename>
$ /path/to/exe/python pyinstxtractor.py <filename>

Licensed under GNU General Public License (GPL) v3.
You are free to modify this source.

CHANGELOG
================================================

Version 1.1 (Jan 28, 2014)
-------------------------------------------------
- First Release
- Supports only pyinstaller 2.0

Version 1.2 (Sept 12, 2015)
-------------------------------------------------
- Added support for pyinstaller 2.1 and 3.0 dev
- Cleaned up code
- Script is now more verbose
- Executable extracted within a dedicated sub-directory

(Support for pyinstaller 3.0 dev is experimental)

Version 1.3 (Dec 12, 2015)
-------------------------------------------------
- Added support for pyinstaller 3.0 final
- Script is compatible with both python 2.x & 3.x (Thanks to Moritz Kroll @ Avira Operations GmbH & Co. KG)

Version 1.4 (Jan 19, 2016)
-------------------------------------------------
- Fixed a bug when writing pyc files >= version 3.3 (Thanks to Daniello Alto: https://github.com/Djamana)

Version 1.5 (March 1, 2016)
-------------------------------------------------
- Added support for pyinstaller 3.1 (Thanks to Berwyn Hoyt for reporting)

Version 1.6 (Sept 5, 2016)
-------------------------------------------------
- Added support for pyinstaller 3.2
- Extractor will use a random name while extracting unnamed files.
- For encrypted pyz archives it will dump the contents as is. Previously, the tool would fail.

Version 1.7 (March 13, 2017)
-------------------------------------------------
- Made the script compatible with python 2.6 (Thanks to Ross for reporting)

Version 1.8 (April 28, 2017)
-------------------------------------------------
- Support for sub-directories in .pyz files (Thanks to Moritz Kroll @ Avira Operations GmbH & Co. KG)

Version 1.9 (November 29, 2017)
-------------------------------------------------
- Added support for pyinstaller 3.3
- Display the scripts which are run at entry (Thanks to Michael Gillespie @ malwarehunterteam for the feature request)

"""

from __future__ import print_function
import os
import struct
import marshal
import zlib
import sys
import imp
import types
from uuid import uuid4 as uniquename


class CTOCEntry:
    def __init__(self, position, cmprsdDataSize, uncmprsdDataSize, cmprsFlag, typeCmprsData, name):
        self.position = position
        self.cmprsdDataSize = cmprsdDataSize
        self.uncmprsdDataSize = uncmprsdDataSize
        self.cmprsFlag = cmprsFlag
        self.typeCmprsData = typeCmprsData
        self.name = name


class PyInstArchive:
    PYINST20_COOKIE_SIZE = 24           # For pyinstaller 2.0
    PYINST21_COOKIE_SIZE = 24 + 64      # For pyinstaller 2.1+
    MAGIC = b'MEI1413121316'  # Magic number which identifies pyinstaller

    def __init__(self, path):
        self.filePath = path


    def open(self):
        try:
            self.fPtr = open(self.filePath, 'rb')
            self.fileSize = os.stat(self.filePath).st_size
        except:
            print('[*] Error: Could not open {0}'.format(self.filePath))
            return False
        return True


    def close(self):
        try:
            self.fPtr.close()
        except:
            pass


    def checkFile(self):
        print('[*] Processing {0}'.format(self.filePath))
        # Check if it is a 2.0 archive
        self.fPtr.seek(self.fileSize - self.PYINST20_COOKIE_SIZE, os.SEEK_SET)
        magicFromFile = self.fPtr.read(len(self.MAGIC))

        if magicFromFile == self.MAGIC:
            self.pyinstVer = 20     # pyinstaller 2.0
            print('[*] Pyinstaller version: 2.0')
            return True

        # Check for pyinstaller 2.1+ before bailing out
        self.fPtr.seek(self.fileSize - self.PYINST21_COOKIE_SIZE, os.SEEK_SET)
        magicFromFile = self.fPtr.read(len(self.MAGIC))

        if magicFromFile == self.MAGIC:
            print('[*] Pyinstaller version: 2.1+')
            self.pyinstVer = 21     # pyinstaller 2.1+
            return True

        print('[*] Error : Unsupported pyinstaller version or not a pyinstaller archive')
        return False


    def getCArchiveInfo(self):
        try:
            if self.pyinstVer == 20:
                self.fPtr.seek(self.fileSize - self.PYINST20_COOKIE_SIZE, os.SEEK_SET)

                # Read CArchive cookie
                (magic, lengthofPackage, toc, tocLen, self.pyver) = 
                struct.unpack('!8siiii', self.fPtr.read(self.PYINST20_COOKIE_SIZE))

            elif self.pyinstVer == 21:
                self.fPtr.seek(self.fileSize - self.PYINST21_COOKIE_SIZE, os.SEEK_SET)

                # Read CArchive cookie
                (magic, lengthofPackage, toc, tocLen, self.pyver, pylibname) = 
                struct.unpack('!8siiii64s', self.fPtr.read(self.PYINST21_COOKIE_SIZE))

        except:
            print('[*] Error : The file is not a pyinstaller archive')
            return False

        print('[*] Python version: {0}'.format(self.pyver))

        # Overlay is the data appended at the end of the PE
        self.overlaySize = lengthofPackage
        self.overlayPos = self.fileSize - self.overlaySize
        self.tableOfContentsPos = self.overlayPos + toc
        self.tableOfContentsSize = tocLen

        print('[*] Length of package: {0} bytes'.format(self.overlaySize))
        return True


    def parseTOC(self):
        # Go to the table of contents
        self.fPtr.seek(self.tableOfContentsPos, os.SEEK_SET)

        self.tocList = []
        parsedLen = 0

        # Parse table of contents
        while parsedLen < self.tableOfContentsSize:
            (entrySize, ) = struct.unpack('!i', self.fPtr.read(4))
            nameLen = struct.calcsize('!iiiiBc')

            (entryPos, cmprsdDataSize, uncmprsdDataSize, cmprsFlag, typeCmprsData, name) = 
            struct.unpack( 
                '!iiiBc{0}s'.format(entrySize - nameLen), 
                self.fPtr.read(entrySize - 4))

            name = name.decode('utf-8').rstrip('')
            if len(name) == 0:
                name = str(uniquename())
                print('[!] Warning: Found an unamed file in CArchive. Using random name {0}'.format(name))

            self.tocList.append( 
                                CTOCEntry(                      
                                    self.overlayPos + entryPos, 
                                    cmprsdDataSize,             
                                    uncmprsdDataSize,           
                                    cmprsFlag,                  
                                    typeCmprsData,              
                                    name                        
                                ))

            parsedLen += entrySize
        print('[*] Found {0} files in CArchive'.format(len(self.tocList)))



    def extractFiles(self):
        print('[*] Beginning extraction...please standby')
        extractionDir = os.path.join(os.getcwd(), os.path.basename(self.filePath) + '_extracted')

        if not os.path.exists(extractionDir):
            os.mkdir(extractionDir)

        os.chdir(extractionDir)

        for entry in self.tocList:
            basePath = os.path.dirname(entry.name)
            if basePath != '':
                # Check if path exists, create if not
                if not os.path.exists(basePath):
                    os.makedirs(basePath)

            self.fPtr.seek(entry.position, os.SEEK_SET)
            data = self.fPtr.read(entry.cmprsdDataSize)

            if entry.cmprsFlag == 1:
                data = zlib.decompress(data)
                # Malware may tamper with the uncompressed size
                # Comment out the assertion in such a case
                assert len(data) == entry.uncmprsdDataSize # Sanity Check

            with open(entry.name, 'wb') as f:
                f.write(data)

            if entry.typeCmprsData == b's':
            	print('[+] Possible entry point: {0}'.format(entry.name))

            elif entry.typeCmprsData == b'z' or entry.typeCmprsData == b'Z':
                self._extractPyz(entry.name)


    def _extractPyz(self, name):
        dirName =  name + '_extracted'
        # Create a directory for the contents of the pyz
        if not os.path.exists(dirName):
            os.mkdir(dirName)

        with open(name, 'rb') as f:
            pyzMagic = f.read(4)
            assert pyzMagic == b'PYZ' # Sanity Check

            pycHeader = f.read(4) # Python magic value

            if imp.get_magic() != pycHeader:
                print('[!] Warning: The script is running in a different python version than the one used to build the executable')
                print('    Run this script in Python{0} to prevent extraction errors(if any) during unmarshalling'.format(self.pyver))

            (tocPosition, ) = struct.unpack('!i', f.read(4))
            f.seek(tocPosition, os.SEEK_SET)

            try:
                toc = marshal.load(f)
            except:
                print('[!] Unmarshalling FAILED. Cannot extract {0}. Extracting remaining files.'.format(name))
                return

            print('[*] Found {0} files in PYZ archive'.format(len(toc)))

            # From pyinstaller 3.1+ toc is a list of tuples
            if type(toc) == list:
                toc = dict(toc)

            for key in toc.keys():
                (ispkg, pos, length) = toc[key]
                f.seek(pos, os.SEEK_SET)

                fileName = key
                try:
                    # for Python > 3.3 some keys are bytes object some are str object
                    fileName = key.decode('utf-8')
                except:
                    pass

                # Make sure destination directory exists, ensuring we keep inside dirName
                destName = os.path.join(dirName, fileName.replace("..", "__"))
                destDirName = os.path.dirname(destName)
                if not os.path.exists(destDirName):
                    os.makedirs(destDirName)

                try:
                    data = f.read(length)
                    data = zlib.decompress(data)
                except:
                    print('[!] Error: Failed to decompress {0}, probably encrypted. Extracting as is.'.format(fileName))
                    open(destName + '.pyc.encrypted', 'wb').write(data)
                    continue

                with open(destName + '.pyc', 'wb') as pycFile:
                    pycFile.write(pycHeader)      # Write pyc magic
                    pycFile.write(b'' * 4)      # Write timestamp
                    if self.pyver >= 33:
                        pycFile.write(b'' * 4)  # Size parameter added in Python 3.3
                    pycFile.write(data)


def main():
    if len(sys.argv) < 2:
        print('[*] Usage: pyinstxtractor.py <filename>')

    else:
        arch = PyInstArchive(sys.argv[1])
        if arch.open():
            if arch.checkFile():
                if arch.getCArchiveInfo():
                    arch.parseTOC()
                    arch.extractFiles()
                    arch.close()
                    print('[*] Successfully extracted pyinstaller archive: {0}'.format(sys.argv[1]))
                    print('')
                    print('You can now use a python decompiler on the pyc files within the extracted directory')
                    return

            arch.close()


if __name__ == '__main__':
    main()

Поместите pyinstxtractor.py и exe в один каталог и выполните
python pyinstxtractor.py ZkDuibi1.exe (мое приложение ZkDuibi1.exe)
![ ]
Создайте папку Zkduibi1.exe_extracted.


Вы можете увидеть часть, отмеченную красной линией. Первая папка — это файл библиотеки. Есть системные, а некоторые написаны мной. К счастью, я пишу их как My_xxx_xxx, хотя учусь впервые Декомпилирован, но все равно легко узнать написанные мной файлы. Второй файл записывает информацию заголовка файла pyc. Третий файл — это ваш собственный файл pyc, но у него нет расширения, но вы можете скачать его у себя дома. На этом первый шаг декомпиляции (exe ——- pyc) завершен.
Поскольку pyinstall удаляет информацию заголовка файла pyc при компиляции py в exe, мы должны добавить информацию заголовка при декомпиляции.
Откройте второй и третий файлы (я использую HXD)


Сравните заголовки этих двух файлов и обнаружите, что zkduibi на 16 байт меньше, чем struct (это, как говорят, информация о версии и т. д., не понимаю), добавьте эти 16 слов Раздел.
Следующим шагом является декомпиляция pyc в py. Во-первых, онлайн-инструменты в Интернете не дали результата.
Затем используйте uncompyle6 для успешной декомпиляции! установка uncompyle6,
pip install uncompyle6
Выполнить uncompyle6 xxxx.pyc> xxx.py.

Следующим шагом является декомпиляция файла в PYZ-00.pyz_extracted, открытие файла с помощью HXD, сравнение со структурой и обнаружение как минимум 4 байтов (примите E3 в качестве стандарта), добавьте 4 байта (00 00 00 00) (Если вы не увеличите эти 4 байта, ошибка будет следующей)

Я подумал об этом и смог успешно завершить декомпиляцию. В результате некоторые файлы можно декомпилировать плавно, а некоторые — нет. Ошибка следующая

Из «GBK» на рисунке видно, что он должен быть связан с кодировкой. Поиск « ufffd» означает китайский язык, который не может быть отображен в python. Что это? Я внезапно вспомнил, что был Странный характер явления. Поэтому я написал файл py с несколькими странными символами, открыл его с помощью HXD и обнаружил, что этот странный символ был закодирован как EF BF BD (�), а затем открыл файл с ошибкой декомпиляции в HDX, поискал EF BF BD (�) ) Заменяется отображаемым символом (любым, например, aaa). Сохраните и снова успешно декомпилируйте.
Работа по декомпиляции завершена! ! !

We use pyinstaller to package friend files into exe files, but sometimes we need to restore,We can use pyinstxtractor.py

usage:

python pyinstxtractor.py xxx.exe

Then I get a folder with this structure

--- xxx.exe_extracted
  -out00-pyz.pyz_extracted
   -Various .pyc files
  -out00-pyz.pyz
  -some
  -others
  -xxx (note that these are unsuffixed)

Then terminalpip install uncompyle
install uncompyle,

Then you can use it

uncompyle6 input.pyc>output.py

Convert pyc files to py files, I hope to help everyone

Finally paste the code of pyinstxtractor.py

"" "
pyinstaller extractor v1.9 (supports pyinstaller 3.3, 3.2, 3.1, 3.0, 2.1, 2.0)
author:extreme coders
e-mail:extremecoders (at) hotmail (dot) com
web:https://0xec.blogspot.com
date:29-november-2017
url:https://sourceforge.net/projects/pyinstallerextractor/
for any suggestions, leave a comment on
https://forum.tuts4you.com/topic/34455-pyinstaller-extractor/
this script extracts a pyinstaller generated executable file.
pyinstaller installation is not needed. the script has it all.
for best results, it is recommended to run this script in the
same version of python as was used to create the executable.
this is just to prevent unmarshalling errors (if any) while
extracting the pyz archive.
usage:just copy this script to the directory where your exe resides
    and run the script with the exe file name as a parameter
c: path  to  exe >python pyinstxtractor.py<filename>
$/path/to/exe/python pyinstxtractor.py<filename>
licensed under gnu general public license (gpl) v3.
you are free to modify this source.
changelog
====================================================
version 1.1 (jan 28, 2014)
-------------------------------------------------
-first release
-supports only pyinstaller 2.0
version 1.2 (sept 12, 2015)
-------------------------------------------------
-added support for pyinstaller 2.1 and 3.0 dev
-cleaned up code
-script is now more verbose
-executable extracted within a dedicated sub-directory
(support for pyinstaller 3.0 dev is experimental)
version 1.3 (dec 12, 2015)
-------------------------------------------------
-added support for pyinstaller 3.0 final
version 1.4 (jan 19, 2016)
-------------------------------------------------
version 1.5 (march 1, 2016)
-------------------------------------------------
version 1.6 (sept 5, 2016)
-------------------------------------------------
-added support for pyinstaller 3.2
-extractor will use a random name while extracting unnamed files.
-for encrypted pyz archives it will dump the contents as is. previously, the tool would fail.
version 1.7 (march 13, 2017)
-------------------------------------------------
version 1.8 (april 28, 2017)
-------------------------------------------------
version 1.9 (november 29, 2017)
-------------------------------------------------
-added support for pyinstaller 3.3
"" "
from __future__ import print_function
import os
import struct
import marshal
import zlib
import sys
import imp
import types
from uuid import uuid4 as uniquename
class ctocentry:
  def __init __ (self, position, cmprsddatasize, uncmprsddatasize, cmprsflag, typecmprsdata, name):
    self.position=position
    self.cmprsddatasize=cmprsddatasize
    self.uncmprsddatasize=uncmprsddatasize
    self.cmprsflag=cmprsflag
    self.typecmprsdata=typecmprsdata
    self.name=name
class pyinstarchive:
  pyinst20_cookie_size=24 #for pyinstaller 2.0
  pyinst21_cookie_size=24 + 64 #for pyinstaller 2.1+
  magic=b "mei  014  013  012  013  016" #magic number which identifies pyinstaller
  def __init __ (self, path):
    self.filepath=path
  def open (self):
    try:
      self.fptr=open (self.filepath, "rb")
      self.filesize=os.stat (self.filepath) .st_size
    except:
      print ("[*] error:could not open {0}". format (self.filepath))
      return false
    return true
  def close (self):
    try:
      self.fptr.close ()
    except:
      pass
  def checkfile (self):
    print ("[*] processing {0}". format (self.filepath))
    #check if it is a 2.0 archive
    self.fptr.seek (self.filesize-self.pyinst20_cookie_size, os.seek_set)
    magicfromfile=self.fptr.read (len (self.magic))
    if magicfromfile == self.magic:
      self.pyinstver=20 #pyinstaller 2.0
      print ("[*] pyinstaller version:2.0")
      return true
    #check for pyinstaller 2.1+ before bailing out
    self.fptr.seek (self.filesize-self.pyinst21_cookie_size, os.seek_set)
    magicfromfile=self.fptr.read (len (self.magic))
    if magicfromfile == self.magic:
      print ("[*] pyinstaller version:2.1+")
      self.pyinstver=21 #pyinstaller 2.1+
      return true
    print ("[*] error:unsupported pyinstaller version or not a pyinstaller archive")
    return false
  def getcarchiveinfo (self):
    try:
      if self.pyinstver == 20:
        self.fptr.seek (self.filesize-self.pyinst20_cookie_size, os.seek_set)
        #read carchive cookie
        (magic, lengthofpackage, toc, toclen, self.pyver)=
        struct.unpack ("! 8siiii", self.fptr.read (self.pyinst20_cookie_size))
      elif self.pyinstver == 21:
        self.fptr.seek (self.filesize-self.pyinst21_cookie_size, os.seek_set)
        #read carchive cookie
        (magic, lengthofpackage, toc, toclen, self.pyver, pylibname)=
        struct.unpack ("! 8siiii64s", self.fptr.read (self.pyinst21_cookie_size))
    except:
      print ("[*] error:the file is not a pyinstaller archive")
      return false
    print ("[*] python version:{0}". format (self.pyver))
    #overlay is the data appended at the end of the pe
    self.overlaysize=lengthofpackage
    self.overlaypos=self.filesize-self.overlaysize
    self.tableofcontentspos=self.overlaypos + toc
    self.tableofcontentssize=toclen
    print ("[*] length of package:{0} bytes" .format (self.overlaysize))
    return true
  def parsetoc (self):
    #go to the table of contents
    self.fptr.seek (self.tableofcontentspos, os.seek_set)
    self.toclist=[]
    parsedlen=0
    #parse table of contents
    while parsedlen<self.tableofcontentssize:
      (entrysize,)=struct.unpack ("! i", self.fptr.read (4))
      namelen=struct.calcsize ("! iiiibc")
      (entrypos, cmprsddatasize, uncmprsddatasize, cmprsflag, typecmprsdata, name)=
      struct.unpack (
        "! iiibc {0} s" .format (entrysize-namelen), 
        self.fptr.read (entrysize-4))
      name=name.decode ("utf-8"). rstrip (" 0")
      if len (name) == 0:
        name=str (uniquename ())
        print ("[!] warning:found an unamed file in carchive. using random name {0}". format (name))
      self.toclist.append (
                ctocentry (
                  self.overlaypos + entrypos, 
                  cmprsddatasize, 
                  uncmprsddatasize, 
                  cmprsflag, 
                  typecmprsdata, 
                  name 
                ))
      parsedlen +=entrysize
    print ("[*] found {0} files in carchive" .format (len (self.toclist)))
  def extractfiles (self):
    print ("[*] beginning extraction ... please standby")
    extractiondir=os.path.join (os.getcwd (), os.path.basename (self.filepath) + "_extracted")
    if not os.path.exists (extractiondir):
      os.mkdir (extractiondir)
    os.chdir (extractiondir)
    for entry in self.toclist:
      basepath=os.path.dirname (entry.name)
      if basepath!="":
        #check if path exists, create if not
        if not os.path.exists (basepath):
          os.makedirs (basepath)
      self.fptr.seek (entry.position, os.seek_set)
      data=self.fptr.read (entry.cmprsddatasize)
      if entry.cmprsflag == 1:
        data=zlib.decompress (data)
        #malware may tamper with the uncompressed size
        #comment out the assertion in such a case
        assert len ​​(data) == entry.uncmprsddatasize #sanity check
      with open (entry.name, "wb") as f:
        f.write (data)
      if entry.typecmprsdata == b "s":
        print ("[+] possible entry point:{0}". format (entry.name))
      elif entry.typecmprsdata == b "z" or entry.typecmprsdata == b "z":
        self._extractpyz (entry.name)
  def _extractpyz (self, name):
    dirname=name + "_extracted"
    #create a directory for the contents of the pyz
    if not os.path.exists (dirname):
      os.mkdir (dirname)
    with open (name, "rb") as f:
      pyzmagic=f.read (4)
      assert pyzmagic == b "pyz  0" #sanity check
      pycheader=f.read (4) #python magic value
      if imp.get_magic ()!=pycheader:
        print ("[!] warning:the script is running in a different python version than the one used to build the executable")
        print ("run this script in python {0} to prevent extraction errors (if any) during unmarshalling" .format (self.pyver))
      (tocposition,)=struct.unpack ("! i", f.read (4))
      f.seek (tocposition, os.seek_set)
      try:
        toc=marshal.load (f)
      except:
        print ("[!] unmarshalling failed. cannot extract {0}. extracting remaining files.". format (name))
        return
      print ("[*] found {0} files in pyz archive" .format (len (toc)))
      #from pyinstaller 3.1+ toc is a list of tuples
      if type (toc) == list:
        toc=dict (toc)
      for key in toc.keys ():
        (ispkg, pos, length)=toc [key]
        f.seek (pos, os.seek_set)
        filename=key
        try:
          #for python>3.3 some keys are bytes object some are str object
          filename=key.decode ("utf-8")
        except:
          pass
        #make sure destination directory exists, ensuring we keep inside dirname
        destname=os.path.join (dirname, filename.replace ("..", "__"))
        destdirname=os.path.dirname (destname)
        if not os.path.exists (destdirname):
          os.makedirs (destdirname)
        try:
          data=f.read (length)
          data=zlib.decompress (data)
        except:
          print ("[!] error:failed to decompress {0}, probably encrypted. extracting as is.". format (filename))
          open (destname + ".pyc.encrypted", "wb"). write (data)
          continue
        with open (destname + ".pyc", "wb") as pycfile:
          pycfile.write (pycheader) #write pyc magic
          pycfile.write (b " 0" * 4) #write timestamp
          if self.pyver>= 33:
            pycfile.write (b " 0" * 4) #size parameter added in python 3.3
          pycfile.write (data)
def main ():
  if len (sys.argv)<2:
    print ("[*] usage:pyinstxtractor.py<filename>")
  else:
    arch=pyinstarchive (sys.argv [1])
    if arch.open ():
      if arch.checkfile ():
        if arch.getcarchiveinfo ():
          arch.parsetoc ()
          arch.extractfiles ()
          arch.close ()
          print ("[*] successfully extracted pyinstaller archive:{0}". format (sys.argv [1]))
          print ("")
          print ("you can now use a python decompiler on the pyc files within the extracted directory")
          return
      arch.close ()
if __name__ == "__main__":
  main ()

to sum up

Понравилась статья? Поделить с друзьями:

Читайте также:

  • Error while waiting for device timed out after 300seconds waiting for emulator to come online
  • Error while trying to retrieve text for error ora 01019 oracle
  • Error while starting in multiplayer mode subnautica что делать
  • Error unsupported protocol при печати
  • Error while signing in user grafana

  • 0 0 голоса
    Рейтинг статьи
    Подписаться
    Уведомить о
    guest

    0 комментариев
    Старые
    Новые Популярные
    Межтекстовые Отзывы
    Посмотреть все комментарии