Is it possible to execute Python bytecode with a script?

Say I have a CPython session running,

Is there a way to run data ( bytes) from a file pycdirectly? (without the need for data on disk and without the need to write a temporary pyc file)

Sample script to show a simple usage example:

if foo:
    data = read_data_from_somewhere()
else:
    data = open("bar.pyc", 'rb').read()

assert(type(data) is bytes)

code = bytes_to_code(data)

# call a method from the loaded code
code.call_function()

Accurate use is not important, but generating the code dynamically and copying it over the network for execution is one use case (in order to think about this issue).


Here are a few usage examples that made me curious about how to do this:

  • Checking Python scripts for malicious code.
    If one team can access a large amount of code hidden in binary data, what does this command look like?
  • ( , , ).
  • - , , , , Python.
+4
2

pyc?

, . - exec. :

spam = 'print(3)'
eggs = compile(spam, '<string>', 'exec')
exec(eggs)

:

marshal

import marshal
bytes = marshal.dumps( eggs )

eggs = marshal.loads( bytes )
exec( eggs )

Ned Batchelder, pyc .

.pyc , :

  • ,
  • .

: Python2, Python3, pyc 12 8 . marshal.loads.

+6

, .pyc , . , bar.pyc python , bar.py :

import bar
bar.call_function()
+1

Source: https://habr.com/ru/post/1584908/


All Articles