Skip to content

Instantly share code, notes, and snippets.

Embed
What would you like to do?
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

This comment has been minimized.

Copy link

@strooooke 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

This comment has been minimized.

Copy link

@pellet pellet commented Aug 24, 2016

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

@bitbytedog

This comment has been minimized.

Copy link

@bitbytedog bitbytedog commented Apr 16, 2017

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

This comment has been minimized.

Copy link

@eighthave eighthave commented Jun 12, 2018

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
You can’t perform that action at this time.