Send keyboard/button events to android over ssh (volume up/down) – python

install ssh server on android. full list of keyboard-codes here:
http://stackoverflow.com/questions/7789826/adb-shell-input-events

sorry, the indents are lost cause of wpress editor..

#!/usr/bin/env python

import paramiko
import termios, fcntl, sys, os

hostname = '192.168.x.x'
port = 22
username = 'user'
password = 'password'

ssh = paramiko.SSHClient()
ssh.load_system_host_keys()
ssh.connect(hostname, port, username, password)

def volume_down():
stdin, stdout, stderr = ssh.exec_command("input keyevent 25")
stdin.write('lol\n')
stdin.flush()
out= stdout.read
print out

def volume_up():
stdin, stdout, stderr = ssh.exec_command("input keyevent 24")
stdin.write('lol\n')
stdin.flush()
out= stdout.read
print out

def read_single_keypress():
"""Waits for a single keypress on stdin.

This is a silly function to call if you need to do it a lot because it has
to store stdin's current setup, setup stdin for reading single keystrokes
then read the single keystroke then revert stdin back after reading the
keystroke.

Returns the character of the key that was pressed (zero on
KeyboardInterrupt which can happen when a signal gets handled)

"""
import termios, fcntl, sys, os
fd = sys.stdin.fileno()
# save old state
flags_save = fcntl.fcntl(fd, fcntl.F_GETFL)
attrs_save = termios.tcgetattr(fd)
# make raw - the way to do this comes from the termios(3) man page.
attrs = list(attrs_save) # copy the stored version to update
# iflag
attrs[0] &= ~(termios.IGNBRK | termios.BRKINT | termios.PARMRK
| termios.ISTRIP | termios.INLCR | termios. IGNCR
| termios.ICRNL | termios.IXON )
# oflag
attrs[1] &= ~termios.OPOST
# cflag
attrs[2] &= ~(termios.CSIZE | termios. PARENB)
attrs[2] |= termios.CS8
# lflag
attrs[3] &= ~(termios.ECHONL | termios.ECHO | termios.ICANON
| termios.ISIG | termios.IEXTEN)
termios.tcsetattr(fd, termios.TCSANOW, attrs)
# turn off non-blocking
fcntl.fcntl(fd, fcntl.F_SETFL, flags_save & ~os.O_NONBLOCK)
# read a single keystroke
try:
ret = sys.stdin.read(1) # returns a single character
except KeyboardInterrupt:
ret = 0

finally:
# restore old state
termios.tcsetattr(fd, termios.TCSAFLUSH, attrs_save)
fcntl.fcntl(fd, fcntl.F_SETFL, flags_save)
return ret

while 1:

key=read_single_keypress()
#print int(key)
if key=="0":
sys.exit()
if key=="\x1b": #ESC
sys.exit()
if key=="\x03": #ctrl-c
sys.exit()
if key=="+":
volume_up()
if key=="-":
volume_down()
print 'key is',key

s.close()

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s