wicked_snail
wicked_snail

Reputation: 9

execute adb commands in cmd prompt from python script

I am trying to execute adb commands in an automated way from python script. Please note that I am using python 2.7 in Windows. If I manually do it, the sequence is like this:

C:\Project\python>adb shell
login:<enter login id e.g. root>
Password: <enter password e.g. test>
Last login: Thu Feb  9 12:29:46 UTC 2017 on pts/0
~ # date
date
Thu Feb  9 12:55:06 UTC 2017

I am trying to handle this sequence from python script. I have tried using subprocess.call("adb shell date") but it fails saying that cannot execute commands without logging in. I am not sure how to to pass the login id and password. Sorry for the noob question, as I am very new to Python.

Appreciate your help guys !!

Cheers

Upvotes: 0

Views: 9136

Answers (2)

Nafeez Quraishi
Nafeez Quraishi

Reputation: 6158

I was getting below error with process.communicate('command_to_send\n')

TypeError: a bytes-like object is required, not 'str'

Using the subprocess communicate command in below way resolved the TypeError:

process.communicate(b'input keyevent KEYCODE_CALL\n')

Upvotes: 0

CodenameLambda
CodenameLambda

Reputation: 1496

Try subprocess.Popen:

import subprocess

cmd_input = """<enter login id e.g. root>
<enter password e.g. test>
date"""

process = subprocess.Popen(
    "adb shell",
    shell=True,
    stdin=subprocess.PIPE,
    stdout=subprocess.PIPE
)
process.communicate()
for i in cmd_input.split("\n"):
    process.communicate(i + "\n")

Or:

process = subprocess.Popen(
    "adb shell",
    shell=True,
    stdin=subprocess.PIPE,
    stdout=subprocess.PIPE
)
process.communicate(user + "\n")
process.communicate(pwd + "\n")
process.communicate(cmd + "\n")

Another option is to use google/python-adb or adb via pip

Upvotes: 1

Related Questions