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
Unix & Linux Stack Exchange is a question and answer site for users of Linux, FreeBSD and other Un*x-like operating systems. It only takes a minute to sign up.
Sign up to join this communityIt 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
env | grep YOURIPADDR
.
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]}'