Skip to content

Instantly share code, notes, and snippets.

@benigumocom
Last active February 16, 2025 20:07
Show Gist options
  • Save benigumocom/a6a87fc1cb690c3c4e3a7642ebf2be6f to your computer and use it in GitHub Desktop.
Save benigumocom/a6a87fc1cb690c3c4e3a7642ebf2be6f to your computer and use it in GitHub Desktop.
Connect Wireless Debug from Terminal on Android11
#!/usr/bin/env python3
"""
Android11
Pair and connect devices for wireless debug on terminal
python-zeroconf: A pure python implementation of multicast DNS service discovery
https://github.com/jstasiak/python-zeroconf
"""
import subprocess
from zeroconf import ServiceBrowser, Zeroconf
TYPE = "_adb-tls-pairing._tcp.local."
NAME = "debug"
PASS = "123456"
FORMAT_QR = "WIFI:T:ADB;S:%s;P:%s;;"
CMD_SHOW = "qrencode -t UTF8 '%s'"
CMD_PAIR = "adb pair %s:%s %s"
CMD_DEVICES = "adb devices -l"
class MyListener:
def remove_service(self, zeroconf, type, name):
print("Service %s removed." % name)
print("Press enter to exit...\n")
def add_service(self, zeroconf, type, name):
info = zeroconf.get_service_info(type, name)
print("Service %s added." % name)
print("service info: %s\n" % info)
self.pair(info)
def pair(self, info):
cmd = CMD_PAIR % (info.server, info.port, PASS)
print(cmd)
subprocess.run(cmd, shell=True)
def main():
text = FORMAT_QR % (NAME, PASS)
subprocess.run(CMD_SHOW % text, shell=True)
print("Scan QR code to pair new devices.")
print("[Developer options]-[Wireless debugging]-[Pair device with QR code]")
zeroconf = Zeroconf()
listener = MyListener()
browser = ServiceBrowser(zeroconf, TYPE, listener)
try:
input("Press enter to exit...\n\n")
finally:
zeroconf.close()
subprocess.run(CMD_DEVICES, shell=True)
if __name__ == '__main__':
main()
@benigumocom
Copy link
Author

【謎?】QRコードによるデバイスのペア設定 – Android11
https://android.benigumo.com/20200920/pair-device-with-qr-code-android11/

@AfzalivE
Copy link

Thank you for writing this script!

@saleehk
Copy link

saleehk commented Mar 19, 2022

@NSTCG
Copy link

NSTCG commented Nov 24, 2022

I created a npm cli package from this reference

https://github.com/saleehk/adb-wifi

https://www.npmjs.com/package/adb-wifi

Thanks @benigumocom ,
also thanks @saleehk for making cli over it

although it currently gives an error : adb.exe: usage: adb pair [:]

@definitelyme
Copy link

In your script, NAME=debug & PASS=123456
what do these values mean? (where can i find them)

@definitelyme
Copy link

definitelyme commented Jun 15, 2023

With the help of ChatGPT, I managed to modify the script to run on MacOS Ventura

#!/usr/bin/env python3

"""
Android11
Pair and connect devices for wireless debug on terminal
pyqrcode: Create QR Codes in Python
https://pypi.org/project/pyqrcode/
zeroconf: A pure python implementation of multicast DNS service discovery
https://github.com/jstasiak/python-zeroconf
"""

import subprocess
import pyqrcode
from zeroconf import ServiceBrowser, Zeroconf
import warnings

NAME = input("Enter a name for wireless debugging: ")
PASS = input("Enter a password for wireless debugging: ")
FORMAT_QR = "WIFI:T:ADB;S:%s;P:%s;;"

CMD_SHOW = "qrencode -t UTF8 '%s'"
CMD_PAIR = "adb pair %s:%s %s"
CMD_DEVICES = "adb devices -l"

class MyListener:

    def remove_service(self, zeroconf, type, name):
        # print("Service %s removed." % name)
        print("Press enter to exit...\n")

    def add_service(self, zeroconf, type, name):
        info = zeroconf.get_service_info(type, name)
        # print("Service %s added." % name)
        # print("service info: %s\n" % info)
        self.pair(info)

    def pair(self, info):
        cmd = CMD_PAIR % (info.server, info.port, PASS)
        print(cmd)
        subprocess.run(cmd, shell=True)


def main():
    text = FORMAT_QR % (NAME, PASS)
    qr_code = pyqrcode.create(text)
    qr_code.png("qr_code.png", scale=6)  # Save the QR code as a PNG image

    subprocess.run(CMD_SHOW % text, shell=True)

    print("=========== Scan QR code to pair new devices =============\n")

    print("[Developer options] =>> [Wireless debugging] =>> [Pair device with QR code]\n\n")

    zeroconf = Zeroconf()
    listener = MyListener()
    browser = ServiceBrowser(zeroconf, "_adb-tls-pairing._tcp.local.", listener)

    try:
        input("Press enter to exit...\n\n")
    finally:
        zeroconf.close()
        subprocess.run(CMD_DEVICES, shell=True)


if __name__ == '__main__':
    warnings.simplefilter('ignore', FutureWarning)
    main()

Terminal Prompt:

Enter the name for wireless debugging: {input-any-name-here}
Enter the password for wireless debugging: {random-numbers-max-5}

NOTE: For this script to work you must have connected to the mobile device in the past.

@Vazgen005
Copy link

I rewrote the script in a more "modern" way.

#!/usr/bin/env python3

"""
Android 11+
Pair and connect devices for wireless debug on terminal

python-zeroconf: A pure python implementation of multicast DNS service discovery
https://github.com/jstasiak/python-zeroconf
"""

import logging
import subprocess
from sys import argv, exit

from zeroconf import ServiceBrowser, Zeroconf

# Constants
TYPE = "_adb-tls-pairing._tcp.local."
NAME = "debug"
PASS = "123456"
FORMAT_QR = "WIFI:T:ADB;S:{name};P:{password};;"
CMD_SHOW = "qrencode -t UTF8 '{data}'"
CMD_PAIR = "adb pair {ip}:{port} {code}"
SUCCESS_MSG = "Successfully paired"


# Configure logging
def setup_logging(debug):
    logging.basicConfig(
        level=logging.DEBUG if debug else logging.INFO,
        format="%(asctime)s - %(levelname)s - %(message)s",
    )


class MyListener:
    def remove_service(self, zeroconf, type, name):
        logging.debug(f"Service {name} removed.")

    def add_service(self, zeroconf, type, name):
        info = zeroconf.get_service_info(type, name)
        logging.debug(f"Service {name} added.")
        logging.debug(f"Service info: {info}")
        self.pair(info)

    def pair(self, info):
        cmd = CMD_PAIR.format(ip=info.server, port=info.port, code=PASS)
        logging.debug(f"Executing command: {cmd}")
        process = subprocess.run(cmd, shell=True, capture_output=True)
        stdout = process.stdout.decode()
        logging.debug(stdout)

        if stdout.startswith(SUCCESS_MSG):
            print(SUCCESS_MSG)
            exit()

    def update_service(self):
        pass


def main():
    setup_logging(len(argv) > 1)

    text = FORMAT_QR.format(name=NAME, password=PASS)
    subprocess.run(CMD_SHOW.format(data=text), shell=True)

    print("Scan QR code to pair new devices.")
    print("[Developer options]-[Wireless debugging]-[Pair device with QR code]")

    zeroconf = Zeroconf()
    listener = MyListener()
    browser = ServiceBrowser(zeroconf, TYPE, listener)

    browser.join()  # Waiting until thread ends

    zeroconf.close()


if __name__ == "__main__":
    try:
        main()
    except KeyboardInterrupt:
        print("\rClosing...")

@Vazgen005
Copy link

I also created a python package: https://pypi.org/project/adb-wifi-py/

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment