adb_shell Documentation
adb_shell
adb_shell package
Subpackages
adb_shell.auth package
Submodules
adb_shell.auth.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_shell.auth.keygen.ANDROID_PUBKEY_MODULUS_SIZE = 256
Size of an RSA modulus such as an encrypted block or a signature.
- adb_shell.auth.keygen.ANDROID_PUBKEY_MODULUS_SIZE_WORDS = 64
Size of the RSA modulus in words.
- adb_shell.auth.keygen.ANDROID_RSAPUBLICKEY_STRUCT = '<LL256s256sL'
Python representation of “struct RSAPublicKey”
- adb_shell.auth.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_shell.auth.keygen.decode_pubkey(public_key)[source]
Decode a public RSA key stored in Android’s custom binary format.
- Parameters:
public_key (TODO) – TODO
- adb_shell.auth.keygen.decode_pubkey_file(public_key_path)[source]
TODO
- Parameters:
public_key_path (str) – TODO
- adb_shell.auth.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_shell.auth.keygen.get_user_info()[source]
TODO
- Returns:
' <username>@<hostname>
- Return type:
str
adb_shell.auth.sign_cryptography module
ADB authentication using the cryptography
package.
Contents
- class adb_shell.auth.sign_cryptography.CryptographySigner(rsa_key_path)[source]
Bases:
object
AuthSigner using cryptography.io.
- 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
adb_shell.auth.sign_pycryptodome module
ADB authentication using pycryptodome
.
Contents
- class adb_shell.auth.sign_pycryptodome.PycryptodomeAuthSigner(rsa_key_path=None)[source]
Bases:
object
AuthSigner using the pycryptodome package.
- 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
adb_shell.auth.sign_pythonrsa module
ADB authentication using the rsa
package.
Contents
- class adb_shell.auth.sign_pythonrsa.PythonRSASigner(pub=None, priv=None)[source]
Bases:
object
Implements
adb_protocol.AuthSigner
using http://stuvel.eu/rsa.- Parameters:
pub (str, None) – The contents of the public key file
priv (str, None) – The contents of the private key file
- priv_key
The loaded private key
- Type:
rsa.key.PrivateKey
- pub_key
The contents of the public key file
- Type:
str, None
- classmethod FromRSAKeyPath(rsa_key_path)[source]
Create a
PythonRSASigner
instance using the provided private key.- Parameters:
rsa_key_path (str) – The path to the private key; the public key must be
rsa_key_path + '.pub'
.- Returns:
A
PythonRSASigner
with private keyrsa_key_path
and public keyrsa_key_path + '.pub'
- Return type:
- class adb_shell.auth.sign_pythonrsa._Accum[source]
Bases:
object
A fake hashing algorithm.
The Python
rsa
lib hashes all messages it signs. ADB does it already, we just need to slap a signature on top of already hashed message. Introduce a “fake” hashing algo for this.- _buf
A buffer for storing data before it is signed
- Type:
bytes
- adb_shell.auth.sign_pythonrsa._load_rsa_private_key(pem)[source]
PEM encoded PKCS#8 private key ->
rsa.PrivateKey
.ADB uses private RSA keys in pkcs#8 format. The
rsa
library doesn’t support them natively. Do some ASN unwrapping to extract naked RSA key (in der-encoded form).See:
- Parameters:
pem (str) – The private key to be loaded
- Returns:
The loaded private key
- Return type:
rsa.key.PrivateKey
Module contents
adb_shell.transport package
Submodules
adb_shell.transport.base_transport module
A base class for transports used to communicate with a device.
- class adb_shell.transport.base_transport.BaseTransport[source]
Bases:
ABC
A base transport class.
- _abc_impl = <_abc._abc_data object>
- abstract bulk_read(numbytes, transport_timeout_s)[source]
Read data from the device.
- Parameters:
numbytes (int) – The maximum amount of data to be received
transport_timeout_s (float, None) – A timeout for the read operation
- Returns:
The received data
- Return type:
bytes
adb_shell.transport.base_transport_async module
A base class for transports used to communicate with a device.
- class adb_shell.transport.base_transport_async.BaseTransportAsync[source]
Bases:
ABC
A base transport class.
- _abc_impl = <_abc._abc_data object>
- abstract async bulk_read(numbytes, transport_timeout_s)[source]
Read data from the device.
- Parameters:
numbytes (int) – The maximum amount of data to be received
transport_timeout_s (float, None) – A timeout for the read operation
- Returns:
The received data
- Return type:
bytes
adb_shell.transport.tcp_transport module
A class for creating a socket connection with the device and sending and receiving data.
- class adb_shell.transport.tcp_transport.TcpTransport(host, port=5555)[source]
Bases:
BaseTransport
TCP connection object.
- 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)
- _connection
A socket connection to the device
- Type:
socket.socket, None
- _host
The address of the device; may be an IP address or a host name
- Type:
str
- _port
The device port to which we are connecting (default is 5555)
- Type:
int
- _abc_impl = <_abc._abc_data object>
- bulk_read(numbytes, transport_timeout_s)[source]
Receive data from the socket.
- Parameters:
numbytes (int) – The maximum amount of data to be received
transport_timeout_s (float, None) – When the timeout argument is omitted,
select.select
blocks until at least one file descriptor is ready. A time-out value of zero specifies a poll and never blocks.
- Returns:
The received data
- Return type:
bytes
- Raises:
TcpTimeoutException – Reading timed out.
- bulk_write(data, transport_timeout_s)[source]
Send data to the socket.
- Parameters:
data (bytes) – The data to be sent
transport_timeout_s (float, None) – When the timeout argument is omitted,
select.select
blocks until at least one file descriptor is ready. A time-out value of zero specifies a poll and never blocks.
- Returns:
The number of bytes sent
- Return type:
int
- Raises:
TcpTimeoutException – Sending data timed out. No data was sent.
adb_shell.transport.tcp_transport_async module
A class for creating a socket connection with the device and sending and receiving data.
- class adb_shell.transport.tcp_transport_async.TcpTransportAsync(host, port=5555)[source]
Bases:
BaseTransportAsync
TCP connection object.
- 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)
- _host
The address of the device; may be an IP address or a host name
- Type:
str
- _port
The device port to which we are connecting (default is 5555)
- Type:
int
- _reader
Object for reading data from the socket
- Type:
StreamReader, None
- _writer
Object for writing data to the socket
- Type:
StreamWriter, None
- _abc_impl = <_abc._abc_data object>
- async bulk_read(numbytes, transport_timeout_s)[source]
Receive data from the socket.
- Parameters:
numbytes (int) – The maximum amount of data to be received
transport_timeout_s (float, None) – Timeout for reading data from the socket; if it is
None
, then it will block until the read operation completes
- Returns:
The received data
- Return type:
bytes
- Raises:
TcpTimeoutException – Reading timed out.
- async bulk_write(data, transport_timeout_s)[source]
Send data to the socket.
- Parameters:
data (bytes) – The data to be sent
transport_timeout_s (float, None) – Timeout for writing data to the socket; if it is
None
, then it will block until the write operation completes
- Returns:
The number of bytes sent
- Return type:
int
- Raises:
TcpTimeoutException – Sending data timed out. No data was sent.
adb_shell.transport.usb_transport module
A class for creating a USB connection with the device and sending and receiving data.
Warning
USB support is an experimental feature.
-
UsbTransport._timeout()
- adb_shell.transport.usb_transport.DEFAULT_TIMEOUT_S = 10
Default timeout
- class adb_shell.transport.usb_transport.UsbTransport(device, setting, usb_info=None, default_transport_timeout_s=None)[source]
Bases:
BaseTransport
USB communication object. Not thread-safe.
Handles reading and writing over USB with the proper endpoints, exceptions, and interface claiming.
- Parameters:
device (usb1.USBDevice) – libusb_device to connect to.
setting (usb1.USBInterfaceSetting) – libusb setting with the correct endpoints to communicate with.
usb_info (TODO, None) – String describing the usb path/serial/device, for debugging.
default_transport_timeout_s (TODO, None) – Timeout in seconds for all I/O.
- _default_transport_timeout_s
Timeout in seconds for all I/O.
- Type:
TODO, None
- _device
libusb_device to connect to.
- Type:
TODO
- _transport
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
- _usb_info
String describing the usb path/serial/device, for debugging.
- Type:
TODO
- _write_endpoint
TODO
- Type:
TODO, None
- _HANDLE_CACHE = <WeakValueDictionary>
- _HANDLE_CACHE_LOCK = <unlocked _thread.lock object>
- _abc_impl = <_abc._abc_data object>
- classmethod _find(setting_matcher, port_path=None, serial=None, default_transport_timeout_s=None)[source]
Gets the first device that matches according to the keyword args.
- Parameters:
setting_matcher (TODO) – TODO
port_path (TODO, None) – TODO
serial (TODO, None) – TODO
default_transport_timeout_s (TODO, None) – TODO
- Returns:
TODO
- Return type:
TODO
- classmethod _find_and_open(setting_matcher, port_path=None, serial=None, default_transport_timeout_s=None)[source]
TODO
- Parameters:
setting_matcher (TODO) – TODO
port_path (TODO, None) – TODO
serial (TODO, None) – TODO
default_transport_timeout_s (TODO, None) – TODO
- Returns:
dev – TODO
- Return type:
TODO
- classmethod _find_devices(setting_matcher, device_matcher=None, usb_info='', default_transport_timeout_s=None)[source]
_find and yield the devices that match.
- Parameters:
setting_matcher (TODO) – Function that returns the setting to use given a
usb1.USBDevice
, orNone
if the device doesn’t have a valid setting.device_matcher (TODO, None) – Function that returns
True
if the givenUsbTransport
is valid.None
to match any device.usb_info (str) – Info string describing device(s).
default_transport_timeout_s (TODO, None) – Default timeout of commands in seconds.
- Yields:
TODO – UsbTransport instances
- classmethod _find_first(setting_matcher, device_matcher=None, usb_info='', default_transport_timeout_s=None)[source]
Find and return the first matching device.
- Parameters:
setting_matcher (TODO) – Function that returns the setting to use given a
usb1.USBDevice
, orNone
if the device doesn’t have a valid setting.device_matcher (TODO) – Function that returns
True
if the givenUsbTransport
is valid.None
to match any device.usb_info (str) – Info string describing device(s).
default_transport_timeout_s (TODO, None) – Default timeout of commands in seconds.
- Returns:
An instance of UsbTransport
- Return type:
TODO
- Raises:
adb_shell.exceptions.DeviceNotFoundError – Raised if the device is not available.
- classmethod _port_path_matcher(port_path)[source]
Returns a device matcher for the given port path.
- Parameters:
port_path (TODO) – TODO
- Returns:
TODO
- Return type:
function
- classmethod _serial_matcher(serial)[source]
Returns a device matcher for the given serial.
- Parameters:
serial (TODO) – TODO
- Returns:
TODO
- Return type:
function
- bulk_read(numbytes, transport_timeout_s=None)[source]
Receive data from the USB device.
- Parameters:
numbytes (int) – The maximum amount of data to be received
transport_timeout_s (float, None) – When the timeout argument is omitted,
select.select
blocks until at least one file descriptor is ready. A time-out value of zero specifies a poll and never blocks.
- Returns:
The received data
- Return type:
bytes
- Raises:
adb_shell.exceptions.UsbReadFailedError – Could not receive data
- bulk_write(data, transport_timeout_s=None)[source]
Send data to the USB device.
- Parameters:
data (bytes) – The data to be sent
transport_timeout_s (float, None) – When the timeout argument is omitted,
select.select
blocks until at least one file descriptor is ready. A time-out value of zero specifies a poll and never blocks.
- Returns:
The number of bytes sent
- Return type:
int
- Raises:
adb_shell.exceptions.UsbWriteFailedError – This transport has been closed, probably due to another being opened
adb_shell.exceptions.UsbWriteFailedError – Could not send data
- connect(transport_timeout_s=None)[source]
Create a USB connection to the device.
- Parameters:
transport_timeout_s (float, None) – Set the timeout on the USB instance
- classmethod find_adb(serial=None, port_path=None, default_transport_timeout_s=None)[source]
TODO
- Parameters:
serial (TODO) – TODO
port_path (TODO) – TODO
default_transport_timeout_s (TODO, None) – Default timeout of commands in seconds.
- Returns:
TODO
- Return type:
- classmethod find_all_adb_devices(default_transport_timeout_s=None)[source]
Find all ADB devices attached via USB.
- Parameters:
default_transport_timeout_s (TODO, None) – Default timeout of commands in seconds.
- Returns:
A generator which yields each ADB device attached via USB.
- Return type:
generator
- property port_path
TODO
- Returns:
TODO
- Return type:
TODO
- property serial_number
TODO
- Returns:
TODO
- Return type:
TODO
- property usb_info
TODO
- Returns:
TODO
- Return type:
TODO
Module contents
Submodules
adb_shell.adb_device module
Implement the AdbDevice
class, which can connect to a device and run ADB shell commands.
Contents
- class adb_shell.adb_device.AdbDevice(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 (BaseTransport) – A user-provided transport for communicating with the device; must be an instance of a subclass of
BaseTransport
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 ofBaseTransport
- _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:
- _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
- _clse(adb_info)[source]
Send a
b'CLSE'
message and then read ab'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
- _filesync_flush(adb_info, filesync_info)[source]
Write the data in the buffer up to
filesync_info.send_idx
, then setfilesync_info.send_idx
to 0.- Parameters:
adb_info (_AdbTransactionInfo) – Info and settings for this ADB transaction
filesync_info (_FileSyncTransactionInfo) – Data and storage for this FileSync transaction
- _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 raisedadb_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 isadb_shell.constants.STAT
- Raises:
adb_shell.exceptions.AdbCommandFailureException – Command failed
adb_shell.exceptions.InvalidResponseError – Received response was not in
expected_ids
- _filesync_read_buffered(size, adb_info, filesync_info)[source]
Read
size
bytes 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_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
- _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 notNone
; otherwise, useself._default_transport_timeout_s
- Parameters:
transport_timeout_s (float, None) – The potential transport timeout
- Returns:
transport_timeout_s
if it is notNone
; otherwise,self._default_transport_timeout_s
- Return type:
float
- _okay(adb_info)[source]
Send an
b'OKAY'
mesage.- Parameters:
adb_info (_AdbTransactionInfo) – Info and settings for this ADB transaction
- _open(destination, transport_timeout_s, read_timeout_s, timeout_s)[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()
the response from the device and fill in theadb_info.remote_id
attribute
- Parameters:
destination (bytes) –
b'SERVICE:COMMAND'
transport_timeout_s (float, None) – Timeout in seconds for sending and receiving data, or
None
; seeBaseTransport.bulk_read()
andBaseTransport.bulk_write()
read_timeout_s (float) – The total time in seconds to wait for a
b'CLSE'
orb'OKAY'
command in_AdbIOManager.read()
timeout_s (float, None) – The total time in seconds to wait for the ADB command to finish
- Returns:
adb_info – Info and settings for this ADB transaction
- Return type:
- _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 (_io.BytesIO) – File-like object for writing to
progress_callback (function, None) – Callback method that accepts
device_path
,bytes_written
, andtotal_bytes
adb_info (_AdbTransactionInfo) – Info and settings for this ADB transaction
filesync_info (_FileSyncTransactionInfo) – Data and storage for this FileSync transaction
- _push(stream, device_path, st_mode, mtime, progress_callback, adb_info, filesync_info)[source]
Push a file-like object to the device.
- Parameters:
stream (_io.BytesIO) – 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
, andtotal_bytes
adb_info (_AdbTransactionInfo) – Info and settings for this ADB transaction
- Raises:
PushFailedError – Raised on push failure.
- _read_until(expected_cmds, adb_info)[source]
Read a packet, acknowledging any write packets.
Read data via
_AdbIOManager.read()
If a
b'WRTE'
packet is received, send anb'OKAY'
packet viaAdbDevice._okay()
Return the
cmd
anddata
that were read by_AdbIOManager.read()
- Parameters:
expected_cmds (list[bytes]) –
_AdbIOManager.read()
will look for a packet whose command is inexpected_cmds
adb_info (_AdbTransactionInfo) – Info and settings for this ADB transaction
- Returns:
cmd (bytes) – The command that was received by
_AdbIOManager.read()
, which is inadb_shell.constants.WIRE_TO_ID
and must be inexpected_cmds
data (bytes) – The data that was received by
_AdbIOManager.read()
- _read_until_close(adb_info)[source]
Yield packets until a
b'CLSE'
packet is received.Read the
cmd
anddata
fields from ab'CLSE'
orb'WRTE'
packet viaAdbDevice._read_until()
If
cmd
isb'CLSE'
, then send ab'CLSE'
message and stopYield
data
and repeat
- Parameters:
adb_info (_AdbTransactionInfo) – Info and settings for this ADB transaction
- Yields:
data (bytes) – The data that was read by
AdbDevice._read_until()
- _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
; seeBaseTransport.bulk_read()
andBaseTransport.bulk_write()
read_timeout_s (float) – The total time in seconds to wait for a
b'CLSE'
orb'OKAY'
command in_AdbIOManager.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
- _streaming_command(service, command, transport_timeout_s, read_timeout_s, timeout_s)[source]
One complete set of packets for a single command.
_open()
a new connection to the device, where thedestination
parameter isservice:command
Read 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
transport_timeout_s (float, None) – Timeout in seconds for sending and receiving data, or
None
; seeBaseTransport.bulk_read()
andBaseTransport.bulk_write()
read_timeout_s (float) – The total time in seconds to wait for a
b'CLSE'
orb'OKAY'
command in_AdbIOManager.read()
timeout_s (float, None) – The total time in seconds to wait for the ADB command to finish
- Yields:
bytes – The responses from the service.
- _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
; seeBaseTransport.bulk_read()
andBaseTransport.bulk_write()
read_timeout_s (float) – The total time in seconds to wait for a
b'CLSE'
orb'OKAY'
command in_AdbIOManager.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
- 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.
- Parameters:
rsa_keys (list, None) – A list of signers of type
CryptographySigner
,PycryptodomeAuthSigner
, orPythonRSASigner
transport_timeout_s (float, None) – Timeout in seconds for sending and receiving data, or
None
; seeBaseTransport.bulk_read()
andBaseTransport.bulk_write()
auth_timeout_s (float, None) – The time in seconds to wait for a
b'CNXN'
authentication responseread_timeout_s (float) – The total time in seconds to wait for expected commands in
_AdbIOManager._read_expected_packet_from_device()
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
- 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
; seeBaseTransport.bulk_read()
andBaseTransport.bulk_write()
read_timeout_s (float) – The total time in seconds to wait for a
b'CLSE'
orb'OKAY'
command in_AdbIOManager.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
- 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'
orb'OKAY'
command in_AdbIOManager.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 legacyadb_shell.constants.MAX_PUSH_DATA
- Return type:
int
- 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
, andtotal_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'
orb'OKAY'
command in_AdbIOManager.read()
- 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
, andtotal_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'
orb'OKAY'
command in_AdbIOManager.read()
- 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
; seeBaseTransport.bulk_read()
andBaseTransport.bulk_write()
read_timeout_s (float) – The total time in seconds to wait for a
b'CLSE'
orb'OKAY'
command in_AdbIOManager.read()
timeout_s (float, None) – The total time in seconds to wait for the ADB command to finish
- 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:
transport_timeout_s (float, None) – Timeout in seconds for sending and receiving data, or
None
; seeBaseTransport.bulk_read()
andBaseTransport.bulk_write()
read_timeout_s (float) – The total time in seconds to wait for a
b'CLSE'
orb'OKAY'
command in_AdbIOManager.read()
timeout_s (float, None) – The total time in seconds to wait for the ADB command to finish
- 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
; seeBaseTransport.bulk_read()
andBaseTransport.bulk_write()
read_timeout_s (float) – The total time in seconds to wait for a
b'CLSE'
orb'OKAY'
command in_AdbIOManager.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
- 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'
orb'OKAY'
command in_AdbIOManager.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, 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:
command (str) – The shell command that will be sent
transport_timeout_s (float, None) – Timeout in seconds for sending and receiving data, or
None
; seeBaseTransport.bulk_read()
andBaseTransport.bulk_write()
read_timeout_s (float) – The total time in seconds to wait for a
b'CLSE'
orb'OKAY'
command in_AdbIOManager.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
decode
is True, otherwise as bytes.
- class adb_shell.adb_device.AdbDeviceTcp(host, port=5555, default_transport_timeout_s=None, banner=None)[source]
Bases:
AdbDevice
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:
- class adb_shell.adb_device.AdbDeviceUsb(serial=None, port_path=None, default_transport_timeout_s=None, banner=None)[source]
Bases:
AdbDevice
A class with methods for connecting to a device via USB and executing ADB commands.
- Parameters:
serial (str, None) – The USB device serial ID
port_path (TODO, None) – TODO
default_transport_timeout_s (float, None) – Default timeout in seconds for USB 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 – Raised if package was not installed with the “usb” extras option (
pip install adb-shell[usb]
)
- _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 USB 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:
- class adb_shell.adb_device._AdbIOManager(transport)[source]
Bases:
object
A class for handling all ADB I/O.
Notes
When the
self._store_lock
andself._transport_lock
locks are held at the same time, it must always be the case that theself._transport_lock
is acquired first. This ensures that there is no potential for deadlock.- Parameters:
transport (BaseTransport) – A transport for communicating with the device; must be an instance of a subclass of
BaseTransport
- _packet_store
A store for holding packets that correspond to different ADB streams
- Type:
- _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
BaseTransport
- Type:
- _transport_lock
A lock for protecting
self._transport
- Type:
Lock
- _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
- _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 inexpected_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
- _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 inexpected_cmds
arg0 (int) – TODO
arg1 (int) – TODO
bytes – The data that was read
- Raises:
adb_shell.exceptions.InvalidCommandError – Unknown command
adb_shell.exceptions.InvalidChecksumError – Received checksum does not match the expected checksum
- _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
- close()[source]
Close the connection via the provided transport’s
close()
method and clear the packet store.
- connect(banner, rsa_keys, auth_timeout_s, auth_callback, adb_info)[source]
Establish an ADB connection to the device.
Use the transport to establish a connection
Send a
b'CNXN'
messageRead the response from the device
If
cmd
is notb'AUTH'
, then authentication is not necesary and so we are doneIf no
rsa_keys
are provided, raise an exceptionLoop through our keys, signing the last
banner2
that we receivedIf the last
arg0
was notadb_shell.constants.AUTH_TOKEN
, raise an exceptionSign the last
banner2
and send it in anb'AUTH'
messageRead the response from the device
If
cmd
isb'CNXN'
, we are done
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:
banner (bytearray, bytes) – The hostname of the machine where the Python interpreter is currently running (
adb_shell.adb_device.AdbDevice._banner
)rsa_keys (list, None) – A list of signers of type
CryptographySigner
,PycryptodomeAuthSigner
, orPythonRSASigner
auth_timeout_s (float, None) – The time in seconds to wait for a
b'CNXN'
authentication responseauth_callback (function, None) – Function callback invoked when the connection needs to be accepted on the device
adb_info (_AdbTransactionInfo) – Info and settings for this connection attempt
- Returns:
bool – Whether the connection was established
maxdata (int) – Maximum amount of data in an ADB packet
- Raises:
adb_shell.exceptions.DeviceAuthError – Device authentication required, no keys available
adb_shell.exceptions.InvalidResponseError – Invalid auth response from the device
- read(expected_cmds, adb_info, allow_zeros=False)[source]
Read packets from the device until we get an expected packet type.
See if the expected packet is in the packet store
While the time limit has not been exceeded:
See if the expected packet is in the packet store
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.
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
andarg1
values to match with 0, in addition toadb_info.remote_id
andadb_info.local_id
, respectively
- Returns:
cmd (bytes) – The received command, which is in
adb_shell.constants.WIRE_TO_ID
and must be inexpected_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
- send(msg, adb_info)[source]
Send a message to the device.
- Parameters:
msg (AdbMessage) – The data that will be sent
adb_info (_AdbTransactionInfo) – Info and settings for this ADB transaction
- adb_shell.adb_device._open_bytesio(stream, *args, **kwargs)[source]
A 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:
stream (BytesIO) – The stream input parameter
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 ofBaseTransportAsync
- _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:
- _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:
- async _clse(adb_info)[source]
Send a
b'CLSE'
message and then read ab'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 setfilesync_info.send_idx
to 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)[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
- 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 isadb_shell.constants.STAT
- 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
size
bytes 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
- 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 raisedfinish_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 notNone
; otherwise, useself._default_transport_timeout_s
- Parameters:
transport_timeout_s (float, None) – The potential transport timeout
- Returns:
transport_timeout_s
if it is notNone
; 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.send()
anb'OPEN'
command to the device that specifies thelocal_id
read()
the response from the device and fill in theadb_info.remote_id
attribute
- Parameters:
destination (bytes) –
b'SERVICE:COMMAND'
transport_timeout_s (float, None) – Timeout in seconds for sending and receiving data, or
None
; seeBaseTransportAsync.bulk_read()
andBaseTransportAsync.bulk_write()
read_timeout_s (float) – The total time in seconds to wait for a
b'CLSE'
orb'OKAY'
command in_AdbIOManagerAsync.read()
timeout_s (float, None) – The total time in seconds to wait for the ADB command to finish
- Returns:
adb_info – Info and settings for this ADB transaction
- Return type:
- 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
, andtotal_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
, andtotal_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.
Read data via
_AdbIOManagerAsync.read()
If a
b'WRTE'
packet is received, send anb'OKAY'
packet viaAdbDeviceAsync._okay()
Return the
cmd
anddata
that were read by_AdbIOManagerAsync.read()
- Parameters:
expected_cmds (list[bytes]) –
_AdbIOManagerAsync.read()
will look for a packet whose command is inexpected_cmds
adb_info (_AdbTransactionInfo) – Info and settings for this ADB transaction
- Returns:
cmd (bytes) – The command that was received by
_AdbIOManagerAsync.read()
, which is inadb_shell.constants.WIRE_TO_ID
and must be inexpected_cmds
data (bytes) – The data that was received by
_AdbIOManagerAsync.read()
- async _read_until_close(adb_info)[source]
Yield packets until a
b'CLSE'
packet is received.Read the
cmd
anddata
fields from ab'CLSE'
orb'WRTE'
packet viaAdbDeviceAsync._read_until()
If
cmd
isb'CLSE'
, then send ab'CLSE'
message and stopYield
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
; seeBaseTransportAsync.bulk_read()
andBaseTransportAsync.bulk_write()
read_timeout_s (float) – The total time in seconds to wait for a
b'CLSE'
orb'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.
_open()
a new connection to the device, where thedestination
parameter isservice:command
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:
service (bytes) – The ADB service (e.g.,
b'shell'
, as used byAdbDeviceAsync.shell()
)command (bytes) – The service command
transport_timeout_s (float, None) – Timeout in seconds for sending and receiving data, or
None
; seeBaseTransportAsync.bulk_read()
andBaseTransportAsync.bulk_write()
read_timeout_s (float) – The total time in seconds to wait for a
b'CLSE'
orb'OKAY'
command in_AdbIOManagerAsync.read()
timeout_s (float, None) – The total time in seconds to wait for the ADB command to finish
- 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
; seeBaseTransportAsync.bulk_read()
andBaseTransportAsync.bulk_write()
read_timeout_s (float) – The total time in seconds to wait for a
b'CLSE'
orb'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 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:
rsa_keys (list, None) – A list of signers of type
CryptographySigner
,PycryptodomeAuthSigner
, orPythonRSASigner
transport_timeout_s (float, None) – Timeout in seconds for sending and receiving data, or
None
; seeBaseTransportAsync.bulk_read()
andBaseTransportAsync.bulk_write()
auth_timeout_s (float, None) – The time in seconds to wait for a
b'CNXN'
authentication responseread_timeout_s (float) – The total time in seconds to wait for expected commands in
_AdbIOManagerAsync._read_expected_packet_from_device()
auth_callback (function, None) – Function callback invoked when the connection needs to be accepted on the device
- 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
; seeBaseTransportAsync.bulk_read()
andBaseTransportAsync.bulk_write()
read_timeout_s (float) – The total time in seconds to wait for a
b'CLSE'
orb'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'
orb'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 legacyadb_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
, andtotal_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'
orb'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
, andtotal_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'
orb'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
; seeBaseTransportAsync.bulk_read()
andBaseTransportAsync.bulk_write()
read_timeout_s (float) – The total time in seconds to wait for a
b'CLSE'
orb'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:
transport_timeout_s (float, None) – Timeout in seconds for sending and receiving data, or
None
; seeBaseTransportAsync.bulk_read()
andBaseTransportAsync.bulk_write()
read_timeout_s (float) – The total time in seconds to wait for a
b'CLSE'
orb'OKAY'
command in_AdbIOManagerAsync.read()
timeout_s (float, None) – The total time in seconds to wait for the ADB command to finish
- 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
; seeBaseTransportAsync.bulk_read()
andBaseTransportAsync.bulk_write()
read_timeout_s (float) – The total time in seconds to wait for a
b'CLSE'
orb'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'
orb'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:
command (str) – The shell command that will be sent
transport_timeout_s (float, None) – Timeout in seconds for sending and receiving data, or
None
; seeBaseTransportAsync.bulk_read()
andBaseTransportAsync.bulk_write()
read_timeout_s (float) – The total time in seconds to wait for a
b'CLSE'
orb'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 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:
- 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
andself._transport_lock
locks are held at the same time, it must always be the case that theself._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:
- _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:
- _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 inexpected_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 inexpected_cmds
arg0 (int) – TODO
arg1 (int) – TODO
bytes – The data that was read
- Raises:
adb_shell.exceptions.InvalidCommandError – Unknown command
adb_shell.exceptions.InvalidChecksumError – Received checksum does not match the expected checksum
- 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 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.
Use the transport to establish a connection
Send a
b'CNXN'
messageRead the response from the device
If
cmd
is notb'AUTH'
, then authentication is not necesary and so we are doneIf no
rsa_keys
are provided, raise an exceptionLoop through our keys, signing the last
banner2
that we receivedIf the last
arg0
was notadb_shell.constants.AUTH_TOKEN
, raise an exceptionSign the last
banner2
and send it in anb'AUTH'
messageRead the response from the device
If
cmd
isb'CNXN'
, we are done
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:
banner (bytearray, bytes) – The hostname of the machine where the Python interpreter is currently running (
adb_shell.adb_device_async.AdbDeviceAsync._banner
)rsa_keys (list, None) – A list of signers of type
CryptographySigner
,PycryptodomeAuthSigner
, orPythonRSASigner
auth_timeout_s (float, None) – The time in seconds to wait for a
b'CNXN'
authentication responseauth_callback (function, None) – Function callback invoked when the connection needs to be accepted on the device
adb_info (_AdbTransactionInfo) – Info and settings for this connection attempt
- Returns:
bool – Whether the connection was established
maxdata (int) – Maximum amount of data in an ADB packet
- Raises:
adb_shell.exceptions.DeviceAuthError – Device authentication required, no keys available
adb_shell.exceptions.InvalidResponseError – Invalid auth response from the device
- async read(expected_cmds, adb_info, allow_zeros=False)[source]
Read packets from the device until we get an expected packet type.
See if the expected packet is in the packet store
While the time limit has not been exceeded:
See if the expected packet is in the packet store
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.
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
andarg1
values to match with 0, in addition toadb_info.remote_id
andadb_info.local_id
, respectively
- Returns:
cmd (bytes) – The received command, which is in
adb_shell.constants.WIRE_TO_ID
and must be inexpected_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:
msg (AdbMessage) – The data that will be sent
adb_info (_AdbTransactionInfo) – Info and settings for this ADB transaction
- 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
- 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
adb_shell.adb_message module
Functions and an AdbMessage
class for packing and unpacking ADB messages.
Contents
- class adb_shell.adb_message.AdbMessage(command, arg0, arg1, data=b'')[source]
Bases:
object
A helper class for packing ADB messages.
- Parameters:
command (bytes) – A command; examples used in this package include
adb_shell.constants.AUTH
,adb_shell.constants.CNXN
,adb_shell.constants.CLSE
,adb_shell.constants.OPEN
, andadb_shell.constants.OKAY
arg0 (int) – Usually the local ID, but
connect()
andconnect()
provideadb_shell.constants.VERSION
,adb_shell.constants.AUTH_SIGNATURE
, andadb_shell.constants.AUTH_RSAPUBLICKEY
arg1 (int) – Usually the remote ID, but
connect()
andconnect()
provideadb_shell.constants.MAX_ADB_DATA
data (bytes) – The data that will be sent
- arg0
Usually the local ID, but
connect()
andconnect()
provideadb_shell.constants.VERSION
,adb_shell.constants.AUTH_SIGNATURE
, andadb_shell.constants.AUTH_RSAPUBLICKEY
- Type:
int
- arg1
Usually the remote ID, but
connect()
andconnect()
provideadb_shell.constants.MAX_ADB_DATA
- Type:
int
- command
The input parameter
command
converted to an integer viaadb_shell.constants.ID_TO_WIRE
- Type:
int
- data
The data that will be sent
- Type:
bytes
- magic
self.command
with its bits flipped; in other words,self.command + self.magic == 2**32 - 1
- Type:
int
- property checksum
Return
checksum(self.data)
- Returns:
The checksum of
self.data
- Return type:
int
- adb_shell.adb_message.checksum(data)[source]
Calculate the checksum of the provided data.
- Parameters:
data (bytearray, bytes, str) – The data
- Returns:
The checksum
- Return type:
int
- adb_shell.adb_message.int_to_cmd(n)[source]
Convert from an integer (4 bytes) to an ADB command.
- Parameters:
n (int) – The integer that will be converted to an ADB command
- Returns:
The ADB command (e.g.,
'CNXN'
)- Return type:
str
- adb_shell.adb_message.unpack(message)[source]
Unpack a received ADB message.
- Parameters:
message (bytes) – The received message
- Returns:
cmd (int) – The ADB command
arg0 (int) – TODO
arg1 (int) – TODO
data_length (int) – The length of the message’s data
data_checksum (int) – The checksum of the message’s data
- Raises:
ValueError – Unable to unpack the ADB command.
adb_shell.constants module
Constants used throughout the code.
- adb_shell.constants.AUTH_RSAPUBLICKEY = 3
AUTH constant for
arg0
- adb_shell.constants.AUTH_SIGNATURE = 2
AUTH constant for
arg0
- adb_shell.constants.AUTH_TOKEN = 1
AUTH constant for
arg0
- adb_shell.constants.CLASS = 255
From adb.h
- adb_shell.constants.DEFAULT_AUTH_TIMEOUT_S = 10.0
Default authentication timeout (in s) for
adb_shell.adb_device.AdbDevice.connect()
andadb_shell.adb_device_async.AdbDeviceAsync.connect()
- adb_shell.constants.DEFAULT_PUSH_MODE = 33272
Default mode for pushed files.
- adb_shell.constants.DEFAULT_READ_TIMEOUT_S = 10.0
Default total timeout (in s) for reading data from the device
- adb_shell.constants.FILESYNC_IDS = (b'DATA', b'DENT', b'DONE', b'FAIL', b'LIST', b'OKAY', b'QUIT', b'RECV', b'SEND', b'STAT')
Commands that are recognized by
adb_shell.adb_device.AdbDevice._filesync_read()
andadb_shell.adb_device_async.AdbDeviceAsync._filesync_read()
- adb_shell.constants.FILESYNC_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}
A dictionary where the keys are the commands in
FILESYNC_IDS
and the values are the keys converted to integers
- adb_shell.constants.FILESYNC_LIST_FORMAT = b'<5I'
The format for FileSync “list” messages
- adb_shell.constants.FILESYNC_PULL_FORMAT = b'<2I'
The format for FileSync “pull” messages
- adb_shell.constants.FILESYNC_PUSH_FORMAT = b'<2I'
The format for FileSync “push” messages
- adb_shell.constants.FILESYNC_STAT_FORMAT = b'<4I'
The format for FileSync “stat” messages
- adb_shell.constants.FILESYNC_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'}
A dictionary where the keys are integers and the values are their corresponding commands (type = bytes) from
FILESYNC_IDS
- adb_shell.constants.IDS = (b'AUTH', b'CLSE', b'CNXN', b'OKAY', b'OPEN', b'SYNC', b'WRTE')
Commands that are recognized by
adb_shell.adb_device._AdbIOManager._read_packet_from_device()
andadb_shell.adb_device_async._AdbIOManagerAsync._read_packet_from_device()
- adb_shell.constants.ID_TO_WIRE = {b'AUTH': 1213486401, b'CLSE': 1163086915, b'CNXN': 1314410051, b'OKAY': 1497451343, b'OPEN': 1313165391, b'SYNC': 1129208147, b'WRTE': 1163154007}
A dictionary where the keys are the commands in
IDS
and the values are the keys converted to integers
- adb_shell.constants.MAX_ADB_DATA = 1048576
//android.googlesource.com/platform/system/core/+/master/adb/adb.h
- Type:
Maximum amount of data in an ADB packet. According to
- Type:
https
- adb_shell.constants.MAX_CHUNK_SIZE = 65536
//android.googlesource.com/platform/system/core/+/master/adb/SYNC.TXT
- Type:
Maximum chunk size. According to https
- adb_shell.constants.MAX_PUSH_DATA = 2048
Maximum size of a filesync DATA packet. Default size.
- adb_shell.constants.MESSAGE_FORMAT = b'<6I'
An ADB message is 6 words in little-endian.
- adb_shell.constants.MESSAGE_SIZE = 24
The size of an ADB message
- adb_shell.constants.PROTOCOL = 1
From adb.h
- adb_shell.constants.SUBCLASS = 66
From adb.h
- adb_shell.constants.VERSION = 16777216
ADB protocol version.
adb_shell.exceptions module
ADB-related exceptions.
- exception adb_shell.exceptions.AdbCommandFailureException[source]
Bases:
Exception
A
b'FAIL'
packet was received.
- exception adb_shell.exceptions.AdbConnectionError[source]
Bases:
Exception
ADB command not sent because a connection to the device has not been established.
- exception adb_shell.exceptions.AdbTimeoutError[source]
Bases:
Exception
ADB command did not complete within the specified time.
- exception adb_shell.exceptions.DeviceAuthError(message, *args)[source]
Bases:
Exception
Device authentication failed.
- exception adb_shell.exceptions.DevicePathInvalidError[source]
Bases:
Exception
A file command was passed an invalid path.
- exception adb_shell.exceptions.InvalidChecksumError[source]
Bases:
Exception
Checksum of data didn’t match expected checksum.
- exception adb_shell.exceptions.InvalidCommandError[source]
Bases:
Exception
Got an invalid command.
- exception adb_shell.exceptions.InvalidResponseError[source]
Bases:
Exception
Got an invalid response to our command.
- exception adb_shell.exceptions.InvalidTransportError[source]
Bases:
Exception
The provided transport does not implement the necessary methods:
close
,connect
,bulk_read
, andbulk_write
.
- exception adb_shell.exceptions.PushFailedError[source]
Bases:
Exception
Pushing a file failed for some reason.
- exception adb_shell.exceptions.TcpTimeoutException[source]
Bases:
Exception
TCP connection timed read/write operation exceeded the allowed time.
- exception adb_shell.exceptions.UsbReadFailedError(msg, usb_error)[source]
Bases:
Exception
TODO
- 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_shell.exceptions.UsbWriteFailedError[source]
Bases:
Exception
adb_shell.transport.usb_transport.UsbTransport.bulk_write()
failed.
Module contents
ADB shell functionality.
Prebuilt wheel can be downloaded from nightly.link.
This Python package implements ADB shell and FileSync functionality. It originated from python-adb.
Installation
pip install adb-shell
Async
To utilize the async version of this code, you must install into a Python 3.7+ environment via:
pip install adb-shell[async]
USB Support (Experimental)
To connect to a device via USB, install this package via:
pip install adb-shell[usb]
Example Usage
(Based on androidtv/adb_manager.py)
from adb_shell.adb_device import AdbDeviceTcp, AdbDeviceUsb
from adb_shell.auth.sign_pythonrsa import PythonRSASigner
# Load the public and private keys
adbkey = 'path/to/adbkey'
with open(adbkey) as f:
priv = f.read()
with open(adbkey + '.pub') as f:
pub = f.read()
signer = PythonRSASigner(pub, priv)
# Connect
device1 = AdbDeviceTcp('192.168.0.222', 5555, default_transport_timeout_s=9.)
device1.connect(rsa_keys=[signer], auth_timeout_s=0.1)
# Connect via USB (package must be installed via `pip install adb-shell[usb])`
device2 = AdbDeviceUsb()
device2.connect(rsa_keys=[signer], auth_timeout_s=0.1)
# Send a shell command
response1 = device1.shell('echo TEST1')
response2 = device2.shell('echo TEST2')
Generate ADB Key Files
If you need to generate a key, you can do so as follows.
from adb_shell.auth.keygen import keygen
keygen('path/to/adbkey')