Frida python redirect outpout to file

Question:

I’m using frida-python to hook android function and I’m trying to redirect the output to a file.

I’ve tried to redirect stdout to a file :

sys.stdout = open(os.path.join(self.dump_path,'apk_hook.txt'), 'w')

before calling

script = self.session.create_script(open("java_hook.js").read())
script.load()

But this redirect everything and not just the result of frida-python.

I’ve also tried to write the result in a file directly in the javascript file (java_hook.js)
but i don’t know how to pass my variable self.dump_path from my python file to my javascript file.

Java.use('java.net.URL').$init.overload('java.lang.String').implementation = function(str1) {
     var file = new File(How_can_i_pass_this_dynamic_variable,"w");
     file.write("helloworld");
     return this.$init(str1);
};

Do you know how can i do it ??

Thanks.

Asked By: nox

||

Answers:

Use send

Java.use('java.net.URL').$init.overload('java.lang.String').implementation = function(str1) {
     send(dynamic_variable);
     return this.$init(str1);
};

In the python side

f = open('/tmp/log', 'w')    
# ...
def on_message(msg, _data):
    f.write(msg['payload'] + 'n')
# ...
script.on('message', on_message)

Unless you want to write to a file on the phone

    var f = new File("/sdcard/log.txt", "w");
    f.write("linen");
    f.flush();
    f.close();

Answered By: whoopdedoo

I understand that Javascript is executed on the phone, which means you can only write a file on the phone as mentioned by whoopdedoo.
If that is what you need, you should edit accordingly the following snippet:

var f = new File("/sdcard/log.txt", "w");
f.write("linen");
f.flush();
f.close();

To write a file directly on your system (tested on windows/macos), I always use > file.txt at the end of my frida command line:

frida -U -l myscript.js -f com.target.app.org --no-pause > file.txt

You will find file.txt in the folder where you executed the frida cmd.

Answered By: Nioooooo
Categories: questions Tags: ,
Answers are sorted by their score. The answer accepted by the question owner as the best is marked with
at the top-right corner.