def convert(root_dir, src): print "Decompiling {}".format(src) dest_path = src[:-1] # .pyc --> .py dest_path = os.path.join("py", dest_path) full_dest_path = os.path.join(root_dir, dest_path) full_dest_dir_path = os.path.dirname(full_dest_path) full_src_path = os.path.join(root_dir, src) # Create destination directory if not os.path.exists(full_dest_dir_path): os.makedirs(full_dest_dir_path) # Decompile .pyc file to .py file with open(full_dest_path, "w+b") as dest_file: try: uncompyle6.uncompyle_file(full_src_path, dest_file) except: traceback.print_exc() # Replace uncompyle6 headers to avoid unnecessary changes in git history dest_file.seek(0) lines = dest_file.read().split("\n") assert all(line.startswith("#") for line in lines[:4]), \ "File (%s) doesn't have uncompyle6 headers" % full_dest_path dest_file.seek(0) dest_file.truncate() dest_file.write("\r\n".join(lines[4:])) # Return decompiled .py file path return [dest_path]
def print_code(func, code): f = StringIO() uncompyle6.uncompyle_file(PYC_FILENAME.format(func), outstream=f) log.info("def {}({}):\n{}".format( func, ", ".join(get_varnames(code.co_argcount)) if code.co_argcount else "", f.getvalue()))
def pyc_deco(): try: line_1 = color.RED + "[" + color.CYAN + "XioChi" + color.RED + "]" + color.ENDC line_1 += color.RED + "[" + color.CYAN + "reversenginer/pyc_decompiler" + color.RED + "]>> " + color.ENDC com = raw_input(line_1) com = com.lower() if com[0:9] == 'set input': input = com[10:40] options[0] = input print color.RED + "[" + color.CYAN + "Target" + color.RED + "]>> " + options[ 0] pyc_deco() if com[0:10] == 'set output': output = com[11:40] options[1] = output print color.RED + "[" + color.CYAN + "Target" + color.RED + "]>> " + options[ 1] pyc_deco() elif com[0:12] == 'show options': print "" print "Options\t\t Value\t\t\tRQ\t Description" print "---------\t--------------\t\t----\t--------------" print "INPUT\t\t" + options[0] + "\tyes\tSource Encoded" print "OUTPUT\t\t" + options[1] + "\tyes\tOutput To Decoded" pyc_deco() elif com[0:2] == 'os': log.logger.single("Command Executed", "\n" + color.CYAN) os.system(com[3:]) pyc_deco() elif com[0:4] == 'help': help.help() pyc_deco() elif com[0:4] == 'back': pass elif com[0:5] == 'about': about.about() pyc_deco() elif com[0:3] == 'run': log.logger.attack('Reverse Enginer - Pyc Decompiler') script = options[0] output = options[1] try: from time import sleep with open(output, "wb") as out: sleep(3) log.logger.attack('Decompile Resources...') uncompyle6.uncompyle_file(script, out) sleep(2) log.logger.attack('Proccess Decompile Done...') pyc_deco() except Exception as e: log.logger.error(str(e)) pyc_deco() else: print color.RED + "[" + color.CYAN + "Wrong Command" + color.RED + "]>>" + com pyc_deco() except (KeyboardInterrupt): print ""
def main_source(file, source): global bindata, source_file source_file = file if source == '': source = '_source.py' arch = pyinstxtractor.PyInstArchive(file) if arch.open(): if arch.checkFile(): if arch.getCArchiveInfo(): arch.parseTOC() arch.extractFiles() arch.close() print('[*] Successfully extracted pyinstaller archive: {0}'. format(file)) arch.close() if os.path.isfile(file.replace('.exe', '')) != True: print('[*] Not found {} file!'.format(file.replace('.exe', ''))) file = input( '[?] Select a "Possible entry point" file from the top list -> ' ) + '.exe' try: os.remove(file.replace('exe', 'pyc')) except: pass os.rename(file.replace('.exe', ''), file.replace('exe', 'pyc')) pycfile = file.replace('exe', 'pyc') archive = zipfile.ZipFile('base_library.zip', 'r') bindata = binascii.unhexlify( binascii.hexlify(archive.read('abc.pyc')).split(b'e3')[0]) archive.close() open('newf5a99.pyc', 'w').close() with open('newf5a99.pyc', 'r+b') as new: new.write(bindata) with open(pycfile, 'rb') as old: new.write(old.read()) os.remove(pycfile) os.rename('newf5a99.pyc', pycfile) if source == '_source.py': if os.path.isdir('../' + file.replace('.exe', '') + source) != True: os.mkdir('../' + file.replace('.exe', '') + source) with open( '../' + file.replace('.exe', '') + source + '/' + file.replace('.exe', '') + '_source.py', "w") as fileobj: uncompyle6.uncompyle_file(pycfile, fileobj) else: if os.path.isdir('../' + source) != True: os.mkdir('../' + source) with open('../' + source + '/' + source, "w") as fileobj: uncompyle6.uncompyle_file(pycfile, fileobj) return file
def main(): logging.info("Decompiling files") errors = 0 PYC = [] for filename in (filename for filename in find_files('scripts', "*") if filename.endswith(".pyc")): PYC.append(filename) with open("allpyc.txt", "w") as f: for item in PYC: f.write("%s\n" % item) try: for filename in PYC: basename = os.path.splitext(os.path.basename(filename))[0] dirname = os.path.dirname(filename) try: fileobj = openAndMakeDirs("decompiled\\%s\\%s.py" % (dirname, basename), "w") uncompyle6.uncompyle_file(filename, fileobj) #print("Decompiled file %s" % (filename)) fileobj.close() except (uncompyle6.semantics.pysource.SourceWalkerError, uncompyle6.parser.ParserError): logging.error("Error occurred decompiling file: %s" % filename) errors += 1 except Exception as e: print(e.__class__.__name__) logging.error(str(e)) if errors > 0: logging.warning( "Decompiling some files failed! Check decompile.log for details") else: logging.info("All files decompiled successfully!") logging.info("Moving other files") List = [] for filename in (filename for filename in find_files('scripts', "*") if not filename.endswith(".pyc")): List.append(filename) for item in List: copyFile(item, "decompiled\\%s\\%s" % (os.path.dirname(item), os.path.basename(item)))
def all_source(fi, source): if source == '': source = '_source.py' files = os.listdir('PYZ-00.pyz_extracted/') files = list(set(fi).intersection(files)) if source == '_source.py': if os.path.isdir('../' + file.replace('.exe', '') + source + '/libs') != True: os.mkdir('../' + file.replace('.exe', '') + source + '/libs') for i in files: print('[*] Processing {}'.format(i)) open('../' + file.replace('.exe', '') + source + '/libs/' + i, 'w').close() with open('../' + file.replace('.exe', '') + source + '/libs/' + i, 'r+b') as new: new.write(bindata) with open('PYZ-00.pyz_extracted/' + i, 'rb') as old: new.write( binascii.unhexlify(binascii.hexlify(old.read())[24:])) with open('../' + file.replace('.exe', '') + source + '/libs/' + i.replace('.pyc', '.py'), "w", encoding='utf-8') as fileobj: uncompyle6.uncompyle_file( '../' + file.replace('.exe', '') + source + '/libs/' + i, fileobj) os.remove('../' + file.replace('.exe', '') + source + '/libs/' + i) print('[+] Successfully decompiling {}'.format(i)) else: if os.path.isdir('../' + source + '/libs') != True: os.mkdir('../' + source + '/libs') for i in files: print('[*] Processing {}'.format(i)) open('../' + source + '/libs/' + i, 'w').close() with open('../' + source + '/libs/' + i, 'r+b') as new: new.write(bindata) with open('PYZ-00.pyz_extracted/' + i, 'rb') as old: new.write( binascii.unhexlify(binascii.hexlify(old.read())[24:])) with open('../' + source + '/libs/' + i.replace('.pyc', '.py'), "w", encoding='utf-8') as fileobj: uncompyle6.uncompyle_file('../' + source + '/libs/' + i, fileobj) os.remove('../' + source + '/libs/' + i) print('[+] Successfully decompiling {}'.format(i))
def main(): try: choose = sys.argv[1] except: print Fore.MAGENTA + '\t--------------------------------------------------' print y + '\t[' + r + '~' + y + '] ' + w + 'compile --> ' + g + 'python bytecode.py 1\n\t' + y + '[' + r + '~' + y + '] ' + w + 'decompile --> ' + g + 'python bytecode.py 2' sys.exit() if choose == '1': time.sleep(2) print y + '\t\t\t-->' + r + ' you Selected Compile ' + y + '<--' print Fore.MAGENTA + '\t\t-----------------------------------------' user_input = raw_input(y + '\t\t[' + r + '*' + y + '] ' + g + 'Enter Your Filename >>> ') try: py_compile.compile(user_input) except: print 'Programm Closed' sys.exit() time.sleep(2) print y + '\t\t[' + r + '!' + y + '] ' + w + str( user_input) + g + ' Compiled to --> ' + w + str(user_input) + 'c' elif choose == '2': time.sleep(2) print y + '\t\t\t-->' + r + ' you Selected DeCompile ' + y + '<--' print Fore.MAGENTA + '\t\t-----------------------------------------' pycfile = raw_input(y + '\t\t[' + r + '*' + y + '] ' + g + 'Enter Your Filename [.pyc] >>> ') pyfile = raw_input(y + '\t\t[' + r + '*' + y + '] ' + g + 'Enter .py file to save ' + w + str(pycfile) + ' in them >>> ') try: with open(pyfile, 'wb') as e: uncompyle6.uncompyle_file(pycfile, e) print y + '\t\t[' + r + '+' + y + '] ' + g + 'File Saved To --> ' + w + str( pyfile) except: print y + '[' + r + '-' + y + '] ' + g + 'Unsuccessful' sys.exit()
def main(dbg=None, sys_argv=list(sys.argv)): """Routine which gets run if we were invoked directly""" # Save the original just for use in the restart that works via exec. orig_sys_argv = list(sys_argv) opts, dbg_opts, sys_argv = Moptions.process_options(__title__, __version__, sys_argv) if opts.server: connection_opts={'IO': 'TCP', 'PORT': opts.port} intf = Mserver.ServerInterface(connection_opts=connection_opts) dbg_opts['interface'] = intf if 'FIFO' == intf.server_type: print('Starting FIFO server for process %s.' % os.getpid()) elif 'TCP' == intf.server_type: print('Starting TCP server listening on port %s.' % intf.inout.PORT) pass elif opts.client: Mclient.main(opts, sys_argv) return dbg_opts['orig_sys_argv'] = orig_sys_argv if dbg is None: dbg = Mdebugger.Debugger(dbg_opts) dbg.core.add_ignore(main) pass Moptions._postprocess_options(dbg, opts) # process_options has munged sys.argv to remove any options that # options that belong to this debugger. The original options to # invoke the debugger and script are in global sys_argv if len(sys_argv) == 0: # No program given to debug. Set to go into a command loop # anyway mainpyfile = None else: mainpyfile = sys_argv[0] # Get script filename. if not os.path.isfile(mainpyfile): mainpyfile=Mclifns.whence_file(mainpyfile) is_readable = Mfile.readable(mainpyfile) if is_readable is None: print("%s: Python script file '%s' does not exist" % (__title__, mainpyfile,), file=sys.stderr) sys.exit(1) elif not is_readable: print("%s: Can't read Python script file '%s'" % (__title__, mainpyfile, ), file=sys.stderr) sys.exit(1) return if Mfile.is_compiled_py(mainpyfile): try: from uncompyle6 import uncompyle_file except ImportError: print("%s: Compiled python file '%s', but uncompyle6 not found" % (__title__, mainpyfile), file=sys.stderr) sys.exit(1) short_name = os.path.basename(mainpyfile).strip('.pyc') fd = tempfile.NamedTemporaryFile(suffix='.py', prefix=short_name + "_", delete=False) try: uncompyle_file(mainpyfile, fd) except: print("%s: error uncompyling '%s'" % (__title__, mainpyfile), file=sys.stderr) sys.exit(1) mainpyfile = fd.name fd.close() # If mainpyfile is an optimized Python script try to find and # use non-optimized alternative. mainpyfile_noopt = pyficache.pyc2py(mainpyfile) if mainpyfile != mainpyfile_noopt \ and Mfile.readable(mainpyfile_noopt): print("%s: Compiled Python script given and we can't use that." % __title__, file=sys.stderr) print("%s: Substituting non-compiled name: %s" % ( __title__, mainpyfile_noopt,), file=sys.stderr) mainpyfile = mainpyfile_noopt pass # Replace trepan's dir with script's dir in front of # module search path. sys.path[0] = dbg.main_dirname = os.path.dirname(mainpyfile) # XXX If a signal has been received we continue in the loop, otherwise # the loop exits for some reason. dbg.sig_received = False # if not mainpyfile: # print('For now, you need to specify a Python script name!') # sys.exit(2) # pass while True: # Run the debugged script over and over again until we get it # right. try: if dbg.program_sys_argv and mainpyfile: normal_termination = dbg.run_script(mainpyfile) if not normal_termination: break else: dbg.core.execution_status = 'No program' dbg.core.processor.process_commands() pass dbg.core.execution_status = 'Terminated' dbg.intf[-1].msg("The program finished - quit or restart") dbg.core.processor.process_commands() except Mexcept.DebuggerQuit: break except Mexcept.DebuggerRestart: dbg.core.execution_status = 'Restart requested' if dbg.program_sys_argv: sys.argv = list(dbg.program_sys_argv) part1 = ('Restarting %s with arguments:' % dbg.core.filename(mainpyfile)) args = ' '.join(dbg.program_sys_argv[1:]) dbg.intf[-1].msg(Mmisc.wrapped_lines(part1, args, dbg.settings['width'])) else: break except SystemExit: # In most cases SystemExit does not warrant a post-mortem session. break except: # FIXME: Should be handled above without this mess exception_name = str(sys.exc_info()[0]) if exception_name == str(Mexcept.DebuggerQuit): break elif exception_name == str(Mexcept.DebuggerRestart): dbg.core.execution_status = 'Restart requested' if dbg.program_sys_argv: sys.argv = list(dbg.program_sys_argv) part1 = ('Restarting %s with arguments:' % dbg.core.filename(mainpyfile)) args = ' '.join(dbg.program_sys_argv[1:]) dbg.intf[-1].msg( Mmisc.wrapped_lines(part1, args, dbg.settings['width'])) pass else: raise pass # Restore old sys.argv sys.argv = orig_sys_argv return
import uncompyle6, os os.chdir("You PY/PYC path") with open("uncompiled file name", "wb") as fileobj: uncompyle6.uncompyle_file("PYC file name", fileobj)
def main(dbg=None, sys_argv=list(sys.argv)): """Routine which gets run if we were invoked directly""" # Save the original just for use in the restart that works via exec. orig_sys_argv = list(sys_argv) opts, dbg_opts, sys_argv = Moptions.process_options(__title__, __version__, sys_argv) if opts.server: connection_opts={'IO': 'TCP', 'PORT': opts.port} intf = Mserver.ServerInterface(connection_opts=connection_opts) dbg_opts['interface'] = intf if 'FIFO' == intf.server_type: print('Starting FIFO server for process %s.' % os.getpid()) elif 'TCP' == intf.server_type: print('Starting TCP server listening on port %s.' % intf.inout.PORT) pass elif opts.client: Mclient.main(opts, sys_argv) return dbg_opts['orig_sys_argv'] = orig_sys_argv if dbg is None: dbg = Mdebugger.Debugger(dbg_opts) dbg.core.add_ignore(main) pass Moptions._postprocess_options(dbg, opts) # process_options has munged sys.argv to remove any options that # options that belong to this debugger. The original options to # invoke the debugger and script are in global sys_argv if len(sys_argv) == 0: # No program given to debug. Set to go into a command loop # anyway mainpyfile = None else: mainpyfile = sys_argv[0] # Get script filename. if not osp.isfile(mainpyfile): mainpyfile=Mclifns.whence_file(mainpyfile) is_readable = Mfile.readable(mainpyfile) if is_readable is None: print("%s: Python script file '%s' does not exist" % (__title__, mainpyfile,), file=sys.stderr) sys.exit(1) elif not is_readable: print("%s: Can't read Python script file '%s'" % (__title__, mainpyfile, ), file=sys.stderr) sys.exit(1) return if Mfile.is_compiled_py(mainpyfile): try: from xdis import load_module, PYTHON_VERSION, IS_PYPY (python_version, timestamp, magic_int, co, is_pypy, source_size) = load_module(mainpyfile, code_objects=None, fast_load=True) assert is_pypy == IS_PYPY assert python_version == PYTHON_VERSION, \ "bytecode is for version %s but we are version %s" % ( python_version, PYTHON_VERSION) # We should we check version magic_int py_file = co.co_filename if osp.isabs(py_file): try_file = py_file else: mainpydir = osp.dirname(mainpyfile) dirnames = [mainpydir] + os.environ['PATH'].split(os.pathsep) + ['.'] try_file = Mclifns.whence_file(py_file, dirnames) if osp.isfile(try_file): mainpyfile = try_file pass else: # Move onto the except branch raise IOError("Python file name embedded in code %s not found" % try_file) except: try: from uncompyle6 import uncompyle_file except ImportError: print("%s: Compiled python file '%s', but uncompyle6 not found" % (__title__, mainpyfile), file=sys.stderr) sys.exit(1) return short_name = osp.basename(mainpyfile).strip('.pyc') fd = tempfile.NamedTemporaryFile(suffix='.py', prefix=short_name + "_", delete=False) try: uncompyle_file(mainpyfile, fd) mainpyfile = fd.name fd.close() except: print("%s: error uncompiling '%s'" % (__title__, mainpyfile), file=sys.stderr) fd.close() os.unlink(fd.name) # FIXME: remove the below line and continue with just the # bytecode sys.exit(1) pass # If mainpyfile is an optimized Python script try to find and # use non-optimized alternative. mainpyfile_noopt = pyficache.pyc2py(mainpyfile) if mainpyfile != mainpyfile_noopt \ and Mfile.readable(mainpyfile_noopt): print("%s: Compiled Python script given and we can't use that." % __title__, file=sys.stderr) print("%s: Substituting non-compiled name: %s" % ( __title__, mainpyfile_noopt,), file=sys.stderr) mainpyfile = mainpyfile_noopt pass # Replace trepan's dir with script's dir in front of # module search path. sys.path[0] = dbg.main_dirname = osp.dirname(mainpyfile) # XXX If a signal has been received we continue in the loop, otherwise # the loop exits for some reason. dbg.sig_received = False # if not mainpyfile: # print('For now, you need to specify a Python script name!') # sys.exit(2) # pass while True: # Run the debugged script over and over again until we get it # right. try: if dbg.program_sys_argv and mainpyfile: normal_termination = dbg.run_script(mainpyfile) if not normal_termination: break else: dbg.core.execution_status = 'No program' dbg.core.processor.process_commands() pass dbg.core.execution_status = 'Terminated' dbg.intf[-1].msg("The program finished - quit or restart") dbg.core.processor.process_commands() except Mexcept.DebuggerQuit: break except Mexcept.DebuggerRestart: dbg.core.execution_status = 'Restart requested' if dbg.program_sys_argv: sys.argv = list(dbg.program_sys_argv) part1 = ('Restarting %s with arguments:' % dbg.core.filename(mainpyfile)) args = ' '.join(dbg.program_sys_argv[1:]) dbg.intf[-1].msg(Mmisc.wrapped_lines(part1, args, dbg.settings['width'])) else: break except SystemExit: # In most cases SystemExit does not warrant a post-mortem session. break except: # FIXME: Should be handled above without this mess exception_name = str(sys.exc_info()[0]) if exception_name == str(Mexcept.DebuggerQuit): break elif exception_name == str(Mexcept.DebuggerRestart): dbg.core.execution_status = 'Restart requested' if dbg.program_sys_argv: sys.argv = list(dbg.program_sys_argv) part1 = ('Restarting %s with arguments:' % dbg.core.filename(mainpyfile)) args = ' '.join(dbg.program_sys_argv[1:]) dbg.intf[-1].msg( Mmisc.wrapped_lines(part1, args, dbg.settings['width'])) pass else: raise pass # Restore old sys.argv sys.argv = orig_sys_argv return
#!/usr/bin/python3 import socket import sys import uncompyle6 import os from io import StringIO f = StringIO() if os.path.exists(os.path.expanduser("~/.gadis")): uncompyle6.uncompyle_file( os.path.expanduser("~/.gadis/share/gadis/settings.pyc"), f) else: uncompyle6.uncompyle_file('/usr/local/share/gadis/settings.pyc', f) f.seek(0) exec(f.read(), globals(), locals()) sock = socket.socket(socket.AF_INET, socket.SOCK_STREAM) addr = ('127.0.0.1', Settings.Remote["port"]) sock.connect(addr) cmd = sys.argv[1] args = sys.argv[2:] if cmd == "send": chan = sys.argv[2] msg = " ".join(sys.argv[3:]) msg = "msg {} {}".format(chan, msg) sock.send(msg.encode('utf-8')) elif cmd == "shutdown": sock.send("shutdown".encode('utf-8')) elif cmd == "noadmin": sock.send("noadmin {}".format(args[0]).encode('utf-8'))