aio_adb_shell.adb_device module¶
Implement the AdbDevice class, which can connect to a device and run ADB shell commands.
Contents
-
class
aio_adb_shell.adb_device.AdbDevice(handle, banner=None)[source]¶ Bases:
objectA class with methods for connecting to a device and executing ADB commands.
- Parameters
handle (BaseHandle) – A user-provided handle for communicating with the device; must be an instance of a subclass of
BaseHandlebanner (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.InvalidHandleError – The passed
handleis not an instance of a subclass ofBaseHandle
-
_available¶ Whether an ADB connection to the device has been established
- Type
bool
The hostname of the machine where the Python interpreter is currently running
- Type
bytearray, bytes
-
_handle¶ The handle that is used to connect to the device; must be a subclass of
BaseHandle- Type
-
async
_close(adb_info)[source]¶ Send a
b'CLSE'message.Warning
This is not to be confused with the
AdbDevice.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 setfilesync_info.send_idxto 0.- Parameters
adb_info (_AdbTransactionInfo) – Info and settings for this ADB transaction
filesync_info (_FileSyncTransactionInfo) – Data and storage for this FileSync transaction
-
async
_filesync_read(expected_ids, adb_info, filesync_info, read_data=True)[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 raisedadb_info (_AdbTransactionInfo) – Info and settings for this ADB transaction
filesync_info (_FileSyncTransactionInfo) – Data and storage for this FileSync transaction
read_data (bool) – Whether to read the received data
- Returns
command_id (bytes) – The received header ID
tuple – The contents of the header
data (bytearray, None) – The received data, or
Noneifread_datais False
- Raises
adb_shell.exceptions.AdbCommandFailureException – Command failed
adb_shell.exceptions.InvalidResponseError – Received response was not in
expected_ids
-
async
_filesync_read_buffered(size, adb_info, filesync_info)[source]¶ Read
sizebytes of data fromself.recv_buffer.- Parameters
size (int) – The amount of data to read
adb_info (_AdbTransactionInfo) – Info and settings for this ADB transaction
filesync_info (_FileSyncTransactionInfo) – Data and storage for this FileSync transaction
- Returns
result – The read data
- Return type
bytearray
-
_filesync_read_until(expected_ids, finish_ids, adb_info, filesync_info)[source]¶ Useful wrapper around
AdbDevice._filesync_read().- Parameters
expected_ids (tuple[bytes]) – If the received header ID is not in
expected_ids, an exception will be raisedfinish_ids (tuple[bytes]) – We will read until we find a header ID that is in
finish_idsadb_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=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.
- 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) – Optionally override size from len(data).
-
static
_handle_progress(progress_callback)[source]¶ Calls the callback with the current progress and total bytes written/received.
- Parameters
progress_callback (function) – Callback method that accepts
filename,bytes_written, andtotal_bytes; total_bytes will be -1 for file-like objects.
-
async
_okay(adb_info)[source]¶ Send an
b'OKAY'mesage.- Parameters
adb_info (_AdbTransactionInfo) – Info and settings for this ADB transaction
-
async
_open(destination, adb_info)[source]¶ Opens a new connection to the device via an
b'OPEN'message._send()anb'OPEN'command to the device that specifies thelocal_id_read()a response from the device that includes a command, another local ID (their_local_id), andremote_idIf
local_idandtheir_local_iddo not match, raise an exception.If the received command is
b'CLSE',_read()another response from the deviceIf the received command is not
b'OKAY', raise an exceptionSet the
adb_info.local_idandadb_info.remote_idattributes
- Parameters
destination (bytes) –
b'SERVICE:COMMAND'adb_info (_AdbTransactionInfo) – Info and settings for this ADB transaction
- Raises
adb_shell.exceptions.InvalidResponseError – Wrong local_id sent to us.
-
async
_pull(filename, dest, progress_callback, adb_info, filesync_info)[source]¶ Pull a file from the device into the file-like
dest_file.- Parameters
filename (str) – The file to be pulled
dest (_io.BytesIO) – File-like object for writing to
progress_callback (function, None) – Callback method that accepts
filename,bytes_written, andtotal_bytesadb_info (_AdbTransactionInfo) – Info and settings for this ADB transaction
filesync_info (_FileSyncTransactionInfo) – Data and storage for this FileSync transaction
-
async
_push(datafile, filename, st_mode, mtime, progress_callback, adb_info, filesync_info)[source]¶ Push a file-like object to the device.
- Parameters
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, andtotal_bytesadb_info (_AdbTransactionInfo) – Info and settings for this ADB transaction
- Raises
PushFailedError – Raised on push failure.
-
async
_read(expected_cmds, adb_info)[source]¶ Receive a response from the device.
Read a message from the device and unpack the
cmd,arg0,arg1,data_length, anddata_checksumfieldsIf
cmdis not a recognized command inadb_shell.constants.WIRE_TO_ID, raise an exceptionIf the time has exceeded
total_timeout_s, raise an exceptionRead
data_lengthbytes from the deviceIf the checksum of the read data does not match
data_checksum, raise an exceptionReturn
command,arg0,arg1, andbytes(data)
- Parameters
expected_cmds (list[bytes]) – We will read packets until we encounter one whose “command” field is in
expected_cmdsadb_info (_AdbTransactionInfo) – Info and settings for this ADB transaction
- Returns
command (bytes) – The received command, which is in
adb_shell.constants.WIRE_TO_IDand must be inexpected_cmdsarg0 (int) – TODO
arg1 (int) – TODO
bytes – The data that was read
- Raises
adb_shell.exceptions.InvalidCommandError – Unknown command or never got one of the expected responses.
adb_shell.exceptions.InvalidChecksumError – Received checksum does not match the expected checksum.
-
async
_read_until(expected_cmds, adb_info)[source]¶ Read a packet, acknowledging any write packets.
Read data via
AdbDevice._read()If a
b'WRTE'packet is received, send anb'OKAY'packet viaAdbDevice._okay()Return the
cmdanddatathat were read byAdbDevice._read()
- Parameters
expected_cmds (list[bytes]) –
AdbDevice._read()with look for a packet whose command is inexpected_cmdsadb_info (_AdbTransactionInfo) – Info and settings for this ADB transaction
- Returns
cmd (bytes) – The command that was received by
AdbDevice._read(), which is inadb_shell.constants.WIRE_TO_IDand must be inexpected_cmdsdata (bytes) – The data that was received by
AdbDevice._read()
- Raises
adb_shell.exceptions.InterleavedDataError – We don’t support multiple streams…
adb_shell.exceptions.InvalidResponseError – Incorrect remote id.
adb_shell.exceptions.InvalidCommandError – Never got one of the expected responses.
-
_read_until_close(adb_info)[source]¶ Yield packets until a
b'CLSE'packet is received.Read the
cmdanddatafields from ab'CLSE'orb'WRTE'packet viaAdbDevice._read_until()If
cmdisb'CLSE', then send ab'CLSE'message and stopIf
cmdis notb'WRTE', raise an exceptionIf
cmdisb'FAIL', raiseAdbCommandFailureExceptionOtherwise, raise
InvalidCommandError
Yield
dataand repeat
- Parameters
adb_info (_AdbTransactionInfo) – Info and settings for this ADB transaction
- Yields
data (bytes) – The data that was read by
AdbDevice._read_until()
-
async
_send(msg, adb_info)[source]¶ Send a message to the device.
Send the message header (
adb_shell.adb_message.AdbMessage.pack)Send the message data
- Parameters
msg (AdbMessage) – The data that will be sent
adb_info (_AdbTransactionInfo) – Info and settings for this ADB transaction
-
async
_service(service, command, timeout_s=None, total_timeout_s=10.0, 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
timeout_s (float, None) – Timeout in seconds for sending and receiving packets, or
None; seeBaseHandle.bulk_read()andBaseHandle.bulk_write()total_timeout_s (float) – The total time in seconds to wait for a
b'CLSE'orb'OKAY'command inAdbDevice._read()decode (bool) – Whether to decode the output to utf8 before returning
- Returns
The output of the ADB command as a string if
decodeis True, otherwise as bytes.- Return type
bytes, str
-
_streaming_command(service, command, adb_info)[source]¶ One complete set of USB packets for a single command.
_open()a new connection to the device, where thedestinationparameter isservice:commandRead the response data via
AdbDevice._read_until_close()
Note
All the data is held in memory, and thus large responses will be slow and can fill up memory.
- Parameters
service (bytes) – The ADB service (e.g.,
b'shell', as used byAdbDevice.shell())command (bytes) – The service command
adb_info (_AdbTransactionInfo) – Info and settings for this ADB transaction
- Yields
bytes – The responses from the service.
-
_streaming_service(service, command, timeout_s=None, total_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
timeout_s (float, None) – Timeout in seconds for sending and receiving packets, or
None; seeBaseHandle.bulk_read()andBaseHandle.bulk_write()total_timeout_s (float) – The total time in seconds to wait for a
b'CLSE'orb'OKAY'command inAdbDevice._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
decodeis True, otherwise as bytes.
-
async
_write(data, adb_info)[source]¶ Write a packet and expect an Ack.
- Parameters
data (bytes) – The data that will be sent
adb_info (_AdbTransactionInfo) – Info and settings for this ADB transaction
-
property
available¶ Whether or not an ADB connection to the device has been established.
- Returns
self._available- Return type
bool
-
async
connect(rsa_keys=None, timeout_s=None, auth_timeout_s=10.0, total_timeout_s=10.0, auth_callback=None)[source]¶ Establish an ADB connection to the device.
Use the handle to establish a connection
Send a
b'CNXN'messageUnpack the
cmd,arg0,arg1, andbannerfields from the responseIf
cmdis notb'AUTH', then authentication is not necesary and so we are doneIf no
rsa_keysare provided, raise an exceptionLoop through our keys, signing the last
bannerthat we receivedIf the last
arg0was notadb_shell.constants.AUTH_TOKEN, raise an exceptionSign the last
bannerand send it in anb'AUTH'messageUnpack the
cmd,arg0, andbannerfields from the response viaadb_shell.adb_message.unpack()If
cmdisb'CNXN', returnbanner
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
rsa_keys (list, None) – A list of signers of type
CryptographySigner,PycryptodomeAuthSigner, orPythonRSASignertimeout_s (float, None) – Timeout in seconds for sending and receiving packets, or
None; seeBaseHandle.bulk_read()andBaseHandle.bulk_write()auth_timeout_s (float, None) – The time in seconds to wait for a
b'CNXN'authentication responsetotal_timeout_s (float) – The total time in seconds to wait for expected commands in
AdbDevice._read()auth_callback (function, None) – Function callback invoked when the connection needs to be accepted on the device
- Returns
Whether the connection was established (
AdbDevice.available)- Return type
bool
- Raises
adb_shell.exceptions.DeviceAuthError – Device authentication required, no keys available
adb_shell.exceptions.InvalidResponseError – Invalid auth response from the device
-
async
list(device_path, timeout_s=None, total_timeout_s=10.0)[source]¶ Return a directory listing of the given path.
- Parameters
device_path (str) – Directory to list.
timeout_s (float, None) – Expected timeout for any part of the pull.
total_timeout_s (float) – The total time in seconds to wait for a
b'CLSE'orb'OKAY'command inAdbDevice._read()
- Returns
files – Filename, mode, size, and mtime info for the files in the directory
- Return type
list[DeviceFile]
-
async
pull(device_filename, dest_file=None, progress_callback=None, timeout_s=None, total_timeout_s=10.0)[source]¶ Pull a file from the device.
- Parameters
device_filename (str) – Filename on the device to pull.
dest_file (str, file, io.IOBase, None) – If set, a filename or writable file-like object.
progress_callback (function, None) – Callback method that accepts filename, bytes_written and total_bytes, total_bytes will be -1 for file-like objects
timeout_s (float, None) – Expected timeout for any part of the pull.
total_timeout_s (float) – The total time in seconds to wait for a
b'CLSE'orb'OKAY'command inAdbDevice._read()
- Returns
The file data if
dest_fileis not set. Otherwise,Trueif the destination file exists- Return type
bytes, bool
- Raises
ValueError – If
dest_fileis of unknown type.
-
async
push(source_file, device_filename, st_mode=33272, mtime=0, progress_callback=None, timeout_s=None, total_timeout_s=10.0)[source]¶ Push a file or directory to the device.
- Parameters
source_file (str) – Either a filename, a directory or file-like object to push to the device.
device_filename (str) – Destination on the device to write to.
st_mode (int) – Stat mode for filename
mtime (int) – Modification time to set on the file.
progress_callback (function, None) – Callback method that accepts filename, bytes_written and total_bytes, total_bytes will be -1 for file-like objects
timeout_s (float, None) – Expected timeout for any part of the push.
total_timeout_s (float) – The total time in seconds to wait for a
b'CLSE'orb'OKAY'command inAdbDevice._read()
-
async
root(timeout_s=None, total_timeout_s=10.0)[source]¶ Gain root access.
The device must be rooted in order for this to work.
- Parameters
timeout_s (float, None) – Timeout in seconds for sending and receiving packets, or
None; seeBaseHandle.bulk_read()andBaseHandle.bulk_write()total_timeout_s (float) – The total time in seconds to wait for a
b'CLSE'orb'OKAY'command inAdbDevice._read()
-
async
shell(command, timeout_s=None, total_timeout_s=10.0, decode=True)[source]¶ Send an ADB shell command to the device.
- Parameters
command (str) – The shell command that will be sent
timeout_s (float, None) – Timeout in seconds for sending and receiving packets, or
None; seeBaseHandle.bulk_read()andBaseHandle.bulk_write()total_timeout_s (float) – The total time in seconds to wait for a
b'CLSE'orb'OKAY'command inAdbDevice._read()decode (bool) – Whether to decode the output to utf8 before returning
- Returns
The output of the ADB shell command as a string if
decodeis True, otherwise as bytes.- Return type
bytes, str
-
async
stat(device_filename, timeout_s=None, total_timeout_s=10.0)[source]¶ Get a file’s
stat()information.- Parameters
device_filename (str) – The file on the device for which we will get information.
timeout_s (float, None) – Expected timeout for any part of the pull.
total_timeout_s (float) – The total time in seconds to wait for a
b'CLSE'orb'OKAY'command inAdbDevice._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
-
streaming_shell(command, timeout_s=None, total_timeout_s=10.0, decode=True)[source]¶ Send an ADB shell command to the device, yielding each line of output.
- Parameters
command (str) – The shell command that will be sent
timeout_s (float, None) – Timeout in seconds for sending and receiving packets, or
None; seeBaseHandle.bulk_read()andBaseHandle.bulk_write()total_timeout_s (float) – The total time in seconds to wait for a
b'CLSE'orb'OKAY'command inAdbDevice._read()decode (bool) – Whether to decode the output to utf8 before returning
- Yields
bytes, str – The line-by-line output of the ADB shell command as a string if
decodeis True, otherwise as bytes.
-
class
aio_adb_shell.adb_device.AdbDeviceTcp(host, port=5555, default_timeout_s=None, banner=None)[source]¶ Bases:
aio_adb_shell.adb_device.AdbDeviceA 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_timeout_s (float, None) – Default timeout in seconds for TCP packets, or
Nonebanner (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
The hostname of the machine where the Python interpreter is currently running
- Type
bytearray, bytes
-
class
aio_adb_shell.adb_device.DeviceFile(filename, mode, size, mtime)¶ Bases:
tuple-
_asdict()¶ Return a new OrderedDict which maps field names to their values.
-
_fields= ('filename', 'mode', 'size', 'mtime')¶
-
_fields_defaults= {}¶
-
classmethod
_make(iterable)¶ Make a new DeviceFile object from a sequence or iterable
-
_replace(**kwds)¶ Return a new DeviceFile object replacing specified fields with new values
-
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
aio_adb_shell.adb_device._AdbTransactionInfo(local_id, remote_id, timeout_s=None, total_timeout_s=10.0)[source]¶ Bases:
objectA class for storing info and settings used during a single ADB “transaction.”
- Parameters
local_id (int) – The ID for the sender (i.e., the device running this code)
remote_id (int) – The ID for the recipient
timeout_s (float, None) – Timeout in seconds for sending and receiving packets, or
None; seeBaseHandle.bulk_read()andBaseHandle.bulk_write()total_timeout_s (float) – The total time in seconds to wait for a command in
expected_cmdsinAdbDevice._read()
-
local_id¶ The ID for the sender (i.e., the device running this code)
- Type
int
-
remote_id¶ The ID for the recipient
- Type
int
-
timeout_s¶ Timeout in seconds for sending and receiving packets, or
None; seeBaseHandle.bulk_read()andBaseHandle.bulk_write()- Type
float, None
-
total_timeout_s¶ The total time in seconds to wait for a command in
expected_cmdsinAdbDevice._read()- Type
float
-
class
aio_adb_shell.adb_device._FileSyncTransactionInfo(recv_message_format)[source]¶ Bases:
objectA class for storing info used during a single FileSync “transaction.”
- Parameters
recv_message_format (bytes) – The FileSync message format
-
recv_buffer¶ A buffer for storing received data
- Type
bytearray
-
recv_message_format¶ The FileSync message format
- Type
bytes
-
recv_message_size¶ The FileSync message size
- Type
int
-
send_buffer¶ A buffer for storing data to be sent
- Type
bytearray
-
send_idx¶ The index in
recv_bufferthat will be the start of the next data packet sent- Type
int
-
can_add_to_send_buffer(data_len)[source]¶ Determine whether
data_lenbytes of data can be added to the send buffer without exceedingconstants.MAX_ADB_DATA.- 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_lenbytes of data can be added to the send buffer without exceedingconstants.MAX_ADB_DATA- Return type
bool