Skip to content

Instantly share code, notes, and snippets.

@aarmea
Created December 25, 2024 19:09
Show Gist options
  • Save aarmea/b288726b72f26c8694e68e6dfde8a463 to your computer and use it in GitHub Desktop.
Save aarmea/b288726b72f26c8694e68e6dfde8a463 to your computer and use it in GitHub Desktop.
Script that connects to a server by MAC, rather than IP, address
#!/bin/bash
# Scans all available local networks for the host specified by `MAC_ADDRESS`
# then connects to it over SSH with the provided parameters.
# Useful for hosts whose root partitions are encrypted that also have Dropbear SSH
# set up in the bootloader as described at https://www.cyberciti.biz/security/how-to-unlock-luks-using-dropbear-ssh-keys-remotely-in-linux/
# Replace these values as appropriate
MAC_ADDRESS="01:23:45:67:89:ab" # Letters must be lowercase
SSH_PORT=1234
USER="root"
echo "Scanning for host with MAC address "$MAC_ADDRESS"..."
# Find all the active interfaces...
ACTIVE_INTERFACES=$(ifconfig | awk '/UP/ {print $1}' | sed 's/://g')
if [ -z "$ACTIVE_INTERFACES" ]; then
echo "Error: No active network interfaces found."
exit 1
fi
# ... arp-scan on all of them...
HOST_IP=""
for IFACE in $ACTIVE_INTERFACES; do
echo "Scanning on interface $IFACE..."
HOST_IP=$(arp-scan --interface="$IFACE" --localnet 2>/dev/null | awk -v mac="$MAC_ADDRESS" 'BEGIN {IGNORECASE = 1} $2 == mac {print $1}')
if [ -n "$HOST_IP" ]; then
break
fi
done
if [ -z "$HOST_IP" ]; then
echo "Error: Could not find a host with the specified MAC address."
exit 1
fi
echo "Host found at IP address $HOST_IP"
# ... and once found, connect via SSH.
ssh -p $SSH_PORT $USER@$HOST_IP
# Generative AI disclaimer:
# The core of the script came from the following ChatGPT response: https://chatgpt.com/share/676c580f-0708-800b-a51b-4edb527f1641
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment