Skip to content

Instantly share code, notes, and snippets.

@clapbr
Last active August 13, 2021 03:07
Show Gist options
  • Save clapbr/f525c15c2795bdd87041022c5f759390 to your computer and use it in GitHub Desktop.
Save clapbr/f525c15c2795bdd87041022c5f759390 to your computer and use it in GitHub Desktop.
flask monkeyrunner http remote PoC (don't use this in production)
from flask import Flask
from flask_restful import Resource, Api, reqparse
from com.android.monkeyrunner import MonkeyRunner, MonkeyDevice
from apscheduler.schedulers.background import BackgroundScheduler
import time
import subprocess
app = Flask(__name__)
api = Api(app)
app.config['psk'] = '9876'
app.config['android_ip'] = '192.168.0.27'
parser = reqparse.RequestParser()
class Monkey(object):
def __init__(self):
self.runner = MonkeyRunner.waitForConnection(3)
apsched = BackgroundScheduler()
apsched.start()
apsched.add_job(self.check_connection, 'interval', seconds=5) # check_connection every 5s
return
def reconnect(self):
self.runner = MonkeyRunner.waitForConnection(3)
try:
self.runner.getPropertyList()
except:
time.sleep(0.5) # prevent reconnecting too fast
return
def check_connection(self):
# Ugliest possible way of keeping ADB alive
adb_check = subprocess.call(['adb', 'get-state', '1'], stderr=subprocess.DEVNULL, stdout=subprocess.DEVNULL)
if adb_check:
subprocess.run(['adb', 'connect', app.config['android_ip']], stderr=subprocess.DEVNULL, stdout=subprocess.DEVNULL)
try:
self.runner.getPropertyList()
except:
print("Connection lost")
self.reconnect()
return
class Input(Resource):
def post(self):
parser.add_argument('psk', type=str)
parser.add_argument('input', type=str)
args = parser.parse_args()
if (args["psk"] == app.config['psk']):
cmd = args["input"]
try:
monkey.runner.press(cmd, MonkeyDevice.DOWN_AND_UP)
return {
'status': True,
'input': cmd
}
except:
return { 'status': False }
else:
return { 'status': False }
monkey = Monkey()
api.add_resource(Input, '/input')
if __name__ == '__main__':
app.run(debug=False) # you should use gunicorn instead of flask debug server
@clapbr
Copy link
Author

clapbr commented Dec 30, 2019

sample usage: curl -d '{"psk":9876,"input":"KEYCODE_VOLUME_MUTE"}' -H 'Content-Type: application/json' http://127.0.0.1:5000/input
full list of keycodes here: https://developer.android.com/reference/android/view/KeyEvent.html

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment