adb_shell.adb_device_async module

Implement the AdbDeviceAsync class, which can connect to a device and run ADB shell commands.

class adb_shell.adb_device_async.AdbDeviceAsync(transport, default_transport_timeout_s=None, banner=None)[source]

Bases: object

A class with methods for connecting to a device and executing ADB commands.

Parameters:
  • transport (BaseTransportAsync) – A user-provided transport for communicating with the device; must be an instance of a subclass of BaseTransportAsync

  • default_transport_timeout_s (float, None) – Default timeout in seconds for transport packets, or None

  • banner (str, bytes, None) – The hostname of the machine where the Python interpreter is currently running; if it is not provided, it will be determined via socket.gethostname()

Raises:

adb_shell.exceptions.InvalidTransportError – The passed transport is not an instance of a subclass of BaseTransportAsync

_available

Whether an ADB connection to the device has been established

Type:

bool

_banner

The hostname of the machine where the Python interpreter is currently running

Type:

bytearray, bytes

_default_transport_timeout_s

Default timeout in seconds for transport packets, or None

Type:

float, None

_io_manager

Used for handling all ADB I/O

Type:

_AdbIOManagerAsync

_local_id

The local ID that is used for ADB transactions; the value is incremented each time and is always in the range [1, 2^32)

Type:

int

_local_id_lock

A lock for protecting _local_id; this is never held for long

Type:

Lock

_maxdata

Maximum amount of data in an ADB packet

Type:

int

_transport

The transport that is used to connect to the device; must be a subclass of BaseTransportAsync

Type:

BaseTransportAsync

async _clse(adb_info)[source]

Send a b'CLSE' message and then read a b'CLSE' message.

Warning

This is not to be confused with the AdbDeviceAsync.close() method!

Parameters:

adb_info (_AdbTransactionInfo) – Info and settings for this ADB transaction

async _filesync_flush(adb_info, filesync_info)[source]

Write the data in the buffer up to filesync_info.send_idx, then set filesync_info.send_idx to 0.

Parameters:
async _filesync_read(expected_ids, adb_info, filesync_info)[source]

Read ADB messages and return FileSync packets.

Parameters:
  • expected_ids (tuple[bytes]) – If the received header ID is not in expected_ids, an exception will be raised

  • adb_info (_AdbTransactionInfo) – Info and settings for this ADB transaction

  • filesync_info (_FileSyncTransactionInfo) – Data and storage for this FileSync transaction

Returns:

  • command_id (bytes) – The received header ID

  • tuple – The contents of the header

  • data (bytearray, None) – The received data, or None if the command ID is adb_shell.constants.STAT

Raises:
async _filesync_read_buffered(size, adb_info, filesync_info)[source]

Read size bytes of data from self.recv_buffer.

Parameters:
Returns:

result – The read data

Return type:

bytearray

async _filesync_read_until(expected_ids, finish_ids, adb_info, filesync_info)[source]

Useful wrapper around AdbDeviceAsync._filesync_read().

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

  • adb_info (_AdbTransactionInfo) – Info and settings for this ADB transaction

  • filesync_info (_FileSyncTransactionInfo) – Data and storage for this FileSync transaction

Yields:
  • cmd_id (bytes) – The received header ID

  • header (tuple) – TODO

  • data (bytearray) – The received data

async _filesync_send(command_id, adb_info, filesync_info, data=b'', size=None)[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.

Parameters:
  • command_id (bytes) – Command to send.

  • adb_info (_AdbTransactionInfo) – Info and settings for this ADB transaction

  • filesync_info (_FileSyncTransactionInfo) – Data and storage for this FileSync transaction

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

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

_get_transport_timeout_s(transport_timeout_s)[source]

Use the provided transport_timeout_s if it is not None; otherwise, use self._default_transport_timeout_s

Parameters:

transport_timeout_s (float, None) – The potential transport timeout

Returns:

transport_timeout_s if it is not None; otherwise, self._default_transport_timeout_s

Return type:

float

async _okay(adb_info)[source]

Send an b'OKAY' mesage.

Parameters:

adb_info (_AdbTransactionInfo) – Info and settings for this ADB transaction

async _open(destination, transport_timeout_s, read_timeout_s, timeout_s)[source]

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

  1. send() an b'OPEN' command to the device that specifies the local_id

  2. read() the response from the device and fill in the adb_info.remote_id attribute

Parameters:
Returns:

adb_info – Info and settings for this ADB transaction

Return type:

_AdbTransactionInfo

async _pull(device_path, stream, progress_callback, adb_info, filesync_info)[source]

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

Parameters:
  • device_path (str) – The file on the device that will be pulled

  • stream (AsyncBufferedIOBase, _AsyncBytesIO) – File-like object for writing to

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

  • adb_info (_AdbTransactionInfo) – Info and settings for this ADB transaction

  • filesync_info (_FileSyncTransactionInfo) – Data and storage for this FileSync transaction

async _push(stream, device_path, st_mode, mtime, progress_callback, adb_info, filesync_info)[source]

Push a file-like object to the device.

Parameters:
  • stream (AsyncBufferedReader, _AsyncBytesIO) – File-like object for reading from

  • device_path (str) – Destination on the device to write to

  • st_mode (int) – Stat mode for the file

  • mtime (int) – Modification time

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

  • adb_info (_AdbTransactionInfo) – Info and settings for this ADB transaction

Raises:

PushFailedError – Raised on push failure.

async _read_until(expected_cmds, adb_info)[source]

Read a packet, acknowledging any write packets.

  1. Read data via _AdbIOManagerAsync.read()

  2. If a b'WRTE' packet is received, send an b'OKAY' packet via AdbDeviceAsync._okay()

  3. Return the cmd and data that were read by _AdbIOManagerAsync.read()

Parameters:
Returns:

async _read_until_close(adb_info)[source]

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

  1. Read the cmd and data fields from a b'CLSE' or b'WRTE' packet via AdbDeviceAsync._read_until()

  2. If cmd is b'CLSE', then send a b'CLSE' message and stop

  3. Yield data and repeat

Parameters:

adb_info (_AdbTransactionInfo) – Info and settings for this ADB transaction

Yields:

data (bytes) – The data that was read by AdbDeviceAsync._read_until()

async _service(service, command, transport_timeout_s=None, read_timeout_s=10.0, timeout_s=None, decode=True)[source]

Send an ADB command to the device.

Parameters:
  • service (bytes) – The ADB service to talk to (e.g., b'shell')

  • command (bytes) – The command that will be sent

  • transport_timeout_s (float, None) – Timeout in seconds for sending and receiving data, or None; see BaseTransportAsync.bulk_read() and BaseTransportAsync.bulk_write()

  • read_timeout_s (float) – The total time in seconds to wait for a b'CLSE' or b'OKAY' command in _AdbIOManagerAsync.read()

  • timeout_s (float, None) – The total time in seconds to wait for the ADB command to finish

  • decode (bool) – Whether to decode the output to utf8 before returning

Returns:

The output of the ADB command as a string if decode is True, otherwise as bytes.

Return type:

bytes, str

async _streaming_command(service, command, transport_timeout_s, read_timeout_s, timeout_s)[source]

One complete set of packets for a single command.

  1. _open() a new connection to the device, where the destination parameter is service:command

  2. Read the response data via AdbDeviceAsync._read_until_close()

Note

All the data is held in memory, and thus large responses will be slow and can fill up memory.

Parameters:
Yields:

bytes – The responses from the service.

async _streaming_service(service, command, transport_timeout_s=None, read_timeout_s=10.0, decode=True)[source]

Send an ADB command to the device, yielding each line of output.

Parameters:
  • service (bytes) – The ADB service to talk to (e.g., b'shell')

  • command (bytes) – The command that will be sent

  • transport_timeout_s (float, None) – Timeout in seconds for sending and receiving data, or None; see BaseTransportAsync.bulk_read() and BaseTransportAsync.bulk_write()

  • read_timeout_s (float) – The total time in seconds to wait for a b'CLSE' or b'OKAY' command in _AdbIOManagerAsync.read()

  • decode (bool) – Whether to decode the output to utf8 before returning

Yields:

bytes, str – The line-by-line output of the ADB command as a string if decode is True, otherwise as bytes.

property available

Whether or not an ADB connection to the device has been established.

Returns:

self._available

Return type:

bool

async close()[source]

Close the connection via the provided transport’s close() method.

async connect(rsa_keys=None, transport_timeout_s=None, auth_timeout_s=10.0, read_timeout_s=10.0, auth_callback=None)[source]

Establish an ADB connection to the device.

See _AdbIOManagerAsync.connect().

Parameters:
Returns:

Whether the connection was established (AdbDeviceAsync.available)

Return type:

bool

async exec_out(command, transport_timeout_s=None, read_timeout_s=10.0, timeout_s=None, decode=True)[source]

Send an ADB exec-out command to the device.

https://www.linux-magazine.com/Issues/2017/195/Ask-Klaus

Parameters:
  • command (str) – The exec-out command that will be sent

  • transport_timeout_s (float, None) – Timeout in seconds for sending and receiving data, or None; see BaseTransportAsync.bulk_read() and BaseTransportAsync.bulk_write()

  • read_timeout_s (float) – The total time in seconds to wait for a b'CLSE' or b'OKAY' command in _AdbIOManagerAsync.read()

  • timeout_s (float, None) – The total time in seconds to wait for the ADB command to finish

  • decode (bool) – Whether to decode the output to utf8 before returning

Returns:

The output of the ADB exec-out command as a string if decode is True, otherwise as bytes.

Return type:

bytes, str

async list(device_path, transport_timeout_s=None, read_timeout_s=10.0)[source]

Return a directory listing of the given path.

Parameters:
  • device_path (str) – Directory to list.

  • transport_timeout_s (float, None) – Expected timeout for any part of the pull.

  • read_timeout_s (float) – The total time in seconds to wait for a b'CLSE' or b'OKAY' command in _AdbIOManagerAsync.read()

Returns:

files – Filename, mode, size, and mtime info for the files in the directory

Return type:

list[DeviceFile]

property max_chunk_size

Maximum chunk size for filesync operations

Returns:

Minimum value based on adb_shell.constants.MAX_CHUNK_SIZE and _max_data / 2, fallback to legacy adb_shell.constants.MAX_PUSH_DATA

Return type:

int

async pull(device_path, local_path, progress_callback=None, transport_timeout_s=None, read_timeout_s=10.0)[source]

Pull a file from the device.

Parameters:
  • device_path (str) – The file on the device that will be pulled

  • local_path (str, BytesIO) – The path or BytesIO stream where the file will be downloaded

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

  • transport_timeout_s (float, None) – Expected timeout for any part of the pull.

  • read_timeout_s (float) – The total time in seconds to wait for a b'CLSE' or b'OKAY' command in _AdbIOManagerAsync.read()

async push(local_path, device_path, st_mode=33272, mtime=0, progress_callback=None, transport_timeout_s=None, read_timeout_s=10.0)[source]

Push a file or directory to the device.

Parameters:
  • local_path (str, BytesIO) – A filename, directory, or BytesIO stream to push to the device

  • device_path (str) – Destination on the device to write to

  • st_mode (int) – Stat mode for local_path

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

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

  • transport_timeout_s (float, None) – Expected timeout for any part of the push

  • read_timeout_s (float) – The total time in seconds to wait for a b'CLSE' or b'OKAY' command in _AdbIOManagerAsync.read()

async reboot(fastboot=False, transport_timeout_s=None, read_timeout_s=10.0, timeout_s=None)[source]

Reboot the device.

Parameters:
  • fastboot (bool) – Whether to reboot the device into fastboot

  • transport_timeout_s (float, None) – Timeout in seconds for sending and receiving data, or None; see BaseTransportAsync.bulk_read() and BaseTransportAsync.bulk_write()

  • read_timeout_s (float) – The total time in seconds to wait for a b'CLSE' or b'OKAY' command in _AdbIOManager.read()

  • timeout_s (float, None) – The total time in seconds to wait for the ADB command to finish

async root(transport_timeout_s=None, read_timeout_s=10.0, timeout_s=None)[source]

Gain root access.

The device must be rooted in order for this to work.

Parameters:
async shell(command, transport_timeout_s=None, read_timeout_s=10.0, timeout_s=None, decode=True)[source]

Send an ADB shell command to the device.

Parameters:
  • command (str) – The shell command that will be sent

  • transport_timeout_s (float, None) – Timeout in seconds for sending and receiving data, or None; see BaseTransportAsync.bulk_read() and BaseTransportAsync.bulk_write()

  • read_timeout_s (float) – The total time in seconds to wait for a b'CLSE' or b'OKAY' command in _AdbIOManagerAsync.read()

  • timeout_s (float, None) – The total time in seconds to wait for the ADB command to finish

  • decode (bool) – Whether to decode the output to utf8 before returning

Returns:

The output of the ADB shell command as a string if decode is True, otherwise as bytes.

Return type:

bytes, str

async stat(device_path, transport_timeout_s=None, read_timeout_s=10.0)[source]

Get a file’s stat() information.

Parameters:
  • device_path (str) – The file on the device for which we will get information.

  • transport_timeout_s (float, None) – Expected timeout for any part of the pull.

  • read_timeout_s (float) – The total time in seconds to wait for a b'CLSE' or b'OKAY' command in _AdbIOManagerAsync.read()

Returns:

  • mode (int) – The octal permissions for the file

  • size (int) – The size of the file

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

async streaming_shell(command, transport_timeout_s=None, read_timeout_s=10.0, decode=True)[source]

Send an ADB shell command to the device, yielding each line of output.

Parameters:
Yields:

bytes, str – The line-by-line output of the ADB shell command as a string if decode is True, otherwise as bytes.

class adb_shell.adb_device_async.AdbDeviceTcpAsync(host, port=5555, default_transport_timeout_s=None, banner=None)[source]

Bases: AdbDeviceAsync

A class with methods for connecting to a device via TCP and executing ADB commands.

Parameters:
  • host (str) – The address of the device; may be an IP address or a host name

  • port (int) – The device port to which we are connecting (default is 5555)

  • default_transport_timeout_s (float, None) – Default timeout in seconds for TCP packets, or None

  • banner (str, bytes, None) – The hostname of the machine where the Python interpreter is currently running; if it is not provided, it will be determined via socket.gethostname()

_available

Whether an ADB connection to the device has been established

Type:

bool

_banner

The hostname of the machine where the Python interpreter is currently running

Type:

bytearray, bytes

_default_transport_timeout_s

Default timeout in seconds for TCP packets, or None

Type:

float, None

_local_id

The local ID that is used for ADB transactions; the value is incremented each time and is always in the range [1, 2^32)

Type:

int

_maxdata

Maximum amount of data in an ADB packet

Type:

int

_transport

The transport that is used to connect to the device

Type:

TcpTransportAsync

class adb_shell.adb_device_async._AdbIOManagerAsync(transport)[source]

Bases: object

A class for handling all ADB I/O.

Notes

When the self._store_lock and self._transport_lock locks are held at the same time, it must always be the case that the self._transport_lock is acquired first. This ensures that there is no potential for deadlock.

Parameters:

transport (BaseTransportAsync) – A transport for communicating with the device; must be an instance of a subclass of BaseTransportAsync

_packet_store

A store for holding packets that correspond to different ADB streams

Type:

_AdbPacketStore

_store_lock

A lock for protecting self._packet_store (this lock is never held for long)

Type:

Lock

_transport

A transport for communicating with the device; must be an instance of a subclass of BaseTransportAsync

Type:

BaseTransportAsync

_transport_lock

A lock for protecting self._transport

Type:

Lock

async _read_bytes_from_device(length, adb_info)[source]

Read length bytes from the device.

Parameters:
  • length (int) – We will read packets until we get this length of data

  • adb_info (_AdbTransactionInfo) – Info and settings for this ADB transaction

Returns:

The data that was read

Return type:

bytes

Raises:

adb_shell.exceptions.AdbTimeoutError – Did not read length bytes in time

async _read_expected_packet_from_device(expected_cmds, adb_info)[source]

Read packets from the device until we get an expected packet type.

Parameters:
  • expected_cmds (list[bytes]) – We will read packets until we encounter one whose “command” field is in expected_cmds

  • adb_info (_AdbTransactionInfo) – Info and settings for this ADB transaction

Returns:

  • cmd (bytes) – The received command, which is in adb_shell.constants.WIRE_TO_ID and must be in expected_cmds

  • arg0 (int) – TODO

  • arg1 (int) – TODO

  • data (bytes) – The data that was read

Raises:

adb_shell.exceptions.AdbTimeoutError – Never got one of the expected responses

async _read_packet_from_device(adb_info)[source]

Read a complete ADB packet (header + data) from the device.

Parameters:

adb_info (_AdbTransactionInfo) – Info and settings for this ADB transaction

Returns:

  • cmd (bytes) – The received command, which is in adb_shell.constants.WIRE_TO_ID and must be in expected_cmds

  • arg0 (int) – TODO

  • arg1 (int) – TODO

  • bytes – The data that was read

Raises:
async _send(msg, adb_info)[source]

Send a message to the device.

  1. Send the message header (adb_shell.adb_message.AdbMessage.pack)

  2. Send the message data

Parameters:
async close()[source]

Close the connection via the provided transport’s close() method and clear the packet store.

async connect(banner, rsa_keys, auth_timeout_s, auth_callback, adb_info)[source]

Establish an ADB connection to the device.

  1. Use the transport to establish a connection

  2. Send a b'CNXN' message

  3. Read the response from the device

  4. If cmd is not b'AUTH', then authentication is not necesary and so we are done

  5. If no rsa_keys are provided, raise an exception

  6. Loop through our keys, signing the last banner2 that we received

    1. If the last arg0 was not adb_shell.constants.AUTH_TOKEN, raise an exception

    2. Sign the last banner2 and send it in an b'AUTH' message

    3. Read the response from the device

    4. If cmd is b'CNXN', we are done

  7. None of the keys worked, so send rsa_keys[0]’s public key; if the response does not time out, we must have connected successfully

Parameters:
Returns:

  • bool – Whether the connection was established

  • maxdata (int) – Maximum amount of data in an ADB packet

Raises:
async read(expected_cmds, adb_info, allow_zeros=False)[source]

Read packets from the device until we get an expected packet type.

  1. See if the expected packet is in the packet store

  2. While the time limit has not been exceeded:

    1. See if the expected packet is in the packet store

    2. Read a packet from the device. If it matches what we are looking for, we are done. If it corresponds to a different stream, add it to the store.

  3. Raise a timeout exception

Parameters:
  • expected_cmds (list[bytes]) – We will read packets until we encounter one whose “command” field is in expected_cmds

  • adb_info (_AdbTransactionInfo) – Info and settings for this ADB transaction

  • allow_zeros (bool) – Whether to allow the received arg0 and arg1 values to match with 0, in addition to adb_info.remote_id and adb_info.local_id, respectively

Returns:

  • cmd (bytes) – The received command, which is in adb_shell.constants.WIRE_TO_ID and must be in expected_cmds

  • arg0 (int) – TODO

  • arg1 (int) – TODO

  • data (bytes) – The data that was read

Raises:

adb_shell.exceptions.AdbTimeoutError – Never got one of the expected responses

async send(msg, adb_info)[source]

Send a message to the device.

Parameters:
class adb_shell.adb_device_async._AsyncBytesIO(bytesio)[source]

Bases: object

An async wrapper for BytesIO.

Parameters:

bytesio (BytesIO) – The BytesIO object that is wrapped

async read(size=-1)[source]

Read data.

Parameters:

size (int) – The size of the data to be read

Returns:

The data that was read

Return type:

bytes

async write(data)[source]

Write data.

Parameters:

data (bytes) – The data to be written

adb_shell.adb_device_async._open_bytesio(stream, *args, **kwargs)[source]

An async context manager for a BytesIO object that does nothing.

Parameters:
  • stream (BytesIO) – The BytesIO stream

  • args (list) – Unused positional arguments

  • kwargs (dict) – Unused keyword arguments

Yields:

_AsyncBytesIO – The wrapped stream input parameter