Skip to content

Instantly share code, notes, and snippets.

@shaobin0604
Forked from dweinstein/android-tcpdump.sh
Created September 24, 2015 06:50
Show Gist options
  • Save shaobin0604/d4ff24f6da77a9b5943e to your computer and use it in GitHub Desktop.
Save shaobin0604/d4ff24f6da77a9b5943e to your computer and use it in GitHub Desktop.
Easier tcpdump setup for Android (make sure tcpdump binary is in /data/local/tmp/xbin/tcpdump). Assumes socat and wireshark are installed on your system and that you're on OS X. Easily tweaked for other platforms...
#!/usr/bin/env bash
TCPDUMP_PID=""
SOCAT_PID=""
OUTPUT_FILE=""
PORT=12345
TMPDIR="."
TCPDUMP_PATH="/data/local/tmp/xbin/tcpdump"
NETCAT_PATH="/data/local/tmp/nc"
HOST_INTERFACE="en0"
DEVICE_INTERFACE="wlan0"
OUTPUT_FILE=$(mktemp -t tcpdump) || exit 1
DEVICEIP=$(adb shell netcfg | grep ${DEVICE_INTERFACE} | awk '{print $3}' | cut -d '/' -f1) || exit 1
trap cleanup INT
trap ensure_processes_killed EXIT
function kill_proc {
$(adb shell ps | grep $1 | awk '{print $2}' | xargs adb shell kill) || true
}
function ensure_processes_killed {
kill_proc ${TCPDUMP_PATH}
kill_proc ${NETCAT_PATH}
}
function cleanup() {
#[[ ${TCPDUMP_PID} != "" ]] && kill ${TCPDUMP_PID} &> /dev/null || true
[[ ${SOCAT_PID} != "" ]] && kill ${SOCAT_PID} &> /dev/null || true
[[ ${OUTPUT_FILE} != "" ]] && rm -i ${OUTPUT_FILE} || true
}
function check_host {
if [[ $(uname) = "Darwin" ]] ; then
HOSTIP=$(ifconfig ${HOST_INTERFACE} | grep "inet " | awk '{print $2}')
else
echo "this is currently meant to run on OS X. Update me to include Linux..."
exit 1
fi
}
function ensure_bin_present {
local info=$(adb shell ls $2 | tr -d '\r' | tr -d '\n')
if [[ ${info} != $2 ]]; then
echo $1 " needs to be loaded to $2; got ${info}"
exit 1
fi
}
function start_record {
CMD="${TCPDUMP_PATH} -n -s 0 -w - not host ${HOSTIP} | ${NETCAT_PATH} -l -p ${PORT}"
adb shell "su -c \"${CMD}\"" &
#TCPDUMP_PID=$!
}
function connect_to_device {
socat -U -d file:${OUTPUT_FILE},create,wronly tcp-connect:${DEVICEIP}:${PORT},forever &> /dev/null
SOCAT_PID=$!
}
function run_wireshark {
echo "output file: ${OUTPUT_FILE}"
wireshark ${OUTPUT_FILE} &> /dev/null &
}
ensure_processes_killed
check_host
ensure_bin_present "netcat" ${NETCAT_PATH}
ensure_bin_present "tcpdump" ${TCPDUMP_PATH}
start_record
run_wireshark
echo "refresh your wireshark periodically; [Ctrl-C] when done capturing"
connect_to_device
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment