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


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
|improve this answer|||||
  • In bash you can use echo "${SSH_CLIENT%% *}" – ewatt Nov 10 '16 at 7:24
  • i use CentOS 7, $SSH_CLIENT variable is empty... ${SSH_CLIENT%% *} and $SSH_CONNECTION too – sungki Hong Nov 10 '16 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 Nov 10 '16 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)

|improve this answer|||||

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]}'
|improve this answer|||||

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.