Skip to content

Instantly share code, notes, and snippets.

@vaughandroid
Created May 25, 2016 09:35
Show Gist options
  • Save vaughandroid/310c6d1d12f5473ea2e098982c77443f to your computer and use it in GitHub Desktop.
Save vaughandroid/310c6d1d12f5473ea2e098982c77443f to your computer and use it in GitHub Desktop.
Script to kill an Android emulator which requires authentication
#!/usr/bin/expect
##############################################################
#
# KILL-EMULATOR
#
# Kills an Android emulator which requires authentication.
# It works by opening a telnet session and authenticates, before issuing the
# kill command.
#
# Usage: `expect -f kill-emulator.exp <port>`
# where <port> is optional (defaults to 5554)
#
# Since SDK Tools 25.1.6, the Android emulator has required authentication
# before any commands can be run on it. This breaks commands such as
# `adb emu kill`.
#
# References:
# - https://developer.android.com/studio/run/emulator-commandline.html#console-session
# - https://code.google.com/p/android/issues/detail?id=21021#
#
##############################################################
set timeout 10
# Parse params.
# Port is optional, and defaults to 5554
proc parseArgv {{port "5554"}} {
variable ::PORT $port
}
parseArgv {*}$argv
# Read auth token from file
set TOKEN [read [open "$::env(HOME)/.emulator_console_auth_token" r]]
send_user "Killing emulator on port $PORT with auth token $TOKEN\n"
# Start telnet session, and issue the commands.
spawn telnet localhost $PORT
expect "OK"
send "auth $TOKEN\r"
send "kill\r"
@strooooke
Copy link

strooooke commented May 31, 2016

Thank you very very much! I had to insert additional
expect "OK"
like this:

# Start telnet session, and issue the commands.
spawn telnet localhost $PORT
expect "OK"
send "auth $TOKEN\r"
expect "OK"
send "kill\r"
expect "OK"

to get it working.

@pellet
Copy link

pellet commented Aug 24, 2016

great work! this fixed my CI... saved me the time having to fix it myself, cheers!

@bitbytedog
Copy link

It can also be done with a bash function:

function stopAvd() {
    nc localhost 5554 << _EOF > /dev/null 2>&1
auth `cat  ~/.emulator_console_auth_token`
kill
_EOF
}

@eighthave
Copy link

If you don't need the auth token, like in a CI runner, then you can do it very simply without auth:

cp /dev/null ~/.emulator_console_auth_token
echo kill | nc -w 120 localhost 5554
rm -f ~/.emulator_console_auth_token

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