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.
Check if there is an environment variable called:
OR
(or any other environment variables) which gets set when the user logs in. Then process it using the user login script.
Extract the IP:
an older thread with a lot of answers, but none are quite what i was looking for, so i'm contributing mine:
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.
Usually there is a log entry in /var/log/messages (or similar, depending on your OS) which you could grep with the username.
You could use the command:
that will give to you somehting like this:
Linux: who am i | awk '{print $5}' | sed 's/[()]//g'
AIX: who am i | awk '{print $6}' | sed 's/[()]//g'