Find the IP address of the client in an SSH sessio

2019-01-20 22:55发布

I have a script that is to be run by a person that logs in to the server with SSH.

Is there a way to find out automatically what IP address the user is connecting from?

Of course, I could ask the user (it is a tool for programmers, so no problem with that), but it would be cooler if I just found out.

19条回答
一夜七次
2楼-- · 2019-01-20 23:30

Check if there is an environment variable called:

$SSH_CLIENT 

OR

$SSH_CONNECTION

(or any other environment variables) which gets set when the user logs in. Then process it using the user login script.

Extract the IP:

$ echo $SSH_CLIENT | awk '{ print $1}'
1.2.3.4
$ echo $SSH_CONNECTION | awk '{print $1}'
1.2.3.4
查看更多
趁早两清
3楼-- · 2019-01-20 23:30

an older thread with a lot of answers, but none are quite what i was looking for, so i'm contributing mine:

sshpid=$$
sshloop=0
while [ "$sshloop" = "0" ]; do
        if [ "$(strings /proc/${sshpid}/environ | grep ^SSH_CLIENT)" ];
then
                read sshClientIP sshClientSport sshClientDport <<< $(strings /proc/${sshpid}/environ | grep ^SSH_CLIENT | cut -d= -f2)
                sshloop=1
        else
                sshpid=$(cat /proc/${sshpid}/status | grep PPid | awk '{print $2}')
                [ "$sshpid" = "0" ] && sshClientIP="localhost" && sshloop=1
        fi
done

this method is compatible with direct ssh, sudoed users, and screen sessions. it will trail up through the process tree until it finds a pid with the SSH_CLIENT variable, then record its IP as $sshClientIP. if it gets too far up the tree, it will record the IP as 'localhost' and leave the loop.

查看更多
Anthone
4楼-- · 2019-01-20 23:32

Usually there is a log entry in /var/log/messages (or similar, depending on your OS) which you could grep with the username.

查看更多
Anthone
5楼-- · 2019-01-20 23:37

You could use the command:

server:~# pinky

that will give to you somehting like this:

Login      Name                 TTY    Idle   When                 Where 

root       root                 pts/0         2009-06-15 13:41     192.168.1.133
查看更多
贼婆χ
6楼-- · 2019-01-20 23:37

Linux: who am i | awk '{print $5}' | sed 's/[()]//g'

AIX: who am i | awk '{print $6}' | sed 's/[()]//g'

查看更多
等我变得足够好
7楼-- · 2019-01-20 23:38

Simplest command to get the last 10 users logged in to the machine is last|head.

To get all the users simply use last command

查看更多
登录 后发表回答