adb Documentation

adb

adb package

Submodules

adb.adb_commands module

A libusb1-based ADB reimplementation.

ADB was giving us trouble with its client/server architecture, which is great for users and developers, but not so great for reliable scripting. This will allow us to more easily catch errors as Python exceptions instead of checking random exit codes, and all the other great benefits from not going through subprocess and a network socket.

All timeouts are in milliseconds.

Contents

class adb.adb_commands.AdbCommands[source]

Bases: object

Exposes adb-like methods for use.

Some methods are more-pythonic and/or have more options.

_images/adb.adb_commands.AdbCommands.__init__.CALLER_GRAPH.svg
build_props

TODO

Type

TODO, None

filesync_handler

TODO

Type

filesync_protocol.FilesyncProtocol

protocol_handler

TODO

Type

adb_protocol.AdbMessage

_device_state

TODO

Type

TODO, None

_handle

TODO

Type

adb.common.TcpHandle, adb.common.UsbHandle, None

_service_connections

[TODO] Connection table tracks each open AdbConnection objects per service type for program functions that choose to persist an AdbConnection object for their functionality, using AdbCommands._get_service_connection()

Type

dict

Close()[source]

TODO

_images/adb.adb_commands.AdbCommands.Close.CALL_GRAPH.svg_images/adb.adb_commands.AdbCommands.Close.CALLER_GRAPH.svg
ConnectDevice(port_path=None, serial=None, default_timeout_ms=None, **kwargs)[source]

Convenience function to setup a transport handle for the adb device from usb path or serial then connect to it.

_images/adb.adb_commands.AdbCommands.ConnectDevice.CALL_GRAPH.svg
Parameters
  • port_path (TODO, None) – The filename of usb port to use.

  • serial (TODO, None) – The serial number of the device to use. If serial specifies a TCP address:port, then a TCP connection is used instead of a USB connection.

  • default_timeout_ms (TODO, None) – The default timeout in milliseconds to use.

  • **kwargs – Keyword arguments

  • handle (common.TcpHandle, common.UsbHandle) – Device handle to use

  • banner (TODO) – Connection banner to pass to the remote device

  • rsa_keys (list[adb_protocol.AuthSigner]) – List of AuthSigner subclass instances to be used for authentication. The device can either accept one of these via the Sign method, or we will send the result of GetPublicKey from the first one if the device doesn’t accept any of them.

  • auth_timeout_ms (int) – Timeout to wait for when sending a new public key. This is only relevant when we send a new public key. The device shows a dialog and this timeout is how long to wait for that dialog. If used in automation, this should be low to catch such a case as a failure quickly; while in interactive settings it should be high to allow users to accept the dialog. We default to automation here, so it’s low by default.

Returns

self – TODO

Return type

AdbCommands

classmethod Devices()[source]

Get a generator of UsbHandle for devices available.

Returns

TODO

Return type

TODO

DisableVerity()[source]

Disable dm-verity checking on userdebug builds.

Returns

TODO

Return type

TODO

EnableVerity()[source]

Re-enable dm-verity checking on userdebug builds.

Returns

TODO

Return type

TODO

GetState()[source]

TODO

_images/adb.adb_commands.AdbCommands.GetState.CALL_GRAPH.svg
Returns

self._device_state – TODO

Return type

TODO

Install(apk_path, destination_dir='', replace_existing=True, grant_permissions=False, timeout_ms=None, transfer_progress_callback=None)[source]

Install an apk to the device.

Doesn’t support verifier file, instead allows destination directory to be overridden.

_images/adb.adb_commands.AdbCommands.Install.CALL_GRAPH.svg_images/adb.adb_commands.AdbCommands.Install.CALLER_GRAPH.svg
Parameters
  • apk_path (TODO) – Local path to apk to install.

  • destination_dir (str) – Optional destination directory. Use /system/app/ for persistent applications.

  • replace_existing (bool) – Whether to replace existing application

  • grant_permissions (bool) – If True, grant all permissions to the app specified in its manifest

  • timeout_ms (int, None) – Expected timeout for pushing and installing.

  • transfer_progress_callback (TODO, None) – callback method that accepts filename, bytes_written, and total_bytes of APK transfer

Returns

ret – The pm install output.

Return type

TODO

InteractiveShell(cmd=None, strip_cmd=True, delim=None, strip_delim=True)[source]

Get stdout from the currently open interactive shell and optionally run a command on the device, returning all output.

_images/adb.adb_commands.AdbCommands.InteractiveShell.CALL_GRAPH.svg
Parameters
  • cmd (TODO, None) – Command to run on the target.

  • strip_cmd (bool) – Strip command name from stdout.

  • delim (TODO, None) – Delimiter to look for in the output to know when to stop expecting more output (usually the shell prompt)

  • strip_delim (bool) – Strip the provided delimiter from the output

Returns

The stdout from the shell command.

Return type

TODO

List(device_path)[source]

Return a directory listing of the given path.

Parameters

device_path (TODO) – Directory to list.

Returns

listing – TODO

Return type

TODO

Logcat(options, timeout_ms=None)[source]

Run shell logcat and stream the output to stdout.

_images/adb.adb_commands.AdbCommands.Logcat.CALL_GRAPH.svg
Parameters
  • options (str) – Arguments to pass to logcat

  • timeout_ms (int, None) – Maximum time to allow the command to run.

Returns

The responses from the logcat command

Return type

generator

Pull(device_filename, dest_file=None, timeout_ms=None, progress_callback=None)[source]

Pull a file from the device.

Parameters
  • device_filename (TODO) – Filename on the device to pull.

  • dest_file (str, file, io.IOBase, None) – If set, a filename or writable file-like object.

  • timeout_ms (int, None) – Expected timeout for any part of the pull.

  • progress_callback (TODO, None) – Callback method that accepts filename, bytes_written and total_bytes, total_bytes will be -1 for file-like objects

Returns

The file data if dest_file is not set. Otherwise, True if the destination file exists

Return type

TODO

Raises

ValueError – If dest_file is of unknown type.

Push(source_file, device_filename, mtime='0', timeout_ms=None, progress_callback=None, st_mode=None)[source]

Push a file or directory to the device.

_images/adb.adb_commands.AdbCommands.Push.CALL_GRAPH.svg_images/adb.adb_commands.AdbCommands.Push.CALLER_GRAPH.svg
Parameters
  • source_file (TODO) – Either a filename, a directory or file-like object to push to the device.

  • device_filename (TODO) – Destination on the device to write to.

  • mtime (str) – Modification time to set on the file.

  • timeout_ms (int, None) – Expected timeout for any part of the push.

  • progress_callback (TODO, None) – Callback method that accepts filename, bytes_written and total_bytes, total_bytes will be -1 for file-like objects

  • st_mode (TODO, None) – Stat mode for filename

Reboot(destination=b'')[source]

Reboot the device.

_images/adb.adb_commands.AdbCommands.Reboot.CALLER_GRAPH.svg
Parameters

destination (bytes) – Specify 'bootloader' for fastboot.

RebootBootloader()[source]

Reboot device into fastboot.

_images/adb.adb_commands.AdbCommands.RebootBootloader.CALL_GRAPH.svg
Remount()[source]

Remount / as read-write.

Returns

TODO

Return type

TODO

Root()[source]

Restart adbd as root on the device.

Returns

TODO

Return type

TODO

Shell(command, timeout_ms=None)[source]

Run command on the device, returning the output.

_images/adb.adb_commands.AdbCommands.Shell.CALLER_GRAPH.svg
Parameters
  • command (TODO) – Shell command to run

  • timeout_ms (int, None) – Maximum time to allow the command to run.

Returns

TODO

Return type

TODO

Stat(device_filename)[source]

Get a file’s stat() information.

_images/adb.adb_commands.AdbCommands.Stat.CALLER_GRAPH.svg
Parameters

device_filename (TODO) – TODO

Returns

  • mode (TODO) – TODO

  • size (TODO) – TODO

  • mtime (TODO) – TODO

StreamingShell(command, timeout_ms=None)[source]

Run command on the device, yielding each line of output.

_images/adb.adb_commands.AdbCommands.StreamingShell.CALLER_GRAPH.svg
Parameters
  • command (bytes) – Command to run on the target.

  • timeout_ms (int, None) – Maximum time to allow the command to run.

Returns

The responses from the shell command.

Return type

generator

Uninstall(package_name, keep_data=False, timeout_ms=None)[source]

Removes a package from the device.

_images/adb.adb_commands.AdbCommands.Uninstall.CALL_GRAPH.svg
Parameters
  • package_name (TODO) – Package name of target package.

  • keep_data (bool) – Whether to keep the data and cache directories

  • timeout_ms (int, None) – Expected timeout for pushing and installing.

Returns

The pm uninstall output.

Return type

TODO

_AdbCommands__reset()

TODO

_images/adb.adb_commands.AdbCommands.__reset.CALL_GRAPH.svg_images/adb.adb_commands.AdbCommands.__reset.CALLER_GRAPH.svg
_Connect(banner=None, **kwargs)[source]

Connect to the device.

_images/adb.adb_commands.AdbCommands._Connect.CALLER_GRAPH.svg
Parameters
Returns

True

Return type

bool

_get_service_connection(service, service_command=None, create=True, timeout_ms=None)[source]

Based on the service, get the AdbConnection for that service or create one if it doesnt exist

_images/adb.adb_commands.AdbCommands._get_service_connection.CALLER_GRAPH.svg
Parameters
  • service (TODO) – TODO

  • service_command (TODO, None) – Additional service parameters to append

  • create (bool) – If False, don’t create a connection if it does not exist

  • timeout_ms (int, None) – TODO

Returns

connection – TODO

Return type

TODO

filesync_handler

alias of adb.filesync_protocol.FilesyncProtocol

protocol_handler

alias of adb.adb_protocol.AdbMessage

adb.adb_commands.CLASS = 255

From adb.h

adb.adb_commands.DeviceIsAvailable(device)

From adb.h

adb.adb_commands.PROTOCOL = 1

From adb.h

adb.adb_commands.SUBCLASS = 66

From adb.h

adb.adb_debug module

Daemon-less ADB client in python.

Contents

adb.adb_debug.Devices(args)[source]

Lists the available devices.

Mimics adb devices output:

List of devices attached
015DB7591102001A        device        1,2
_images/adb.adb_debug.Devices.CALLER_GRAPH.svg
Parameters

args (argparse.ArgumentParser) – CLI arguments; see adb.common_cli.GetDeviceArguments().

Returns

0

Return type

int

adb.adb_debug.List(device, device_path)[source]

Prints a directory listing.

Parameters
Yields

str – A formatted listing for a file in device_path

adb.adb_debug.Shell(device, *command)[source]

Runs a command on the device and prints the stdout.

Parameters
adb.adb_debug.main()[source]

TODO

adb.adb_keygen module

This file implements encoding and decoding logic for Android’s custom RSA public key binary format. Public keys are stored as a sequence of little-endian 32 bit words. Note that Android only supports little-endian processors, so we don’t do any byte order conversions when parsing the binary struct.

Structure from: https://github.com/aosp-mirror/platform_system_core/blob/c55fab4a59cfa461857c6a61d8a0f1ae4591900c/libcrypto_utils/android_pubkey.c

typedef struct RSAPublicKey {
    // Modulus length. This must be ANDROID_PUBKEY_MODULUS_SIZE_WORDS
    uint32_t modulus_size_words;

    // Precomputed montgomery parameter: -1 / n[0] mod 2^32
    uint32_t n0inv;

    // RSA modulus as a little-endian array
    uint8_t modulus[ANDROID_PUBKEY_MODULUS_SIZE];

    // Montgomery parameter R^2 as a little-endian array of little-endian words
    uint8_t rr[ANDROID_PUBKEY_MODULUS_SIZE];

    // RSA modulus: 3 or 65537
    uint32_t exponent;
} RSAPublicKey;

Contents

adb.adb_keygen.ANDROID_PUBKEY_MODULUS_SIZE = 256

Size of an RSA modulus such as an encrypted block or a signature.

adb.adb_keygen.ANDROID_PUBKEY_MODULUS_SIZE_WORDS = 64

Size of the RSA modulus in words.

adb.adb_keygen.ANDROID_RSAPUBLICKEY_STRUCT = '<LL256s256sL'

Python representation of “struct RSAPublicKey”

adb.adb_keygen._to_bytes(n, length, endianess='big')[source]

Partial python2 compatibility with int.to_bytes

https://stackoverflow.com/a/20793663

Parameters
  • n (TODO) – TODO

  • length (TODO) – TODO

  • endianess (str, TODO) – TODO

Returns

TODO

Return type

TODO

adb.adb_keygen.decode_pubkey(public_key)[source]

Decode a public RSA key stored in Android’s custom binary format.

Parameters

public_key (TODO) – TODO

adb.adb_keygen.decode_pubkey_file(public_key_path)[source]

TODO

Parameters

public_key_path (str) – TODO

adb.adb_keygen.encode_pubkey(private_key_path)[source]

Encodes a public RSA key into Android’s custom binary format.

Parameters

private_key_path (str) – TODO

Returns

TODO

Return type

TODO

adb.adb_keygen.get_user_info()[source]

TODO

Returns

' <username>@<hostname>

Return type

str

adb.adb_keygen.keygen(filepath)[source]

Generate an ADB public/private key pair.

  • The private key is stored in filepath.

  • The public key is stored in filepath + '.pub'

(Existing files will be overwritten.)

Parameters

filepath (str) – File path to write the private/public keypair

adb.adb_keygen.write_public_keyfile(private_key_path, public_key_path)[source]

Write a public keyfile to public_key_path in Android’s custom RSA public key format given a path to a private keyfile.

Parameters
  • private_key_path (TODO) – TODO

  • public_key_path (TODO) – TODO

adb.adb_protocol module

ADB protocol implementation.

Implements the ADB protocol as seen in android’s adb/adbd binaries, but only the host side.

Contents

adb.adb_protocol.AUTH_RSAPUBLICKEY = 3

AUTH constants for arg0.

adb.adb_protocol.AUTH_SIGNATURE = 2

AUTH constants for arg0.

adb.adb_protocol.AUTH_TOKEN = 1

AUTH constants for arg0.

class adb.adb_protocol.AdbMessage(command=None, arg0=None, arg1=None, data=b'')[source]

Bases: object

ADB Protocol and message class.

local_id/remote_id

Turns out the documentation is host/device ambidextrous, so local_id is the id for ‘the sender’ and remote_id is for ‘the recipient’. So since we’re only on the host, we’ll re-document with host_id and device_id:

OPEN(host_id, 0, 'shell:XXX')
READY/OKAY(device_id, host_id, '')
WRITE(0, host_id, 'data')
CLOSE(device_id, host_id, '')
_images/adb.adb_protocol.AdbMessage.__init__.CALLER_GRAPH.svg
Parameters
  • command (bytes, None) – One of: [b'SYNC', b'CNXN', b'AUTH', b'OPEN', b'OKAY', b'CLSE', b'WRTE']

  • arg0 (TODO, None) – TODO

  • arg1 (TODO, None) – TODO

  • data (bytes) – TODO

command

The value in AdbMessage.commands that corresponds to the command parameter

Type

int

commands

A dictionary with keys [b'SYNC', b'CNXN', b'AUTH', b'OPEN', b'OKAY', b'CLSE', b'WRTE'].

Type

dict

connections

TODO

Type

int

constants

A dictionary with values [b'SYNC', b'CNXN', b'AUTH', b'OPEN', b'OKAY', b'CLSE', b'WRTE'].

Type

dict

format

The format for unpacking the ADB message.

Type

bytes

ids

[b'SYNC', b'CNXN', b'AUTH', b'OPEN', b'OKAY', b'CLSE', b'WRTE']

Type

list[bytes]

static CalculateChecksum(data)[source]

TODO

_images/adb.adb_protocol.AdbMessage.CalculateChecksum.CALLER_GRAPH.svg
Returns

TODO

Return type

TODO

classmethod Command(usb, service, command='', timeout_ms=None)[source]

One complete set of USB packets for a single command.

Sends service:command in a new connection, reading the data for the response. All the data is held in memory, large responses will be slow and can fill up memory.

_images/adb.adb_protocol.AdbMessage.Command.CALL_GRAPH.svg
Parameters
Returns

The response from the service.

Return type

str

Raises
classmethod Connect(usb, banner=b'notadb', rsa_keys=None, auth_timeout_ms=100)[source]

Establish a new connection to the device.

_images/adb.adb_protocol.AdbMessage.Connect.CALL_GRAPH.svg
Parameters
  • usb (adb.common.TcpHandle, adb.common.UsbHandle) – A adb.common.TcpHandle or adb.common.UsbHandle instance with BulkRead and BulkWrite methods.

  • banner (str) – A string to send as a host identifier.

  • rsa_keys (list[adb_protocol.AuthSigner]) – List of AuthSigner subclass instances to be used for authentication. The device can either accept one of these via the Sign method, or we will send the result of GetPublicKey from the first one if the device doesn’t accept any of them.

  • auth_timeout_ms (int) – Timeout to wait for when sending a new public key. This is only relevant when we send a new public key. The device shows a dialog and this timeout is how long to wait for that dialog. If used in automation, this should be low to catch such a case as a failure quickly; while in interactive settings it should be high to allow users to accept the dialog. We default to automation here, so it’s low by default.

Returns

banner – The device’s reported banner. Always starts with the state (device, recovery, or sideload), sometimes includes information after a : with various product information.

Return type

TODO

Raises
classmethod InteractiveShellCommand(conn, cmd=None, strip_cmd=True, delim=None, strip_delim=True, clean_stdout=True)[source]

Retrieves stdout of the current InteractiveShell and sends a shell command if provided TODO: Should we turn this into a yield based function so we can stream all output?

_images/adb.adb_protocol.AdbMessage.InteractiveShellCommand.CALL_GRAPH.svg
Parameters
  • conn (AdbConnection) – Instance of AdbConnection

  • cmd (str, None) – Command to run on the target.

  • strip_cmd (bool) – Strip command name from stdout.

  • delim (TODO) – Delimiter to look for in the output to know when to stop expecting more output (usually the shell prompt)

  • strip_delim (bool) – Strip the provided delimiter from the output

  • clean_stdout (bool) – Cleanup the stdout stream of any backspaces and the characters that were deleted by the backspace

Returns

stdout – The stdout from the shell command.

Return type

TODO

classmethod Open(usb, destination, timeout_ms=None)[source]

Opens a new connection to the device via an OPEN message.

Not the same as the posix open or any other google3 Open methods.

_images/adb.adb_protocol.AdbMessage.Open.CALL_GRAPH.svg_images/adb.adb_protocol.AdbMessage.Open.CALLER_GRAPH.svg
Parameters
Returns

The local connection id.

Return type

_AdbConnection, None

Raises
Pack()[source]

Returns this message in an over-the-wire format.

_images/adb.adb_protocol.AdbMessage.Pack.CALL_GRAPH.svg_images/adb.adb_protocol.AdbMessage.Pack.CALLER_GRAPH.svg
Returns

TODO

Return type

bytes

classmethod Read(usb, expected_cmds, timeout_ms=None, total_timeout_ms=None)[source]

Receive a response from the device.

_images/adb.adb_protocol.AdbMessage.Read.CALL_GRAPH.svg_images/adb.adb_protocol.AdbMessage.Read.CALLER_GRAPH.svg
Parameters
  • usb (adb.common.TcpHandle, adb.common.UsbHandle) – TODO

  • expected_cmds (TODO) – Read until we receive a header ID that is in expected_cmds

  • timeout_ms (int, None) – Timeout in milliseconds for USB packets.

  • total_timeout_ms (int, None) – The total time to wait for a command in expected_cmds

Returns

  • command (TODO) – TODO

  • arg0 (TODO) – TODO

  • arg1 (TODO) – TODO

  • bytes – TODO

Raises
Send(usb, timeout_ms=None)[source]

Send this message over USB.

_images/adb.adb_protocol.AdbMessage.Send.CALL_GRAPH.svg
Parameters
classmethod StreamingCommand(usb, service, command='', timeout_ms=None)[source]

One complete set of USB packets for a single command.

Sends service:command in a new connection, reading the data for the response. All the data is held in memory, large responses will be slow and can fill up memory.

_images/adb.adb_protocol.AdbMessage.StreamingCommand.CALL_GRAPH.svg_images/adb.adb_protocol.AdbMessage.StreamingCommand.CALLER_GRAPH.svg
Parameters
Yields

str – The responses from the service.

Raises
classmethod Unpack(message)[source]

TODO

_images/adb.adb_protocol.AdbMessage.Unpack.CALLER_GRAPH.svg
Parameters

message (TODO) – TODO

Returns

  • cmd (TODO) – TODO

  • arg0 (TODO) – TODO

  • arg1 (TODO) – TODO

  • data_length (TODO) – TODO

  • data_checksum (TODO) – TODO

  • unused_magic (TODO) – TODO

Raises

ValueError – Unable to unpack the ADB command.

property checksum

TODO

_images/adb.adb_protocol.AdbMessage.checksum.CALL_GRAPH.svg_images/adb.adb_protocol.AdbMessage.checksum.CALLER_GRAPH.svg
Returns

TODO

Return type

TODO

commands = {b'AUTH': 1213486401, b'CLSE': 1163086915, b'CNXN': 1314410051, b'OKAY': 1497451343, b'OPEN': 1313165391, b'SYNC': 1129208147, b'WRTE': 1163154007}
connections = 0
constants = {1129208147: b'SYNC', 1163086915: b'CLSE', 1163154007: b'WRTE', 1213486401: b'AUTH', 1313165391: b'OPEN', 1314410051: b'CNXN', 1497451343: b'OKAY'}
format = b'<6I'
ids = [b'SYNC', b'CNXN', b'AUTH', b'OPEN', b'OKAY', b'CLSE', b'WRTE']
class adb.adb_protocol.AuthSigner[source]

Bases: object

Signer for use with authenticated ADB, introduced in 4.4.x/KitKat.

GetPublicKey()[source]

Returns the public key in PEM format without headers or newlines.

Raises

NotImplementedError – This method is implemented in subclasses.

Sign(data)[source]

Signs given data using a private key.

Parameters

data (bytes) – The data to be signed

Raises

NotImplementedError – This method is implemented in subclasses.

exception adb.adb_protocol.InterleavedDataError[source]

Bases: Exception

We only support command sent serially.

_images/adb.adb_protocol.InterleavedDataError.CALL_GRAPH.svg
exception adb.adb_protocol.InvalidChecksumError[source]

Bases: Exception

Checksum of data didn’t match expected checksum.

_images/adb.adb_protocol.InvalidChecksumError.CALL_GRAPH.svg
exception adb.adb_protocol.InvalidCommandError(message, response_header, response_data)[source]

Bases: Exception

Got an invalid command over USB.

_images/adb.adb_protocol.InvalidCommandError.CALL_GRAPH.svg_images/adb.adb_protocol.InvalidCommandError.__init__.CALLER_GRAPH.svg
exception adb.adb_protocol.InvalidResponseError[source]

Bases: Exception

Got an invalid response to our command.

_images/adb.adb_protocol.InvalidResponseError.CALL_GRAPH.svg
adb.adb_protocol.MAX_ADB_DATA = 4096

Maximum amount of data in an ADB packet.

adb.adb_protocol.MakeWireIDs(ids)[source]

TODO

Parameters

ids (list[bytes]) – TODO

Returns

  • id_to_wire (dict) – TODO

  • wire_to_id (dict) – TODO

adb.adb_protocol.VERSION = 16777216

ADB protocol version.

class adb.adb_protocol._AdbConnection(usb, local_id, remote_id, timeout_ms)[source]

Bases: object

ADB Connection.

_images/adb.adb_protocol._AdbConnection.__init__.CALLER_GRAPH.svg
Parameters
  • usb (adb.common.UsbHandle) – TODO

  • local_id (TODO) – TODO

  • remote_id (TODO) – TODO

  • timeout_ms (int) – Timeout in milliseconds for USB packets.

local_id

The ID for the sender

Type

TODO

remote_id

The ID for the recipient

Type

TODO

timeout_ms

Timeout in milliseconds for USB packets.

Type

int

usb

TODO

Type

adb.common.UsbHandle

Close()[source]

TODO

_images/adb.adb_protocol._AdbConnection.Close.CALL_GRAPH.svg_images/adb.adb_protocol._AdbConnection.Close.CALLER_GRAPH.svg
Raises
Okay()[source]

TODO

_images/adb.adb_protocol._AdbConnection.Okay.CALL_GRAPH.svg_images/adb.adb_protocol._AdbConnection.Okay.CALLER_GRAPH.svg
ReadUntil(*expected_cmds)[source]

Read a packet, Ack any write packets.

_images/adb.adb_protocol._AdbConnection.ReadUntil.CALL_GRAPH.svg_images/adb.adb_protocol._AdbConnection.ReadUntil.CALLER_GRAPH.svg
Parameters

*expected_cmds (TODO) – TODO

Returns

  • cmd (TODO) – TODO

  • data (TODO) – TODO

Raises
ReadUntilClose()[source]

Yield packets until a b'CLSE' packet is received.

_images/adb.adb_protocol._AdbConnection.ReadUntilClose.CALL_GRAPH.svg
Yields

data (TODO) – TODO

Write(data)[source]

Write a packet and expect an Ack.

_images/adb.adb_protocol._AdbConnection.Write.CALL_GRAPH.svg
Parameters

data (TODO) – TODO

Returns

len(data)

Return type

int

Raises
_Send(command, arg0, arg1, data=b'')[source]

TODO

_images/adb.adb_protocol._AdbConnection._Send.CALLER_GRAPH.svg
Parameters
  • command (TODO) – TODO

  • arg0 (TODO) – TODO

  • arg1 (TODO) – TODO

  • data (bytes) – TODO

adb.adb_protocol.find_backspace_runs(stdout_bytes, start_pos)[source]

TODO

_images/adb.adb_protocol.find_backspace_runs.CALLER_GRAPH.svg
Parameters
  • stdout_bytes (TODO) – TODO

  • start_pos (TODO) – TODO

Returns

  • int – The index/position of the first backspace.

  • num_backspaces (int) – TODO

adb.common module

Common code for ADB and Fastboot.

Common usb browsing and usb communication.

Contents

adb.common.DEFAULT_TIMEOUT_MS = 10000

Default timeout

adb.common.GetInterface(setting)[source]

Get the class, subclass, and protocol for the given USB setting.

_images/adb.common.GetInterface.CALLER_GRAPH.svg
Parameters

setting (TODO) – TODO

Returns

  • TODO – TODO

  • TODO – TODO

  • TODO – TODO

adb.common.InterfaceMatcher(clazz, subclass, protocol)[source]

Returns a matcher that returns the setting with the given interface.

_images/adb.common.InterfaceMatcher.CALL_GRAPH.svg
Parameters
  • clazz (TODO) – TODO

  • subclass (TODO) – TODO

  • protocol (TODO) – TODO

Returns

Matcher – TODO

Return type

function

class adb.common.TcpHandle(serial, timeout_ms=None)[source]

Bases: object

TCP connection object.

Provides same interface as UsbHandle.

_images/adb.common.TcpHandle.__init__.CALLER_GRAPH.svg
Parameters
  • serial (str, bytes, bytearray) – Android device serial of the form “host” or “host:port”. (Host may be an IP address or a host name.)

  • timeout_ms (TODO, None) – TODO

_connection

TODO

Type

TODO, None

_serial_number

<host>:<port>

Type

str

_timeout_ms

TODO

Type

float, None

host

TODO

Type

str, TODO

port

TODO

Type

str, int, TODO

BulkRead(numbytes, timeout=None)[source]

TODO

_images/adb.common.TcpHandle.BulkRead.CALL_GRAPH.svg
Parameters
  • numbytes (int) – TODO

  • timeout_ms (TODO, None) – TODO

Returns

TODO

Return type

TODO

Raises

adb.usb_exceptions.TcpTimeoutException – Reading timed out.

BulkWrite(data, timeout=None)[source]

TODO

_images/adb.common.TcpHandle.BulkWrite.CALL_GRAPH.svg
Parameters
  • data (TODO) – TODO

  • timeout (TODO, None) – TODO

Returns

TODO

Return type

TODO

Raises

adb.usb_exceptions.TcpTimeoutException – Sending data timed out. No data was sent.

Close()[source]

TODO

Returns

TODO

Return type

TODO

Timeout(timeout_ms)[source]

TODO

_images/adb.common.TcpHandle.Timeout.CALLER_GRAPH.svg
Parameters

timeout_ms (TODO) – TODO

Returns

TODO

Return type

float

TimeoutSeconds(timeout_ms)[source]

TODO

_images/adb.common.TcpHandle.TimeoutSeconds.CALL_GRAPH.svg_images/adb.common.TcpHandle.TimeoutSeconds.CALLER_GRAPH.svg
Parameters

timeout_ms (TODO) – TODO

Returns

TODO

Return type

float

_connect()[source]

TODO

_images/adb.common.TcpHandle._connect.CALL_GRAPH.svg
property serial_number

TODO

_images/adb.common.TcpHandle.serial_number.CALLER_GRAPH.svg
Returns

self._serial_number – The _serial_number attribute (<host>:<port>)

Return type

str

class adb.common.UsbHandle(device, setting, usb_info=None, timeout_ms=None)[source]

Bases: object

USB communication object. Not thread-safe.

Handles reading and writing over USB with the proper endpoints, exceptions, and interface claiming.

Important methods: * UsbHandle.FlushBuffers * UsbHandle.BulkRead * UsbHandle.BulkWrite(bytes data)

_images/adb.common.UsbHandle.__init__.CALLER_GRAPH.svg
Parameters
  • device (TODO) – libusb_device to connect to.

  • setting (TODO) – libusb setting with the correct endpoints to communicate with.

  • usb_info (TODO, None) – String describing the usb path/serial/device, for debugging.

  • timeout_ms (TODO, None) – Timeout in milliseconds for all I/O.

_device

libusb_device to connect to.

Type

TODO

_handle

TODO

Type

TODO

_interface_number

TODO

Type

TODO

_max_read_packet_len

TODO

Type

TODO

_read_endpoint

TODO

Type

TODO

_setting

libusb setting with the correct endpoints to communicate with.

Type

TODO

_timeout_ms

Timeout in milliseconds for all I/O.

Type

TODO, None

_usb_info

String describing the usb path/serial/device, for debugging.

Type

TODO

_write_endpoint

TODO

Type

TODO, None

BulkRead(length, timeout_ms=None)[source]

TODO

_images/adb.common.UsbHandle.BulkRead.CALL_GRAPH.svg_images/adb.common.UsbHandle.BulkRead.CALLER_GRAPH.svg
Parameters
  • length (int) – TODO

  • timeout_ms (TODO, None) – TODO

Returns

TODO

Return type

bytearray

Raises

usb_exceptions.ReadFailedError – Could not receive data

BulkReadAsync(length, timeout_ms=None)[source]

TODO

Parameters
  • length (int) – TODO

  • timeout_ms (TODO, None) – TODO

Raises

NotImplementedError – This is always raised because this method is not implemented.

BulkWrite(data, timeout_ms=None)[source]

TODO

_images/adb.common.UsbHandle.BulkWrite.CALL_GRAPH.svg
Parameters
  • data (bytes) – TODO

  • timeout_ms (TODO, None) – TODO

Returns

TODO

Return type

TODO

Raises
Close()[source]

TODO

_images/adb.common.UsbHandle.Close.CALL_GRAPH.svg_images/adb.common.UsbHandle.Close.CALLER_GRAPH.svg
classmethod Find(setting_matcher, port_path=None, serial=None, timeout_ms=None)[source]

Gets the first device that matches according to the keyword args.

_images/adb.common.UsbHandle.Find.CALL_GRAPH.svg_images/adb.common.UsbHandle.Find.CALLER_GRAPH.svg
Parameters
  • setting_matcher (TODO) – TODO

  • port_path (TODO, None) – TODO

  • serial (TODO, None) – TODO

  • timeout_ms (TODO, None) – TODO

Returns

TODO

Return type

TODO

classmethod FindAndOpen(setting_matcher, port_path=None, serial=None, timeout_ms=None)[source]

TODO

_images/adb.common.UsbHandle.FindAndOpen.CALL_GRAPH.svg_images/adb.common.UsbHandle.FindAndOpen.CALLER_GRAPH.svg
Parameters
  • setting_matcher (TODO) – TODO

  • port_path (TODO, None) – TODO

  • serial (TODO, None) – TODO

  • timeout_ms (TODO, None) – TODO

Returns

dev – TODO

Return type

TODO

classmethod FindDevices(setting_matcher, device_matcher=None, usb_info='', timeout_ms=None)[source]

Find and yield the devices that match.

_images/adb.common.UsbHandle.FindDevices.CALLER_GRAPH.svg
Parameters
  • setting_matcher (TODO) – Function that returns the setting to use given a usb1.USBDevice, or None if the device doesn’t have a valid setting.

  • device_matcher (TODO, None) – Function that returns True if the given UsbHandle is valid. None to match any device.

  • usb_info (str) – Info string describing device(s).

  • timeout_ms (TODO, None) – Default timeout of commands in milliseconds.

Yields

TODO – UsbHandle instances

classmethod FindFirst(setting_matcher, device_matcher=None, **kwargs)[source]

Find and return the first matching device.

_images/adb.common.UsbHandle.FindFirst.CALL_GRAPH.svg_images/adb.common.UsbHandle.FindFirst.CALLER_GRAPH.svg
Parameters
Returns

An instance of UsbHandle.

Return type

TODO

Raises

adb.usb_exceptions.DeviceNotFoundError – Raised if the device is not available.

FlushBuffers()[source]

TODO

_images/adb.common.UsbHandle.FlushBuffers.CALL_GRAPH.svg
Raises

adb.usb_exceptions.ReadFailedError – TODO

Open()[source]

Opens the USB device for this setting, and claims the interface.

_images/adb.common.UsbHandle.Open.CALL_GRAPH.svg
classmethod PortPathMatcher(port_path)[source]

Returns a device matcher for the given port path.

_images/adb.common.UsbHandle.SerialMatcher.CALL_GRAPH.svg_images/adb.common.UsbHandle.PortPathMatcher.CALLER_GRAPH.svg
Parameters

port_path (TODO) – TODO

Returns

TODO

Return type

function

classmethod SerialMatcher(serial)[source]

Returns a device matcher for the given serial.

_images/adb.common.UsbHandle.SerialMatcher.CALLER_GRAPH.svg
Parameters

serial (TODO) – TODO

Returns

TODO

Return type

function

Timeout(timeout_ms)[source]

TODO

_images/adb.common.UsbHandle.Timeout.CALLER_GRAPH.svg
Returns

TODO

Return type

TODO

_HANDLE_CACHE = <WeakValueDictionary>
_HANDLE_CACHE_LOCK = <unlocked _thread.lock object>
property port_path

TODO

_images/adb.common.UsbHandle.port_path.CALLER_GRAPH.svg
Returns

TODO

Return type

TODO

property serial_number

TODO

_images/adb.common.UsbHandle.serial_number.CALLER_GRAPH.svg
Returns

TODO

Return type

TODO

property usb_info

TODO

_images/adb.common.UsbHandle.usb_info.CALL_GRAPH.svg_images/adb.common.UsbHandle.usb_info.CALLER_GRAPH.svg
Returns

TODO

Return type

TODO

adb.common_cli module

Common code for ADB and Fastboot CLI.

Usage introspects the given class for methods, args, and docs to show the user.

StartCli() handles connecting to a device, calling the expected method, and outputting the results.

Contents

adb.common_cli.GetCommonArguments()[source]

Return a parser for common CLI commands.

Returns

group – A parser for common CLI commands.

Return type

argparse.ArgumentParser

adb.common_cli.GetDeviceArguments()[source]

Return a parser for device-related CLI commands.

Returns

group – A parser for device-related CLI commands.

Return type

argparse.ArgumentParser

adb.common_cli.MakeSubparser(subparsers, parents, method, arguments=None)[source]

Returns an argparse subparser to create a ‘subcommand’ to adb.

_images/adb.common_cli.MakeSubparser.CALL_GRAPH.svg
Parameters
  • subparsers (TODO) – TODO

  • parents (TODO) – TODO

  • method (TODO) – TODO

  • arguments (TODO, None) – TODO

Returns

subparser – TODO

Return type

TODO

class adb.common_cli.PositionalArg(option_strings, dest, nargs=None, const=None, default=None, type=None, choices=None, required=False, help=None, metavar=None)[source]

Bases: argparse.Action

A positional CLI argument.

_images/adb.common_cli.PositionalArg.CALL_GRAPH.svg
adb.common_cli.StartCli(args, adb_commands, extra=None, **device_kwargs)[source]

Starts a common CLI interface for this usb path and protocol.

Handles connecting to a device, calling the expected method, and outputting the results.

_images/adb.common_cli.StartCli.CALL_GRAPH.svg
Parameters
  • args (TODO) – TODO

  • adb_commands (TODO) – TODO

  • extra (TODO, None) – TODO

  • **device_kwargs (TODO) – TODO

Returns

TODO

Return type

TODO

adb.common_cli._DocToArgs(doc)[source]

Converts a docstring documenting arguments into a dict.

_images/adb.common_cli._DocToArgs.CALLER_GRAPH.svg
Parameters

doc (str) – The docstring for a method; see MakeSubparser.

Returns

out – A dictionary of arguments and their descriptions from the docstring doc.

Return type

dict

class adb.common_cli._PortPathAction(option_strings, dest, nargs=None, const=None, default=None, type=None, choices=None, required=False, help=None, metavar=None)[source]

Bases: argparse.Action

TODO

_images/adb.common_cli._PortPathAction.CALL_GRAPH.svg
adb.common_cli._RunMethod(dev, args, extra)[source]

Runs a method registered via MakeSubparser().

_images/adb.common_cli._RunMethod.CALLER_GRAPH.svg
Parameters
  • dev (TODO) – TODO

  • args (TODO) – TODO

  • extra (TODO) – TODO

Returns

0

Return type

int

adb.debug module

TEMPORARY.

adb.debug.debug_print(name, var)[source]

Print debugging info.

adb.fastboot module

A libusb1-based fastboot implementation.

Contents

adb.fastboot.CLASS = 255

From fastboot.c

adb.fastboot.DEFAULT_MESSAGE_CALLBACK(m)

TODO

adb.fastboot.DeviceIsAvailable(device)

TODO

class adb.fastboot.FastbootCommands[source]

Bases: object

Encapsulates the fastboot commands.

_images/adb.fastboot.FastbootCommands.__init__.CALLER_GRAPH.svg
_handle

TODO

Type

TODO, None

_protocol

TODO

Type

TODO, None

Close()[source]

TODO

ConnectDevice(port_path=None, serial=None, default_timeout_ms=None, chunk_kb=1024, **kwargs)[source]

Convenience function to get an adb device from usb path or serial.

Parameters
  • port_path (TODO, None) – The filename of usb port to use.

  • serial (TODO, None) – The serial number of the device to use. If serial specifies a TCP address:port, then a TCP connection is used instead of a USB connection.

  • default_timeout_ms (TODO, None) – The default timeout in milliseconds to use.

  • chunk_kb (int) – Amount of data, in kilobytes, to break fastboot packets up into

  • **kwargs (dict) – Keyword arguments

  • handle (adb.common.TcpHandle, adb.common.UsbHandle) – Device handle to use

  • banner (TODO) – Connection banner to pass to the remote device

  • rsa_keys (list[adb_protocol.AuthSigner]) – List of AuthSigner subclass instances to be used for authentication. The device can either accept one of these via the Sign method, or we will send the result of GetPublicKey from the first one if the device doesn’t accept any of them.

  • auth_timeout_ms (TODO) – Timeout to wait for when sending a new public key. This is only relevant when we send a new public key. The device shows a dialog and this timeout is how long to wait for that dialog. If used in automation, this should be low to catch such a case as a failure quickly; while in interactive settings it should be high to allow users to accept the dialog. We default to automation here, so it’s low by default.

Returns

self – TODO

Return type

FastbootCommands

Continue()[source]

Continues execution past fastboot into the system.

_images/adb.fastboot.FastbootCommands.Continue.CALL_GRAPH.svg
Returns

TODO

Return type

TODO

classmethod Devices()[source]

Get a generator of UsbHandle for devices available.

Returns

TODO

Return type

TODO

Download(source_file, source_len=0, info_cb=<function <lambda>>, progress_callback=None)[source]

Downloads a file to the device.

_images/adb.fastboot.FastbootCommands.Download.CALLER_GRAPH.svg
Parameters
  • source_file (TODO) – A filename or file-like object to download to the device.

  • source_len (int) – Optional length of source_file. If source_file is a file-like object and source_len is not provided, source_file is read into memory.

  • info_cb (TODO) – Optional callback accepting FastbootMessage for text sent from the bootloader.

  • progress_callback (TODO, None) – Optional callback called with the percent of the source_file downloaded. Note, this doesn’t include progress of the actual flashing.

Returns

Response to a download request, normally nothing.

Return type

TODO

Erase(partition, timeout_ms=None)[source]

Erases the given partition.

_images/adb.fastboot.FastbootCommands.Erase.CALL_GRAPH.svg
Parameters
  • partition (TODO) – Partition to clear.

  • timeout_ms (TODO, None) – TODO

Flash(partition, timeout_ms=0, info_cb=<function <lambda>>)[source]

Flashes the last downloaded file to the given partition.

_images/adb.fastboot.FastbootCommands.Flash.CALL_GRAPH.svg_images/adb.fastboot.FastbootCommands.Flash.CALLER_GRAPH.svg
Parameters
  • partition (TODO) – Partition to overwrite with the new image.

  • timeout_ms (int) – Optional timeout in milliseconds to wait for it to finish.

  • info_cb (TODO) – See FastbootCommands.Download(). Usually no messages.

Returns

Response to a download request, normally nothing.

Return type

TODO

FlashFromFile(partition, source_file, source_len=0, info_cb=<function <lambda>>, progress_callback=None)[source]

Flashes a partition from the file on disk.

_images/adb.fastboot.FastbootCommands.FlashFromFile.CALL_GRAPH.svg_images/adb.fastboot.FastbootCommands.FlashFromFile.CALLER_GRAPH.svg
Parameters
  • partition (TODO) – Partition name to flash to.

  • source_file (TODO) – Filename to download to the device.

  • source_len (int) – Optional length of source_file, uses os.stat if not provided.

  • info_cb (TODO) – See Download.

  • progress_callback (TODO) – See Download.

Returns

Download and flash responses, normally nothing.

Return type

TODO

Getvar(var, info_cb=<function <lambda>>)[source]

Returns the given variable’s definition.

_images/adb.fastboot.FastbootCommands.Getvar.CALL_GRAPH.svg
Parameters
  • var (TODO) – A variable the bootloader tracks. Use ‘all’ to get them all.

  • info_cb (TODO) – See FastbootCommands.Download(). Usually no messages.

Returns

Value of var according to the current bootloader.

Return type

TODO

Oem(command, timeout_ms=None, info_cb=<function <lambda>>)[source]

Executes an OEM command on the device.

_images/adb.fastboot.FastbootCommands.Oem.CALL_GRAPH.svg
Parameters
  • command (TODO) – Command to execute, such as ‘poweroff’ or ‘bootconfig read’.

  • timeout_ms (TODO, None) – Optional timeout in milliseconds to wait for a response.

  • info_cb (TODO) – See FastbootCommands.Download(). Messages vary based on command.

Returns

Return type

The final response from the device.

Reboot(target_mode=b'', timeout_ms=None)[source]

Reboots the device.

_images/adb.fastboot.FastbootCommands.Reboot.CALL_GRAPH.svg
Parameters
  • target_mode (bytes) – Normal reboot when unspecified. Can specify other target modes such as ‘recovery’ or ‘bootloader’.

  • timeout_ms (TODO, None) – Optional timeout in milliseconds to wait for a response.

Returns

Usually the empty string. Depends on the bootloader and the target_mode.

Return type

TODO

RebootBootloader(timeout_ms=None)[source]

Reboots into the bootloader, usually equiv to Reboot(‘bootloader’).

_images/adb.fastboot.FastbootCommands.RebootBootloader.CALL_GRAPH.svg
Parameters

timeout_ms (TODO, None) – TODO

Returns

TODO

Return type

TODO

_FastbootCommands__reset()

TODO

_images/adb.fastboot.FastbootCommands.__reset.CALL_GRAPH.svg
_SimpleCommand(command, arg=None, **kwargs)[source]

TODO

_images/adb.fastboot.FastbootCommands._SimpleCommand.CALL_GRAPH.svg_images/adb.fastboot.FastbootCommands._SimpleCommand.CALLER_GRAPH.svg
Parameters
  • command (TODO) – TODO

  • arg (TODO, None) – TODO

  • **kwargs (dict) – Keyword arguments

  • TODO – TODO

Returns

TODO

Return type

TODO

property usb_handle

TODO

Returns

self._handle – TODO

Return type

TODO

exception adb.fastboot.FastbootInvalidResponse(message, *args)[source]

Bases: adb.usb_exceptions.FormatMessageWithArgumentsException

Fastboot responded with a header we didn’t expect.

_images/adb.fastboot.FastbootInvalidResponse.CALL_GRAPH.svg
class adb.fastboot.FastbootMessage(message, header)

Bases: tuple

FastbootMessage

_fields_defaults = {}
class adb.fastboot.FastbootProtocol(usb, chunk_kb=1024)[source]

Bases: object

Encapsulates the fastboot protocol.

_images/adb.fastboot.FastbootProtocol.__init__.CALLER_GRAPH.svg
Parameters
chunk_kb

Packet size. For older devices, 4 may be required.

Type

int

usb

adb.common.UsbHandle instance.

Type

adb.common.UsbHandle

FINAL_HEADERS = {b'DATA', b'OKAY'}
HandleDataSending(source_file, source_len, info_cb=<function <lambda>>, progress_callback=None, timeout_ms=None)[source]

Handles the protocol for sending data to the device.

_images/adb.fastboot.FastbootProtocol.HandleDataSending.CALL_GRAPH.svg_images/adb.fastboot.FastbootProtocol.HandleDataSending.CALLER_GRAPH.svg
Parameters
  • source_file (TODO) – File-object to read from for the device.

  • source_len (TODO) – Amount of data, in bytes, to send to the device.

  • info_cb (TODO) – Optional callback for text sent from the bootloader.

  • progress_callback (TODO, None) – Callback that takes the current and the total progress of the current file.

  • timeout_ms (TODO, None) – Timeout in milliseconds to wait for each response.

Returns

OKAY packet’s message.

Return type

TODO

Raises
HandleSimpleResponses(timeout_ms=None, info_cb=<function <lambda>>)[source]

Accepts normal responses from the device.

_images/adb.fastboot.FastbootProtocol.HandleSimpleResponses.CALL_GRAPH.svg_images/adb.fastboot.FastbootProtocol.HandleSimpleResponses.CALLER_GRAPH.svg
Parameters
  • timeout_ms (TODO, None) – Timeout in milliseconds to wait for each response.

  • info_cb (TODO) – Optional callback for text sent from the bootloader.

Returns

OKAY packet’s message.

Return type

TODO

SendCommand(command, arg=None)[source]

Sends a command to the device.

_images/adb.fastboot.FastbootProtocol.SendCommand.CALL_GRAPH.svg
Parameters
  • command (str) – The command to send.

  • arg (str) – Optional argument to the command.

_AcceptResponses(expected_header, info_cb, timeout_ms=None)[source]

Accepts responses until the expected header or a FAIL.

_images/adb.fastboot.FastbootProtocol._AcceptResponses.CALLER_GRAPH.svg
Parameters
  • expected_header (TODO) – OKAY or DATA

  • info_cb (TODO) – Optional callback for text sent from the bootloader.

  • timeout_ms (TODO) – Timeout in milliseconds to wait for each response.

Returns

OKAY packet’s message.

Return type

TODO

Raises
static _HandleProgress(total, progress_callback)[source]

Calls the callback with the current progress and total.

_images/adb.fastboot.FastbootProtocol._HandleProgress.CALLER_GRAPH.svg
Parameters
  • total (TODO) – TODO

  • progress_callback (TODO) – TODO

_Write(data, length, progress_callback=None)[source]

Sends the data to the device, tracking progress with the callback.

_images/adb.fastboot.FastbootProtocol._Write.CALL_GRAPH.svg_images/adb.fastboot.FastbootProtocol._Write.CALLER_GRAPH.svg
Parameters
  • data (TODO) – TODO

  • length (TODO) – TODO

  • progress_callback (TODO, None) – TODO

property usb_handle

TODO

Returns

self.usbadb.common.UsbHandle instance.

Return type

adb.common.UsbHandle

exception adb.fastboot.FastbootRemoteFailure(message, *args)[source]

Bases: adb.usb_exceptions.FormatMessageWithArgumentsException

Remote error.

_images/adb.fastboot.FastbootRemoteFailure.CALL_GRAPH.svg
exception adb.fastboot.FastbootStateMismatch(message, *args)[source]

Bases: adb.usb_exceptions.FormatMessageWithArgumentsException

Fastboot and uboot’s state machines are arguing. You Lose.

_images/adb.fastboot.FastbootStateMismatch.CALL_GRAPH.svg
exception adb.fastboot.FastbootTransferError(message, *args)[source]

Bases: adb.usb_exceptions.FormatMessageWithArgumentsException

Transfer error.

_images/adb.fastboot.FastbootTransferError.CALL_GRAPH.svg
adb.fastboot.PROTOCOL = 3

From fastboot.c

adb.fastboot.SUBCLASS = 66

From fastboot.c

adb.fastboot.VENDORS = {1105, 1282, 1478, 2389, 2996, 4046, 6353, 8888, 8980, 16700, 32903}

From fastboot.c

adb.fastboot_debug module

Fastboot in python.

Call it similar to how you call android’s fastboot, but this only accepts usb paths and no serials.

Contents

adb.fastboot_debug.Devices()[source]

Lists the available devices.

List of devices attached
015DB7591102001A        device
_images/adb.fastboot_debug.Devices.CALLER_GRAPH.svg
Returns

0

Return type

int

adb.fastboot_debug._InfoCb(message)[source]

Print a message to stdout.

Parameters

message (adb.fastboot.FastbootMessage) – A FastbootMessage with header and message attributes

adb.fastboot_debug.main()[source]

TODO

adb.filesync_protocol module

ADB protocol implementation.

Implements the ADB protocol as seen in android’s adb/adbd binaries, but only the host side.

Contents

adb.filesync_protocol.DEFAULT_PUSH_MODE = 33272

Default mode for pushed files.

class adb.filesync_protocol.DeviceFile(filename, mode, size, mtime)

Bases: tuple

_fields_defaults = {}
property filename

Alias for field number 0

property mode

Alias for field number 1

property mtime

Alias for field number 3

property size

Alias for field number 2

class adb.filesync_protocol.FileSyncConnection(adb_connection, recv_header_format)[source]

Bases: object

Encapsulate a FileSync service connection.

Parameters
adb

ADB connection

Type

adb.adb_protocol._AdbConnection

send_buffer

bytearray(adb_protocol.MAX_ADB_DATA) (see adb.adb_protocol.MAX_ADB_DATA)

Type

byte_array

send_idx

TODO

Type

int

send_header_len

struct.calcsize(b'<2I')

Type

int

recv_buffer

TODO

Type

bytearray

recv_header_format

TODO

Type

bytes

recv_header_len

struct.calcsize(recv_header_format)

Type

int

Read(expected_ids, read_data=True)[source]

Read ADB messages and return FileSync packets.

_images/adb.filesync_protocol.FileSyncConnection.Read.CALL_GRAPH.svg_images/adb.filesync_protocol.FileSyncConnection.Read.CALLER_GRAPH.svg
Parameters
  • expected_ids (tuple[bytes]) – If the received header ID is not in expected_ids, an exception will be raised

  • read_data (bool) – Whether to read the received data

Returns

  • command_id (bytes) – The received header ID

  • tuple – TODO

  • data (bytearray) – The received data

Raises
ReadUntil(expected_ids, *finish_ids)[source]

Useful wrapper around FileSyncConnection.Read().

_images/adb.filesync_protocol.FileSyncConnection.ReadUntil.CALL_GRAPH.svg
Parameters
  • expected_ids (tuple[bytes]) – If the received header ID is not in expected_ids, an exception will be raised

  • finish_ids (tuple[bytes]) – We will read until we find a header ID that is in finish_ids

Yields
  • cmd_id (bytes) – The received header ID

  • header (tuple) – TODO

  • data (bytearray) – The received data

Send(command_id, data=b'', size=0)[source]

Send/buffer FileSync packets.

Packets are buffered and only flushed when this connection is read from. All messages have a response from the device, so this will always get flushed.

_images/adb.filesync_protocol.FileSyncConnection.Send.CALL_GRAPH.svg
Parameters
  • command_id (bytes) – Command to send.

  • data (str, bytes) – Optional data to send, must set data or size.

  • size (int) – Optionally override size from len(data).

_CanAddToSendBuffer(data_len)[source]

Determine whether data_len bytes of data can be added to the send buffer without exceeding adb.adb_protocol.MAX_ADB_DATA.

_images/adb.filesync_protocol.FileSyncConnection._CanAddToSendBuffer.CALLER_GRAPH.svg
Parameters

data_len (int) – The length of the data to be potentially added to the send buffer (not including the length of its header)

Returns

Whether data_len bytes of data can be added to the send buffer without exceeding adb.adb_protocol.MAX_ADB_DATA

Return type

bool

_Flush()[source]

TODO

_images/adb.filesync_protocol.FileSyncConnection._Flush.CALLER_GRAPH.svg
Raises

adb.usb_exceptions.WriteFailedError – Could not send data

_ReadBuffered(size)[source]

Read size bytes of data from self.recv_buffer.

_images/adb.filesync_protocol.FileSyncConnection._ReadBuffered.CALLER_GRAPH.svg
Parameters

size (int) – The amount of data to read

Returns

result – The read data

Return type

bytearray

id_to_wire = {b'DATA': 1096040772, b'DENT': 1414415684, b'DONE': 1162760004, b'FAIL': 1279869254, b'LIST': 1414744396, b'OKAY': 1497451343, b'QUIT': 1414092113, b'RECV': 1447249234, b'SEND': 1145980243, b'STAT': 1413567571}
ids = [b'STAT', b'LIST', b'SEND', b'RECV', b'DENT', b'DONE', b'DATA', b'OKAY', b'FAIL', b'QUIT']
wire_to_id = {1096040772: b'DATA', 1145980243: b'SEND', 1162760004: b'DONE', 1279869254: b'FAIL', 1413567571: b'STAT', 1414092113: b'QUIT', 1414415684: b'DENT', 1414744396: b'LIST', 1447249234: b'RECV', 1497451343: b'OKAY'}
class adb.filesync_protocol.FilesyncProtocol[source]

Bases: object

Implements the FileSync protocol as described in sync.txt.

classmethod List(connection, path)[source]

Get a list of the files in path.

Parameters
Returns

files – Information about the files in path

Return type

list[DeviceFile]

classmethod Pull(connection, filename, dest_file, progress_callback)[source]

Pull a file from the device into the file-like dest_file.

_images/adb.filesync_protocol.FilesyncProtocol.Pull.CALL_GRAPH.svg
Parameters
  • connection (adb.adb_protocol._AdbConnection) – ADB connection

  • filename (str) – The file to be pulled

  • dest_file (_io.BytesIO) – File-like object for writing to

  • progress_callback (function, None) – Callback method that accepts filename, bytes_written, and total_bytes

Raises

PullFailedError – Unable to pull file

classmethod Push(connection, datafile, filename, st_mode=33272, mtime=0, progress_callback=None)[source]

Push a file-like object to the device.

_images/adb.filesync_protocol.FilesyncProtocol.Push.CALL_GRAPH.svg_images/adb.filesync_protocol.FilesyncProtocol.Push.CALLER_GRAPH.svg
Parameters
  • connection (adb.adb_protocol._AdbConnection) – ADB connection

  • datafile (_io.BytesIO) – File-like object for reading from

  • filename (str) – Filename to push to

  • st_mode (int) – Stat mode for filename

  • mtime (int) – Modification time

  • progress_callback (function, None) – Callback method that accepts filename, bytes_written, and total_bytes

Raises

PushFailedError – Raised on push failure.

static Stat(connection, filename)[source]

Get file status (mode, size, and mtime).

_images/adb.filesync_protocol.FilesyncProtocol.Stat.CALLER_GRAPH.svg
Parameters
Returns

  • mode (int) – The mode of the file

  • size (int) – The size of the file

  • mtime (int) – The time of last modification for the file

Raises

adb.adb_protocol.InvalidResponseError – Expected STAT response to STAT, got something else

classmethod _HandleProgress(progress_callback)[source]

Calls the callback with the current progress and total bytes written/received.

_images/adb.filesync_protocol.FilesyncProtocol._HandleProgress.CALL_GRAPH.svg_images/adb.filesync_protocol.FilesyncProtocol._HandleProgress.CALLER_GRAPH.svg
Parameters

progress_callback (function) – Callback method that accepts filename, bytes_written, and total_bytes; total_bytes will be -1 for file-like objects.

exception adb.filesync_protocol.InterleavedDataError[source]

Bases: Exception

We only support command sent serially.

_images/adb.filesync_protocol.InterleavedDataError.CALL_GRAPH.svg
exception adb.filesync_protocol.InvalidChecksumError[source]

Bases: Exception

Checksum of data didn’t match expected checksum.

_images/adb.filesync_protocol.InvalidChecksumError.CALL_GRAPH.svg
adb.filesync_protocol.MAX_PUSH_DATA = 2048

Maximum size of a filesync DATA packet.

exception adb.filesync_protocol.PullFailedError[source]

Bases: Exception

Pulling a file failed for some reason.

_images/adb.filesync_protocol.PullFailedError.CALL_GRAPH.svg
exception adb.filesync_protocol.PushFailedError[source]

Bases: Exception

Pushing a file failed for some reason.

_images/adb.filesync_protocol.PushFailedError.CALL_GRAPH.svg
adb.sign_cryptography module

ADB authentication using the cryptography package.

Contents

class adb.sign_cryptography.CryptographySigner(rsa_key_path)[source]

Bases: adb.adb_protocol.AuthSigner

AuthSigner using cryptography.io.

Warning

This is currently broken!

_images/adb.sign_cryptography.CryptographySigner.CALL_GRAPH.svg
Parameters

rsa_key_path (str) – The path to the private key.

public_key

The contents of the public key file

Type

str

rsa_key

The loaded private key

Type

cryptography.hazmat.backends.openssl.rsa._RSAPrivateKey

GetPublicKey()[source]

Returns the public key in PEM format without headers or newlines.

Returns

self.public_key – The contents of the public key file

Return type

str

Sign(data)[source]

Signs given data using a private key.

Parameters

data (TODO) – TODO

Returns

The signed data

Return type

TODO

adb.sign_pycryptodome module

ADB authentication using pycryptodome.

Contents

class adb.sign_pycryptodome.PycryptodomeAuthSigner(rsa_key_path=None)[source]

Bases: adb.adb_protocol.AuthSigner

TODO

_images/adb.sign_pycryptodome.PycryptodomeAuthSigner.CALL_GRAPH.svg
Parameters

rsa_key_path (str, None) – The path to the private key

public_key

The contents of the public key file

Type

str

rsa_key

The contents of theprivate key

Type

Crypto.PublicKey.RSA.RsaKey

GetPublicKey()[source]

Returns the public key in PEM format without headers or newlines.

Returns

self.public_key – The contents of the public key file

Return type

str

Sign(data)[source]

Signs given data using a private key.

Parameters

data (bytes, bytearray) – The data to be signed

Returns

The signed data

Return type

bytes

adb.sign_pythonrsa module
adb.usb_exceptions module

Common exceptions for ADB and Fastboot.

Contents

exception adb.usb_exceptions.AdbCommandFailureException[source]

Bases: Exception

ADB Command returned a FAIL.

_images/adb.usb_exceptions.AdbCommandFailureException.CALL_GRAPH.svg
exception adb.usb_exceptions.AdbOperationException[source]

Bases: Exception

Failed to communicate over adb with device after multiple retries.

_images/adb.usb_exceptions.AdbOperationException.CALL_GRAPH.svg
exception adb.usb_exceptions.CommonUsbError[source]

Bases: Exception

Base class for usb communication errors.

_images/adb.usb_exceptions.CommonUsbError.CALL_GRAPH.svg
exception adb.usb_exceptions.DeviceAuthError(message, *args)[source]

Bases: adb.usb_exceptions.FormatMessageWithArgumentsException

Device authentication failed.

_images/adb.usb_exceptions.DeviceAuthError.CALL_GRAPH.svg
exception adb.usb_exceptions.DeviceNotFoundError(message, *args)[source]

Bases: adb.usb_exceptions.FormatMessageWithArgumentsException

Device isn’t on USB.

_images/adb.usb_exceptions.DeviceNotFoundError.CALL_GRAPH.svg
exception adb.usb_exceptions.FormatMessageWithArgumentsException(message, *args)[source]

Bases: adb.usb_exceptions.CommonUsbError

Exception that both looks good and is functional.

Okay, not that kind of functional, it’s still a class.

This interpolates the message with the given arguments to make it human-readable, but keeps the arguments in case other code try-excepts it.

_images/adb.usb_exceptions.FormatMessageWithArgumentsException.CALL_GRAPH.svg
Parameters
  • message (str) – The error message

  • args (str) – Positional arguments for formatting message

exception adb.usb_exceptions.LibusbWrappingError(msg, usb_error)[source]

Bases: adb.usb_exceptions.CommonUsbError

Wraps libusb1 errors while keeping their original usefulness.

_images/adb.usb_exceptions.LibusbWrappingError.CALL_GRAPH.svg
Parameters
  • msg (str) – The error message

  • usb_error (libusb1.USBError) – An exception from libusb1

usb_error

An exception from libusb1

Type

libusb1.USBError

exception adb.usb_exceptions.ReadFailedError(msg, usb_error)[source]

Bases: adb.usb_exceptions.LibusbWrappingError

Raised when the device doesn’t respond to our commands.

_images/adb.usb_exceptions.ReadFailedError.CALL_GRAPH.svg
exception adb.usb_exceptions.TcpTimeoutException(message, *args)[source]

Bases: adb.usb_exceptions.FormatMessageWithArgumentsException

TCP connection timed out in the time out given.

_images/adb.usb_exceptions.TcpTimeoutException.CALL_GRAPH.svg
exception adb.usb_exceptions.WriteFailedError(msg, usb_error)[source]

Bases: adb.usb_exceptions.LibusbWrappingError

Raised when the device doesn’t accept our command.

_images/adb.usb_exceptions.WriteFailedError.CALL_GRAPH.svg

Module contents

Note: This is not an official Google project. It is maintained by ex-Google engineers. For a better maintained option, look at adb_shell.

This repository contains a pure-python implementation of the ADB and Fastboot protocols, using libusb1 for USB communications.

This is a complete replacement and rearchitecture of the Android project’s ADB and fastboot code.

This code is mainly targeted to users that need to communicate with Android devices in an automated fashion, such as in automated testing. It does not have a daemon between the client and the device, and therefore does not support multiple simultaneous commands to the same device. It does support any number of devices and never communicates with a device that it wasn’t intended to, unlike the Android project’s ADB.

Using as standalone tool

Install using pip:

pip install adb

Once installed, two new binaries should be available: pyadb and pyfastboot.

pyadb devices
pyadb shell ls /sdcard

Running ./make_tools.py creates two files: adb.zip and fastboot.zip. They can be run similar to native adb and fastboot via the python interpreter:

python adb.zip devices
python adb.zip shell ls /sdcard

Using as a Python Library

A presentation was made at PyCon 2016, and here’s some demo code:

import os.path as op

from adb import adb_commands
from adb import sign_cryptography


# KitKat+ devices require authentication
signer = sign_cryptography.CryptographySigner(
    op.expanduser('~/.android/adbkey'))
# Connect to the device
device = adb_commands.AdbCommands()
device.ConnectDevice(
    rsa_keys=[signer])
# Now we can use Shell, Pull, Push, etc!
for i in xrange(10):
    print device.Shell('echo %d' % i)

Pros

  • Simpler code due to use of libusb1 and Python.

  • API can be used by other Python code easily.

  • Errors are propagated with tracebacks, helping debug connectivity issues.

  • No daemon outliving the command.

  • Can be packaged as standalone zips that can be run independent of the CPU architecture (e.g. x86 vs ARM).

Cons

  • Technically slower due to Python, mitigated by no daemon.

  • Only one command per device at a time.

  • More dependencies than Android’s ADB.

Dependencies

  • libusb1 (1.0.16+)

  • python-libusb1 (1.2.0+)

  • adb.zip: one of

    • py-cryptography

    • python-rsa (3.2+)

  • fastboot.zip (optional)

    • python-progressbar (2.3+)

History

1.0.0

  • Initial version

1.1.0

  • Added TcpHandle (jameyhicks)

  • Various timing and other changes (alusco)

1.2.0

  • Update to libusb1 1.6+ (bytearray output)

  • Add support for Python 3.6

  • Create adb.zip and fastboot.zip as executable tools.

  • Add Travis CI integration

  • Support multiple crypto libraries (M2Crypto + python-rsa)

  • Push directories

1.3.0

Backwards Incompatible changes

adb_commands.AdbCommands is now a normal class rather than a collection of staticmethods. Using the following example code to get started:

device = adb_commands.AdbCommands()
device.ConnectDevice(rsa_keys=[signer])

Other changes/fixes

Many changes since 1.2.0!

  • New entrypoints exposed by pip: pyadb and pyfastboot

  • Lots of Python 2/3 compatibility fixes

  • Windows compatibility fixes

  • Transfer progress available (Push, Pull, Install)

  • Handle some misbehaving devices (double CLSE bug)

  • New options for Push and Install (st_mode and grant_permissions)

Indices and tables