2

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

0

3 Answers 3

7

It is available as part of the environment variable SSH_CLIENT:

$ echo "$SSH_CLIENT"
SSH_CLIENT=192.168.0.101 39323 22
$ echo "$SSH_CLIENT" | cut -d' ' -f 1
192.168.0.101
3
  • 1
    In bash you can use echo "${SSH_CLIENT%% *}"
    – ewatt
    Nov 10, 2016 at 7:24
  • 1
    i use CentOS 7, $SSH_CLIENT variable is empty... ${SSH_CLIENT%% *} and $SSH_CONNECTION too 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
    Nov 10, 2016 at 9:49
2

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)

0

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 .