Running tcpdump tool in Python ADB

This article and the previous one: Python ADB runs shell scripts similar to
The main technical point of the previous article is to say that text files such as shell s are "hidden" in Python code;
This article mainly talks about how to hide binary executable files such as tcpdump into Python code.

::: the App with online function of the story Android phone. If the App fails to connect to the network,
For problems such as network exceptions, the development generally needs to test students' bag grabs; for example, Android Phones
The development of streaming media protocol (HTTP, HTTP Live, RTSP) testing often requires testers to grab packets.
Android generally uses tcpdump command-line tool to grab packages,
However, some Android is castrated, and many command-line tools are not integrated, such as tcpdump,
Consider the following: adb push tcpdump /system/bin,
Then through / system/bin/tcpdump -vv -s 0 -w /sdcard/tcp.pcap to grab the packet.
It is not difficult to execute tcpdump. It is difficult to "hide" tcpdump into Python code,
Why "hide", because we can only package. py code files into. exe,
Any other format of non code files cannot be compiled and packaged,
Therefore, first convert tcpdump binary file to. py file, so that tcpdump compilation can be packaged into. exe.
:::


Two ways of mutual existence between tcpdump tool and Python
Fusion mode Specific effect
Exposed (low end) Tcpdump tools and Python scripts are independent files, and tcpdump tools are exposed
---catch_tcpdump.py
---tcpdump
Hidden (high end) Hide tcpdump tool in Python code as text
---catch_tcpdump.py
---tcpdump.py

Binary to text

lib64.encode() function, binary files (. Exe,. JPG,. MP4,. docx with or without suffix, etc.) can be converted into text files (English characters that can be read by human beings composed of ASCII code).

# coding=utf-8

import base64

bin_hf = open('tcpdump', 'rb')  # Binary (with b, representing binary mode) reading mode
text_hf = open("tcpdump.txt", "wb")  # Binary (with b for binary mode) write mode

base64.encode(bin_hf, text_hf)  # First, turn the binary file tcpdump into a string variable

bin_hf.close()
text_hf.close()

copy all the text in tcpdump.txt to tcpdump bin string variable,
Put it in a tcpdump.py file (this file is 824kb large, please download the material of this case for self reference)

Similarly, the lib64.decode() function converts text files to binary files.
As we learned in the last lesson, the content of text files can be simply "hidden" in Python code blocks,
That is to say, through lib64 module + tempfile module, it can be converted into binary file without sense,
To sum up, binary files can also be easily "hidden" into Python code blocks.


Python batch script form

tcpdump.py generated above is a custom module, which needs to be import ed,
Remember the essence of batch scripts: execute statements in batch order.

# coding=utf-8

import os
import base64
import tempfile
import tcpdump

# Step 1: convert tcpdump text file to tcpdump binary
signal_1, text_file = tempfile.mkstemp()  # Create first temporary file

with open(text_file, "w") as hf:
    hf.write(tcpdump.tcpdump_bin)
text_hf = open(text_file, "rb")  # Binary (with b, representing binary mode) reading mode

signal_2, bin_file = tempfile.mkstemp()  # Create first temporary file
bin_hf = open(bin_file, 'wb')  # Binary (with b for binary mode) write mode
base64.decode(text_hf, bin_hf)  # First, turn the binary file tcpdump into a string variable

bin_hf.close()  # Closing handle
text_hf.close()  # Closing handle
os.close(signal_1)  # Temporary file cleanup
os.close(signal_2)  # Temporary file cleanup
os.remove(text_file)  # Temporary file cleanup
print(bin_file)

# Step 2: run tcpdump and intercept log
os.system("adb root")
os.system("adb remount")
os.system("adb wait-for-device")
os.system("adb push %s /system/bin/tcpdump" % bin_file)  # Push temporary file to terminal device
os.system("adb shell chmod 777 /system/bin/tcpdump")  # Assignment 777
os.popen("adb shell \"nohup /system/bin/tcpdump -vv -s 0 -w /sdcard/tcp.pcap &\"")  # Independent background execution without interference, popen does not block

# Step 3: clean up
os.remove(bin_file)  # Temporary file cleanup

os.system("pause")

Python procedure oriented function form

Process function oriented programming thinking should be as follows:
How many functions do you need to do this.
It is better to encapsulate all functions as much as possible, only exposing certain parameter interfaces.

# coding=utf-8

import os
import base64
import tempfile
import tcpdump


def text_2_bin():
    '''tcpdump Text file transfer tcpdump Binary system'''

    signal_1, text_file = tempfile.mkstemp()  # Create first temporary file
    with open(text_file, "w") as hf:
        hf.write(tcpdump.tcpdump_bin)
    text_hf = open(text_file, "rb")  # Binary (with b, representing binary mode) reading mode

    signal_2, bin_file = tempfile.mkstemp()  # Create first temporary file
    bin_hf = open(bin_file, 'wb')  # Binary (with b for binary mode) write mode
    base64.decode(text_hf, bin_hf)  # First, turn the binary file tcpdump into a string variable
    # Various destruction
    text_hf.close()
    bin_hf.close()
    os.close(signal_1)
    os.close(signal_2)
    os.remove(text_file)
    return bin_file


def catch_tcpdump(bin_file):
    '''Function tcpdump And intercept log'''
    os.system("adb root")
    os.system("adb remount")
    os.system("adb wait-for-device")
    os.system("adb push %s /system/bin/tcpdump" % bin_file)  # Push temporary file to terminal device
    os.system("adb shell chmod 777 /system/bin/tcpdump")  # Assignment 777
    os.popen("adb shell \"nohup /system/bin/tcpdump -vv -s 0 -w /sdcard/tcp.pcap &\"")  # Independent background execution without interference, popen does not block

bin_file = text_2_bin()
catch_tcpdump(bin_file)
os.remove(bin_file)  # Delete temporary files
os.system("pause")

Python object oriented class form

The programming thinking of object-oriented class should be as follows:
If you are given a blank world, what kinds of things do you need in this world,
What are the common attributes and methods of these kinds of things,
What is the relationship between these kinds of things (objects) and other kinds of things (objects).
Try to encapsulate these classes and only expose the external attributes (variables) and methods (functions).

# coding=utf-8

import os
import base64
import tempfile
import tcpdump


class BinGenerator():
    def __init__(self, text):
        # Only the following two attributes can be exposed
        self.text = text
        self.bin_file = None

    def text_2_bin(self):
        '''tcpdump Text file transfer tcpdump Binary system'''

        signal_1, text_file = tempfile.mkstemp()  # Create first temporary file
        with open(text_file, "w") as hf:
            hf.write(self.text)
        text_hf = open(text_file, "rb")  # Binary (with b, representing binary mode) reading mode

        signal_2, self.bin_file = tempfile.mkstemp()  # Create first temporary file
        bin_hf = open(self.bin_file, 'wb')  # Binary (with b for binary mode) write mode
        base64.decode(text_hf, bin_hf)  # First, convert the binary file tcpdump to string change

        # Various destruction
        text_hf.close()
        bin_hf.close()
        os.close(signal_1)
        os.close(signal_2)
        os.remove(text_file)
        return self.bin_file


def catch_tcpdump(bin_file):
    '''Function tcpdump And intercept log'''
    os.system("adb root")
    os.system("adb remount")
    os.system("adb wait-for-device")
    os.system("adb push %s /system/bin/tcpdump" % bin_file)  # Push temporary file to terminal device
    os.system("adb shell chmod 777 /system/bin/tcpdump")  # Assignment 777
    os.popen("adb shell \"nohup /system/bin/tcpdump -vv -s 0 -w /sdcard/tcp.pcap &\"")  # Independent background execution without interference, popen does not block


b_obj = BinGenerator(tcpdump.tcpdump_bin)
bin_file = b_obj.text_2_bin()
catch_tcpdump(bin_file)
os.remove(bin_file)  # Delete temporary files
os.system("pause")

Download address of this case

Jump to the official website of selfie tutorial to download case materials


Operation mode

Make sure the Android device is connected to the computer through the USB cable, and the adb device is effectively connected,
The three implementation forms of the above code can be run directly, for example, saved as catch ﹣ tcpdump.py and placed on the desktop,
It is recommended to run Python catch ﹣ tcpdump.py, or double-click it.
This time, we also provide the catch [tcpdump.exe that has been compiled and packaged. Double click directly to run it.


The contrast between the exposed and the hidden

After the package is compiled by py2ex, there is only one catch ﹣ tcpdump.exe,
There is an additional tcpdump file that must be attached to the exposed.


For more and better original articles, please visit the official website: www.zipython.com
Selfie course (Python course of automatic test, compiled by Wu Sanren)
Original link: https://www.zipython.com/#/detail?id=c68aae803360428f9ac87b1c99ff65da
You can also follow the wechat subscription number of "wusanren" and accept the article push at any time.

Tags: Python shell Android network

Posted on Sun, 05 Apr 2020 21:37:31 -0700 by Billett