Skip to content

Instantly share code, notes, and snippets.

@rwarren
Created May 4, 2019 05:48
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save rwarren/f84948a045ee40c60dc5e7b969b5db48 to your computer and use it in GitHub Desktop.
Save rwarren/f84948a045ee40c60dc5e7b969b5db48 to your computer and use it in GitHub Desktop.
shell function to robustly get the IP address of the currently connected ssh client (through subshells, user changes, and more)
get_ssh_client_ip() {
# Returns (via stdout) the IP address for the currently connected SSH session
# - this relies on the ssh server setting the SSH_CLIENT env var (done by openssh, dropbear, etc)
pid=$$ # current pid will be checked
while [ "$pid" -ne 1 ]; do
cip=$(cat /proc/$pid/environ | tr '\0' '\n' | grep 'SSH_CLIENT=' | awk -F'[= ]' '{ print $2 }')
[ -n "$cip" ] && break # got it!
pid=$(awk '{ print $4 }' /proc/$pid/stat) # the parent pid for the next try
done
echo "$cip" # will be null if we couldn't find it
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment