Coding With Fun
Home Docker Django Node.js Articles Python pip guide FAQ Policy

How Python calls JS code when doing JS reverse


Jun 01, 2021 Article blog


Table of contents


Once in JS逆向 I do not know how to use Python to achieve, estimated that I am not enough level, then what should I do? This article introduces you to a third-party pyexecjs which solves my problems well and can run JavaScript code with python

Configure the environment

node.js

Download address: https://nodejs.org/en/download/

Choose a good version directly under the good, it will automatically join the system environment, check the Node .js version, the version number appears on the configuration.

 How Python calls JS code when doing JS reverse1

Pyexecjs

pip install pyexecjs

Basic use

Check to see if the engine you are using is node.js

import execjs


print(execjs.get().name)
运行结果:
Node.js (V8)

Run the js code

pyexecjs runs js code in two ways

I. eval()

eval() can execute js code directly

import execjs


print(execjs.eval("a = new Array(1, 2, 3)"))
运行结果:
[1, 2, 3]

2. compile()

This method is recommended if there is a large amount of code, first write js code to a file, read execution when needed.

Create a js_text.js file that writes the following code:

function a(str) {
    return str;
}

python code:

import execjs


with open('js_text.js', 'r', encoding='utf-8') as f:
    jstext = f.read()


ctx = execjs.compile(jstext)
a = '123456'
result = ctx.call('a', a)
print(result)
运行结果:
123456

Call compile to compile js code first, then the call method to execute, the name of the function in js code of the first argument of the call and the second argument is the argument required by the function (if there are more than one argument, write down one argument directly with a comma).

Common problems

The string returned by the js code can go wrong if there are special characters.

The workaround is to encode the string base64 before returning it.

function a(str) {
    return new Buffer(str).toString("base64");
}

With this method you don't have to rewrite the code, just snap js code to run, buckle code sometimes some variables are not declared, in js code to find the complement can help you save brain power.

Source: www.toutiao.com/a6864498293032878604/

Above is W3Cschool编程狮 about doing JS reverse, Python how to call JS code related to the introduction, I hope to help you.