swind / pure-python-adb Goto Github PK
View Code? Open in Web Editor NEWThis is pure-python implementation of the ADB client.
License: MIT License
This is pure-python implementation of the ADB client.
License: MIT License
Hi,
By default, your module is modifying default logging output. Is it possible to document the behaviour and/or to disable logging capabilities in your module?
Sample code:
#!/usr/bin/env python3
import logging
from colorlog import ColoredFormatter
from adb.client import Client as AdbClient
# create logger
mylogger = logging.getLogger(__name__)
mylogger.setLevel(logging.DEBUG)
# create console handler and set level to INFO
ch=logging.StreamHandler()
ch.setLevel(logging.DEBUG)
# create formatter
formatter = ColoredFormatter(" %(log_color)s%(levelname)-8s%(reset)s | %(log_color)s%(message)s%(reset)s")
ch.setFormatter(formatter)
mylogger.addHandler(ch)
mylogger.debug('blu')
mylogger.info('blu')
mylogger.warning('blu')
mylogger.error('blu')
hi:
The pure python adb library is very useful for me. But I met a strange issue:
I have a PC (named PCA), the PC connects 2 Android devices and the PC uses windows 7.
I installed the pure python adb library on the PC and use it to execute some adb shell command on addroid devices. It works fine.
I have another PC (named PCB), it uses centos 7 and also have installed the pure python adb library. For some reason, I wish to access the andirod devices of PCA from PCB. I know the adb only listen on 127.0.0.1 5037 of PCA, and I could not connect to PCA with pure-python-adb;
So I installed a softeware on PCA that will do port forward, for example: the PCA's ip address is 10.69.67.139, so I set in the port forword software, use it to forward any ip packet to 10.69.67.130:5036 to 127.0.0.1:5037, this time, I can use pure-python-adb to connect to 19.69.67.139:5036. It also works.
My issue is: sometimes the pure-python-adb will broken for connection reset by peer. I means sometimes means: sometimes it is ok, but sometimes it fails; even I execute the same shell command.
the error log is something like this:
01-02-2019:09:15:43,231 DEBUG [connection.py:24] Connect to adb server - 10.69.67.139:5036
2019-02-01 09:15:43 [DEBUG] Connect to adb server - 10.69.67.139:5036
01-02-2019:09:15:43,232 DEBUG [connection.py:75] 000Chost:devices
2019-02-01 09:15:43 [DEBUG] 000Chost:devices
01-02-2019:09:15:43,234 DEBUG [connection.py:47] Connection closed...
2019-02-01 09:15:43 [DEBUG] Connection closed...
2019-02-01 09:15:43 [ INFO] shell: ifconfig
01-02-2019:09:15:43,235 DEBUG [connection.py:24] Connect to adb server - 10.69.67.139:5036
2019-02-01 09:15:43 [DEBUG] Connect to adb server - 10.69.67.139:5036
01-02-2019:09:15:43,235 DEBUG [connection.py:24] Connect to adb server - 10.69.67.139:5036
2019-02-01 09:15:43 [DEBUG] Connect to adb server - 10.69.67.139:5036
01-02-2019:09:15:43,236 DEBUG [connection.py:75] 001Fhost:transport:5LM0216922003133
2019-02-01 09:15:43 [DEBUG] 001Fhost:transport:5LM0216922003133
Exception in thread Thread-1:
Traceback (most recent call last):
File "/usr/lib64/python2.7/threading.py", line 811, in __bootstrap_inner
self.run()
File "/usr/lib64/python2.7/threading.py", line 764, in run
self.__target(*self.__args, **self.__kwargs)
File "adb_proxy.py", line 140, in run
self.deal_message(message, address)
File "adb_proxy.py", line 128, in deal_message
response = self.tc.dealwith_direct_operation(data)
File "adb_proxy.py", line 83, in dealwith_direct_operation
return self._run_shell_command(device, command)
File "adb_proxy.py", line 67, in _run_shell_command
device.shell('{}'.format(command)))
File "/usr/lib/python2.7/site-packages/adb/command/transport/init.py", line 20, in shell
conn = self.create_connection(timeout=timeout)
File "/usr/lib/python2.7/site-packages/adb/device.py", line 45, in create_connection
self.transport(conn)
File "/usr/lib/python2.7/site-packages/adb/command/transport/init.py", line 15, in transport
connection.send(cmd)
File "/usr/lib/python2.7/site-packages/adb/connection.py", line 77, in send
return self._check_status()
File "/usr/lib/python2.7/site-packages/adb/connection.py", line 80, in _check_status
recv = self._recv(4).decode('utf-8')
File "/usr/lib/python2.7/site-packages/adb/connection.py", line 56, in _recv
return self.socket.recv(length)
error: [Errno 104] Connection reset by peer
Thanks in advance.
Hi guys,
I am a learner of python-abd, and I want to know whether this support concurrent operations at the same time, for example, whether two input_swipe() operations are allowed to run in two separate processes, like human can use two fingers to swipe in two regions simultaneously.
Any idea or answer will be appreciated!
I try to read the logcat lines from the open connection following the example. Using connection.read(1024) read the number of characters but it is possible to read the logcat by lines?
Thanks.
Hi,
The ADB device is connected to a remote host, therefore I'm setting up the client like this:
from ppadb.client import Client as AdbClient
client = AdbClient(host='remote_host', port=5037)
device = client.devices()[0]
Now, in /data/local/tmp
I'm putting a file of varying size, e.g.:
cd /data/local/tmp
head -c 1024 /dev/urandom > output.z # 1k file
head -c $((1024*64)) /dev/urandom > output.z # 64k file
head -c $((1024*1024)) /dev/urandom > output.z # 1MB file
Then try to pull it:
device.pull('/data/local/tmp/output.z', 'output.z')
this works fine if the file is under 1024kB, i.e. 1024*1024 bytes. Then, if the file is at least 1MB, most of the calls to pull
stall and the interpreter is locked down, i.e. it can't be terminated by Ctrl-C
, because it's stuck at socket.recv
. When I add a timeout, it times out at the last call to self.socket.recv
in Connection._recv
, i.e. it always times out at receiving the last part of the file.
I'm running ADB server version 29.0.1-5644136, the code is executed from Windows using Python 3.7.4.
I am using your package to work on my project github.com/YuvrajRaghuvanshiS/Whatsapp-Key-Database-Extractor and replacing traditional ADB with ppadb however sometimes when I stop process in the middle it does not close process on it's own neither it does on re-run and I get stuck with
RuntimeError: ERROR: connecting to 127.0.0.1:5037 [WinError 10061] No connection could be made because the target machine actively refused it.
Is adb running on your computer?
I'm uploading screenshot. Please let me know what am I missing because I could not seem to find an answer.
Any chance of adding async support or creating an async version of this package?
I have found it useful to implement:
-extend Device so that host:devices can pass back the device status, rather than just the serialno (two separate suggestions, the device status (2nd tuple of the "adb devices" parse) to let me know if a connection is: device, offline, no (permissions), ... Then I can know if I could make a connection to the device.
The implementation of host:track-devices is essentially a change in the command string from the existing shell implementation, moved into init.py in adb/command/host. It opens the socket with "host:track-devices" command and provides a socket to listen to messages when a the transport list changes (device connection is made).
It would be nice to have a message one when the device goes offline, but that does not seem to be the adbd service implementation on either my Mint or Pi implementations. There is nothing that pure-python-adb can do about that.
The format of the message(s) appears to be:
####serialno\tstatus\n
where:
So with this added facility you can find out when devices come online, and will find out devices that have gone offline (when something new comes online).
When using bash terminal on MacOs, I don't have any issue with adb commands; however when using AdbClient in Python 3.7, the 'cd' command does not work, for example: device.shell('cd /system/bin') simple returns ''. Other common commands like ls -la, cp, chmod, etc all work fine in device.shell(). For such a common command as 'cd', I'm wondering if I am missing something?
I've searched extensively on StackOV and others but I found nothing in this regard. Any guidance is much appreciated.
I'm using version 0.3.0.dev0
Hi,
Love the library. Super easy to use. Could we get support for 'adb bugreport <zip_file>' added? I can use 'adb shell bugreport' with this library but thats deprecated. Seems like the 'device' class is where that needs to be at.
Thx!
-Dave
不能从手机上 pull 文件夹 到 host上的文件夹, 比如:
adb pull "/sdcard/folder" "/folder_on_host"
这样的命令在shell里面是可以执行的
I can't figure out how to get the device number? I can get it in android studio's terminal with adb devices. And I can paste it into your example code, for instance:
from adb.client import Client as AdbClient
client = AdbClient(host="127.0.0.1", port=5037)
device = client.device("here I entered my device number")
device.push("c:\python36\scripts\d123.txt", "/sdcard/Download/d123.txt")
Should I be able to get the device number?
Thanks you, Steve
Thanks for your awesome project.
My cell phone is Motorola Z (XT1650-05 / Android 8.0.0 / System OCC27.102-23), it will throw error "[[INSTALL_FAILED_TEST_ONLY: installPackageLI]]". Install commands as below:
adb push app-debug.apk /data/local/tmp
adb shell pm install -t -r /data/local/tmp/app-debug.apk
I found it's a OS BUG from Lenovo BBS, and the offical solution is:
adb install -t -r app-debug.apk
I found some adb commands (eg:logcat) do not implement in this project, and I wonder maybe "logcat" is same as "install", can you share some advice?
BR
File "/usr/lib/python2.7/site-packages/adb/device.py", line 77, in install
self.push(path, dest)
File "/usr/lib/python2.7/site-packages/adb/device.py", line 53, in push
sync_conn = self.sync()
File "/usr/lib/python2.7/site-packages/adb/command/transport/init.py", line 36, in sync
conn.send(cmd)
File "/usr/lib/python2.7/site-packages/adb/connection.py", line 77, in send
return self._check_status()
File "/usr/lib/python2.7/site-packages/adb/connection.py", line 83, in _check_status
raise RuntimeError("ERROR: {} {}".format(repr(recv), error))
RuntimeError: ERROR: u''
The program often reports this error when I was installing a app. But I have no problem using the ADB command。 Is there a problem with the synchronization module? thanks.
The push
method from the Device
class has an small bug when pushing folders recursively. This is the structure of the folder I want to push:
/home/israel/resource
├── dtd
│ └── test1.dtd
└── xml
├── test1.xml
├── test2.xml
├── testAttrEnvVar.xml
└── testEnvVar.xml
This is how I'm calling the method:
device.push("/home/israel/resource", "/sdcard")
The previous situations raises:
RuntimeError: ERROR: 'FAIL' +
The cause is located in this loop:
for root, dirs, files in os.walk(src):
root_dir_path = os.path.join(basename, root.replace(src, ""))
First iteration:
src = /tmp/tmp0s3s470s/rtixmlTester/resource
basename = resource
root = /tmp/tmp0s3s470s/rtixmlTester/resource
root_dir_path = resource/
Second iteration:
src = /tmp/tmp0s3s470s/rtixmlTester/resource
basename = resource
root = /tmp/tmp0s3s470s/rtixmlTester/resource/xml
root_dir_path = /xml
The value for root_dir_path
is wrong and should be resource/xml
.
A "quick" fix is to just add /
to the end of the src
parameter:
device.push("/home/israel/resource/", "/sdcard")
Hi! I am trying to work with two phones simultaneously but they have equal serial numbers. However their transport id or usb-ports differ. When I try to connect to this devices with serial number with the following code I obviously obtain an error:
os.system('adb start-server')
client = AdbClient(host="127.0.0.1", port=5037)
device = client.device("0123456789ABCDEF")
device.shell("echo hello world !")
RuntimeError: ERROR: 'FAIL' 0014more than one device
I know that in bash I can specify a particular device with transport id, but I do not understand how to do this in Python. Can you help me deal with this issue?
When we push an audio file normally (using Cygwin terminal) there's a progress % that gets printed every 50 milliseconds on the shell's stdout. Was wondering how can I get that stdout as a string until it is finished?
devices = self.adb_client.devices()
if devices:
device = devices[0]
self.status_message('Pushing audio file......')
device.push('audio/SRV.wav', '/sdcard/music/srv.wav')
while True:
with self.adb_client.create_connection() as conn:
result = conn.receive()
print(result)
Maybe this is ADB bug. but python code should check it for now.
SEND: host-serial:AABBCC:list-forward
Will also get other forwards which serial not "AABBCC"
Hello,
First of all thank you for your lib is so helpful.
However, I'm having a tiny issue when I attempt to launch a process as :
device.shell("/system/bin/sh"). My code is then blocked.
Any help ?
Hey,
is it possible to add support for adb command emu
? Like for example if you want to find out your avd name via adb emu avd name
?
Thanks in advance!
你好~
很高兴终于有人打算做这个东西了,看起来确实很不错
近期我也在做一个类似的东西 pyatool,主要为了解决在开发中频繁使用恶心的subprocess的问题;
想问一下,是否考虑支持让用户自定义函数?类似:
def download_and_install(url, toolkit=None):
resp = requests.get(url)
if not resp.ok:
return False
with tempfile.NamedTemporaryFile('wb+', suffix='.apk', delete=False) as temp:
temp.write(resp.content)
temp.close()
toolkit.adb.run(['install', '-r', '-d', '-t', temp.name])
os.remove(temp.name)
return True
PYAToolkit.bind_func(real_func=download_and_install)
# and
device_toolkit = PYAToolkit('123456F')
device_toolkit.download_and_install()
似乎能覆盖更多的场景 :)
另外,如果导入方式是:
from adb.client import Client as AdbClient
会与google提供的python-adb冲突~
The Android ADB impl has ReportProgress to report progress during file transfer.
I'm proposing a new argument progress
in Sync.push(), similar to scp, allowing users to pass a callback and e.g. print progress on screen.
Is there a way to fix when calling "su" with device.shell() method? I am noticing when I call that command to assume root, that the rest of the script does not execute.
I imagine one workaround would just to perform "su [rest of command]" so it returns the command output, but being able to just perform "su" to take over as root for the rest of commands is beneficial for modularization, in my case at least.
*Update: calling "su echo hello world" for example actually did not work. I have a handler assigned to these shell calls, and issuing the "su" does output that I correctly assumed root, but no further commands issue and the script just hangs, as if it's waiting...
The pull()
function does not support pulling directories:
# ... omitted
dev.pull("/sdcard/Download/com.mwr.dz_2019.10.27_11.45.28", "com.mwr.dz_2019.10.27_11.45.28")
Out[10]: 'read failed: Is a directory'
It would be nice if this gets added.
I have Python 3.7.3 64bit.
I have installed pure-python-adb-0.2.6.dev0.
Adb server is running on android-emulator.
I can connect successfully using adb.exe
But using following code :
from ppadb.client import Client
adb = Client(host='127.0.0.1', port=62001)
devices=adb.devices()
The Program seems to stuck at adb.devices()
if i want to execute "su" and "ps -A"
what should I do
Thanks for ppadb! So far it has been very useful.
I noticed ppadb install a package called tools
into site_packages
.
It's a minor thing, but perhaps rename it to something less generic / common?
In our use case, it was causing conflicts with a project-local module called tools
.
> Traceback (most recent call last):
> File "<stdin>", line 1, in <module>
> File "C:\Users\x\AppData\Local\Programs\Python\Python38-32\lib\site-packages\ppadb\command\host\__init__.py", line 23, in devices
> result = self._execute_cmd(cmd)
> File "C:\Users\x\AppData\Local\Programs\Python\Python38-32\lib\site-packages\ppadb\command\host\__init__.py", line 14, in _execute_cmd
> conn.send(cmd)
> File "C:\Users\x\AppData\Local\Programs\Python\Python38-32\lib\site-packages\ppadb\connection.py", line 77, in send
> return self._check_status()
> File "C:\Users\x\AppData\Local\Programs\Python\Python38-32\lib\site-packages\ppadb\connection.py", line 83, in _check_status
> raise RuntimeError("ERROR: {} {}".format(repr(recv), error))
> RuntimeError: ERROR: 'Andr' oid Console: type 'help' for a list of commands
> OK
I have an android emulator running on port 5554.
You can see the device returns OK
but ppadb still returns an error.
I am very new to ADB and Android development. But I do work abit with python. I really apprecitae that this library can do all the stuff in single python script. However, I was getting this error:
devices = client.devices()
File "/home/rrr/.local/lib/python2.7/site-packages/ppadb/command/host/__init__.py", line 23, in devices
result = self._execute_cmd(cmd)
File "/home/rrr/.local/lib/python2.7/site-packages/ppadb/command/host/__init__.py", line 13, in _execute_cmd
with self.create_connection() as conn:
File "/home/rrr/.local/lib/python2.7/site-packages/ppadb/client.py", line 14, in create_connection
conn.connect()
File "/home/rrr/.local/lib/python2.7/site-packages/ppadb/connection.py", line 41, in connect
e
RuntimeError: ERROR: connecting to 127.0.0.1:5037 [Errno 111] Connection refused.
Is adb running on your computer?
And it took me pretty long time to find out how to fix it. Plus, I do not like the fact, that there is nothing about adb server starting on your machine in examples and at all in README.
Is it possible to add method, that we can call for starting adb server?
To make it like this:
client = AdbClient(host="127.0.0.1", port=5037)
if ppadb.adb_server_not_running():
ppadb.start_adb_server()
devices = client.devices()
I am pretty sure, many people starting with ADB would really apprecitae this.
It is possible for adbd to respond with more than two tokens on the devices line, such as:
???????? no permission
If this occurs the current split of:
serial, _ = line.split()
finds too many list elements and takes a fault.
If the line is changed to:
tuples = line.split()
serial = tuples[0] # grab the serialno tuple
We only need to look for the serial tuple and don't care how many others are there.
When run testcases, warning like this always show
C:\Python36\lib\site-packages\adb\connection.py:26: ResourceWarning: unclosed <socket.socket fd=656, family=AddressFamil
y.AF_INET, type=SocketKind.SOCK_STREAM, proto=0, laddr=('127.0.0.1', 52097), raddr=('127.0.0.1', 5037)>
Within sync/__init__.py file streams are never closed which generates a warning within a CentOS VM. To prevent this warning from occurring line 30 and 56 should be modified using with open(src/dest, 'rb'/'wb') as stream:
followed by indenting corresponding code.
output:
AttributeError: 'NoneType' object has no attribute 'forward'
screencap truncated in game“王者荣耀” https://pvp.qq.com/
https://gitee.com/DaveBoy/Pics/raw/master/Typora%E5%9B%BE%E5%BA%8A/screen.png
Hello;
On linux, adb push will preserve the file modify and access time, per example below:
$ adb push doc1.pdf /sdcard/Documents/sync-2
4331 KB/s (298200 bytes in 0.067s)
$ adb shell stat /sdcard/Documents/sync-2/doc1.pdf
File: `/sdcard/Documents/sync-2/doc1.pdf'
Size: 298200 Blocks: 584 IO Blocks: 512 regular file
Device: 15h/21d Inode: 1344393 Links: 1
Access: (660/-rw-rw----) Uid: ( 0/ root) Gid: ( 1015/sdcard_rw)
Access: 2018-04-27 04:30:18.000000000
Modify: 2018-04-27 04:30:18.000000000
Change: 2018-12-30 13:21:16.527000210
But calling device.push() will not, it resets all time stamps to the copy time. Here is the same file but copied to android using device.push():
File: `/sdcard/Documents/sync-2/doc1.pdf'
Size: 298200 Blocks: 584 IO Blocks: 512 regular file
Device: 15h/21d Inode: 1344394 Links: 1
Access: (660/-rw-rw----) Uid: ( 0/ root) Gid: ( 1015/sdcard_rw)
Access: 2018-12-30 13:26:13.000000000
Modify: 2018-12-30 13:26:13.000000000
Change: 2018-12-30 13:26:11.077000227
I think this is an important bug to fix IMHO, as it prevents writing code to sync files between an android device and a desktop.
Thank you.
Currently when sending an adb reverse command, an error occurs:
RuntimeError: ERROR: 'FAIL' 0016malformed forward spec
After digging into the code and the adb source code, it turns out that there's a small typo in the command:
This should be: reverse:forward:{remote};{local}
, note the last :
which should be ;
. See:
Google's adb package also uses the name adb
, and so these packages can't be used together. To get around this for my androidtv
package (which is used by Home Assistant), I forked your repo and renamed the package from adb
to adb_messenger
.
Any chance you'd be willing to rename the package from adb
to something else?
Is there capability to get return value of command execution via 'adb shell' ?
hi:
Is there a timeout when installing app?
I didn't find any way to do the equivalent of executing adb exec-out <command>
. Any plans of including it? Would it be difficult to implement that? I think it could be very useful to support it.
Now I use device.shell('input keyevent KEYCODE_POWER'), can u show me some usages?
Thanks a lot
According to the readme.md adb forward is supported, but i couldn't find any Example.
Can some one explain how it is done?
Traceback (most recent call last):
File "Serial.py", line 5, in
device.shell("echo hello world !")
AttributeError: 'NoneType' object has no attribute 'shell'
I am getting this error when trying to run this code on linux
from ppadb.client import Client as AdbClient
client = AdbClient(host="127.0.0.1", port=5037)
device = client.device("emulator-5554")
device.shell("echo hello world !") inside Serial.py
Am I missing anything?
Hi,
Issue core methods to get access to device API hangs and never finish.
Python code:
from ppadb.client import Client
adb = Client(host='192.168.0.123', port=5556)
devices = adb.devices() #Never passes this line, hangs forever
print(devices.version()) #Same, never passes this line, hangs forever
Shell:
$adb connect 192.168.0.123:5556
daemon not running; starting now at tcp:5037
daemon started successfully
connected to 192.168.0.123:5556
$adb shell input touchscreen swipe 500 500 500 900 200
Scroll Event Works
Troubleshooting:
Reinstalled ADB:
$sudo aptitude reinstall adb
reinstalled pure-python-adb:
$pip3 install pure-python-adb -U --no-cache-dir
noting helped...
Hello,
wait_boot_completed in transport/init.py has an incorrect timeout calculation.
In particular:
end_time = time.time() + timeout * 1000
timeout is defined as a value in seconds. time.time() returns a floating point value in seconds. Therefore the multiplication by 1000 is incorrect, and causes major hang-up issues if you do an adb reboot and want to hold up your script from doing anything until boot_completed is reached and the reboot fails to complete.
Can this line be fixed to:
end_time = time.time() + timeout
Thanks,
Edwin
device.shell('su cd /data/data/<app_pkg>/databases/')
blocking code. How to make request with su??
我想要把擷取到的圖片不儲存直接output並轉成opencv2可用的array
能請問下要怎麼改嗎?
現在卡在不知道怎麼把device.shell("screencap -p")的output存成字串
在实际使用过程中,发现执行meminfoContext = self.device.shell(dumpsys meminfo),获取系统所有进程内存数据时,耗时超过500ms,不知道是不是因为socket通信效率太低导致
Most modern Android applications support multiple platforms (device resolutions, ABI, etc) and hence have theirs installation packages splitted in multiple APK files; actually, any application in Google Play top-100 contains multiple APK files when you download it from Google Play.
It is required to support install-mulitple
command to install such applications. Without this command implementation ppadb
will become obsolete soon.
截取的图片,有的设备上的可以识别,有的设备上的不能识别
A declarative, efficient, and flexible JavaScript library for building user interfaces.
🖖 Vue.js is a progressive, incrementally-adoptable JavaScript framework for building UI on the web.
TypeScript is a superset of JavaScript that compiles to clean JavaScript output.
An Open Source Machine Learning Framework for Everyone
The Web framework for perfectionists with deadlines.
A PHP framework for web artisans
Bring data to life with SVG, Canvas and HTML. 📊📈🎉
JavaScript (JS) is a lightweight interpreted programming language with first-class functions.
Some thing interesting about web. New door for the world.
A server is a program made to process requests and deliver data to clients.
Machine learning is a way of modeling and interpreting data that allows a piece of software to respond intelligently.
Some thing interesting about visualization, use data art
Some thing interesting about game, make everyone happy.
We are working to build community through open source technology. NB: members must have two-factor auth.
Open source projects and samples from Microsoft.
Google ❤️ Open Source for everyone.
Alibaba Open Source for everyone
Data-Driven Documents codes.
China tencent open source team.