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:39

Just type the following command on your Linux machine:

who
查看更多
女痞
3楼-- · 2019-01-20 23:39

Search for SSH connections for "myusername" account;

Take first result string;

Take 5th column;

Split by ":" and return 1st part (port number don't needed, we want just IP):

netstat -tapen | grep "sshd: myusername" | head -n1 | awk '{split($5, a, ":"); print a[1]}'


Another way:

who am i | awk '{l = length($5) - 2; print substr($5, 2, l)}'

查看更多
Melony?
4楼-- · 2019-01-20 23:42
who am i | awk '{print $5}' | sed 's/[()]//g' | cut -f1 -d "." | sed 's/-/./g'


export DISPLAY=`who am i | awk '{print $5}' | sed 's/[()]//g' | cut -f1 -d "." | sed 's/-/./g'`:0.0

I use this to determine my DISPLAY variable for the session when logging in via ssh and need to display remote X.

查看更多
趁早两清
5楼-- · 2019-01-20 23:42
 who | cut -d"(" -f2 |cut -d")" -f1
查看更多
一夜七次
6楼-- · 2019-01-20 23:44
netstat -tapen | grep ssh | awk '{ print $4}'
查看更多
劫难
7楼-- · 2019-01-20 23:44

Assuming he opens an interactive session (that is, allocates a pseudo terminal) and you have access to stdin, you can call an ioctl on that device to get the device number (/dev/pts/4711) and try to find that one in /var/run/utmp (where there will also be the username and the IP address the connection originated from).

查看更多
登录 后发表回答