Created
December 28, 2023 10:00
-
-
Save jwangac/25f4e2f630bc9bc2cf5f2c1c45c39db0 to your computer and use it in GitHub Desktop.
A Bash script to connect to an Android device over ADB using a hostname
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| #!/bin/bash | |
| set -euo pipefail | |
| shopt -s inherit_errexit | |
| if [[ $# -ne 1 ]]; then | |
| >&2 echo "usage: $0 <hostname>" | |
| exit 1 | |
| fi | |
| # fix freeze when adb is not running | |
| adb start-server >/dev/null 2>/dev/null | |
| sleep 0.1 | |
| devices=$(adb devices | grep -v "List" | grep device | wc -l || true) | |
| if [[ $devices -gt 0 ]]; then | |
| echo "Devices are connected." | |
| adb disconnect | |
| fi | |
| hostname="$1" | |
| ipv4=$(dig +short "$hostname" A | head -n 1) | |
| port="$(nmap $ipv4 -p 37000-44000 | awk "/\/tcp/" | cut -d/ -f1 | sort | head -n 1)" | |
| target="$ipv4:$port" | |
| echo "Target: $target" | |
| adb connect "$target" | |
| if [[ "$port" != "37000" ]]; then | |
| adb tcpip 37000 | |
| adb disconnect | |
| sleep 1 | |
| adb connect "$ipv4:37000" | |
| fi |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment