Created
May 4, 2019 05:48
-
-
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)
This file contains 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
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