我们用pyinstaller把朋友文件打包成exe文件,但有时候我们需要还原,我们可以用pyinstxtractor.py

用法:

python pyinstxtractor.py xxx.exe

之后得到一个这样结构的文件夹

--- xxx.exe_extracted

-- out00-PYZ.pyz_extracted

- 各种.pyc文件

-- out00-PYZ.pyz

-- some

-- others

-- xxx(注意这些都是没后缀的)

然后再终端pip install uncompyle安装uncompyle,

然后就可以使用啦

uncompyle6 input.pyc > output.py

把pyc文件转换为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:\path\to\exe\>python pyinstxtractor.py

$ /path/to/exe/python pyinstxtractor.py

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'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 ')

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()

总结

以上所述是小编给大家介绍的python 反编译exe文件为py文件的实例代码,希望对大家有所帮助,如果大家有任何疑问欢迎给我留言,小编会及时回复大家的!

时间: 2019-06-25

python文件输出exe文件反汇编_python 反编译exe文件为py文件的实例代码相关推荐

  1. 安卓反编译揭秘,伪加密APK文件如何被破坏

    2019独角兽企业重金招聘Python工程师标准>>> 1. 源码混淆 如上图,对Android APP的源码进行混淆后混淆器将代码中的所有变量.函数.类的名称加密为简短的英文字母代 ...

  2. 反编译828D PLC的工程文件(*.ptp)

    反编译828D PLC的工程文件(*.ptp) "拉兹-胡夫"变换 PLC存储格式 CPU信息描述 打印设置 LAD/STL可编辑数据 符号表 监控数据表 SDB数据 工具命令 软 ...

  3. android oat如何提取dex文件字节码,Android: 使用oatdump反编译oat文件

    网上经常看到有通过apktool将apk中的dex反编译成smali格式的文件,以便分析功能实现与破-解,确没怎么看到oat文件反通过oatdump反编译的,所以就写了一篇这样的文档.声明一下oat文 ...

  4. 反编译“微软纸牌集合”资源文件

    @[TOC]反编译"微软纸牌集合"资源文件 成功反编译"微软纸牌集合"资源文件 一天时间,终于成功反编译了"微软纸牌集合(Microsoft Soli ...

  5. 02_反汇编_反编译

    实际上安卓的应用都是zip包,只不过把zip扩展名修改了,修改成了APK.所以如果你想拿到它的图片的话,实际上特别简单,你就把它这个.apk换成.zip.换成.zip之后这里的图片资源就都可以拿到了. ...

  6. python下载文件损坏_pythonw.exe停止工作,无法运行IDLE或任何.py文件 - python

    此问题与任何代码都不完全相同.我认为我的安装(python 3.3.5)以某种方式损坏.我尝试了卸载和重新安装以及修复,但是没有任何效果.自从我上次运行任何python代码或进行涉及python的操作 ...

  7. python 文件路径找不到_python路径正确但找不到文件

    python 为什么明明有这个文件路径,但有时候会找不到 整理路径,请用 os.path.normpath() 进行整理,然后你再试试,不要用 join a = os.path.normpath(&q ...

  8. python读取指定页docx内容_Python读取指定目录下指定后缀文件并保存为docx

    最近有个奇葩要求 要项目中的N行代码 申请专利啥的 然后作为程序员当然不能复制粘贴 用代码解决.. 使用python-docx读写docx文件 环境使用python3.6.0 首先pip安装pytho ...

  9. python打包exe os模块_python打包成exe格式的方法求教

    展开全部 在需要打包的目录下,新建一py文件setup.py#coding=utf-8 ''' Created on 2014-11-04 @author: NeoWu ''' from py2exe ...

最新文章

  1. 日期類型的定義6/14
  2. Leetcode PHP题解--D25 500. Keyboard Row
  3. 关于PHP程序员解决问题的能力
  4. SQL SERVER2000教程-第五章 处理数据 第十三节 设定数字日期格式
  5. GNS3中下载路由器
  6. MySQL经典50题
  7. JavaGUI——背景图片设置
  8. iOS——百度地图点击标注事件
  9. 【华为】某中小型企业网 组网案例—总公司+分公司模式
  10. 著者四角号码查询_著者姓名汉语拼音与四角号码数字混合编制书次号之见
  11. 小红书主页爬取_小红书数据爬取教程
  12. JavaSE详细总结——万字纯手码
  13. 激光雷达与毫米波雷达的区别
  14. STL vector :大理石在哪儿?
  15. JAVA反射----->看这篇就够了
  16. 视频剪辑必看,6个免费的音、视频素材网站
  17. Mac Homebrew 下载慢的解决方法
  18. java写100以内的素数_求出100以内的素数(java实现)
  19. 工具 | Cursor:一个不只是写代码的工具
  20. MFC sendMessage消息使用说明

热门文章

  1. win7计算机里不显示摄像头,win7没有摄像头图标怎么办|win7显示摄像头图标的方法...
  2. Laravel Eloquent 小技巧
  3. Excel文档安全性设置
  4. eeepc linux 软件管理,华硕EeePC 901下EEEbuntu 3.0完美优化教程
  5. 使用EasyExcel将本地excel数据读取后导入mysql数据库中
  6. requests案例--度娘翻译
  7. hdoj 1276 士兵队列训练问题 模拟队列
  8. uniapp换皮肤功能demo
  9. GDPR哪些情况下会对企业征收行政罚款?
  10. 【解决方案】摄像机户外直播能在哪些地方运用?团建/项目启动会/户外婚礼等户外直播方案介绍