In SSH server, I want to get the connected client IP address. I use $ who or $ w can get logged information(include client's IP address)

I just want client's IP address (one thing), use in shell script


3 Answers 3


It is available as part of the environment variable SSH_CLIENT:

$ echo "$SSH_CLIENT"
SSH_CLIENT= 39323 22
$ echo "$SSH_CLIENT" | cut -d' ' -f 1
  • 1
    In bash you can use echo "${SSH_CLIENT%% *}"
    – ewatt
    Commented Nov 10, 2016 at 7:24
  • 1
    i use CentOS 7, $SSH_CLIENT variable is empty... ${SSH_CLIENT%% *} and $SSH_CONNECTION too Commented Nov 10, 2016 at 7:34
  • I use have this set when using CENTOS 7 (both as server connected from a Linux Mint system, as well as from CentOS 7 system). If you know (by other means) your client IP try: env | grep YOURIPADDR.
    – Anthon
    Commented Nov 10, 2016 at 9:49

For all users try

w --no-header | awk '{print $1" "$3}'

In short

w -h | awk '{print $1" "$3}'

There you can grep for the username. Keep in mind that a user can login several times and from different locations / IPS. You also want to check if you can force the w-command to output IPs instead of hostnames (depends on version -n or -i)

Probably you also have to filter out local logins (console)


Another way is using netstat and awk. Assuming that you are using port 22 for the ssh protocol:

netstat -putan | awk '/:22 / && /ESTABLISHED/ {split($5,result,":"); print result[1]}'

Not the answer you're looking for? Browse other questions tagged .