Search code examples
androidpythonadb

Using Google's Python-ADB over a local network


Pretty self explanatory, as the title says, is there a way to connect to an ADB over TCP enabled device on a network, using Google's Python-ADB library?

I saw something mentioned in the adb_commands.py file to do with a TCP connection, here is the comment:

If serial specifies a TCP address:port,
then a TCP connection is used instead of a USB connection.

However there is no examples of doing this.

I have the devices IP address and port, as well as the correct ADB keys, and I was wondering if someone could supply an example code snippet.

Thanks heaps :)

P.S. I am using python3.7, and here is the output of uname -a:

Linux Kali 4.18.0-kali2-amd64 #1 SMP Debian 4.18.10-2kali1 (2018-10-09) x86_64 GNU/Linux

Solution

  • Yes, simply pass ip:port to the serial positional argument:

    import os.path as op
    
    from adb import adb_commands
    from adb import sign_m2crypto
    
    # KitKat+ devices require authentication
    signer = sign_m2crypto.M2CryptoSigner(
        op.expanduser('~/.android/adbkey'))
    # Connect to the device
    device = adb_commands.AdbCommands()
    device.ConnectDevice(port_path=None, serial="192.168.0.140:5555",
        rsa_keys=[signer])
    
    # Now we can use Shell, Pull, Push, etc!
    # for i in range(10):
    #     print device.Shell('echo %d' % i)
    
    print device.Shell('uname -a').rstrip()
    print "%s, %s" % (device.Shell('getprop ro.product.brand').rstrip(),
                      device.Shell('getprop ro.product.model').rstrip())
    print device.Shell('getprop ro.build.version.release').rstrip()
    print device.List('/system')
    

    Output on my device:

    Linux localhost 4.4.78-perf-g27c78a6 #1 SMP PREEMPT Thu Sep 6 03:28:28 CST 2018 aarch64
    Xiaomi, MI 6
    8.0.0
    [DeviceFile(filename=bytearray(b'.'), mode=16877,
    ...
    

    Tested with Python 2.7.15; the library isn't fully py3 ready yet. Note that you still have to make your device listen in tcpip mode first by doing adb tcpip 5555 or another port.