Find the IP address of the client in an SSH session

后端 未结 19 1012
刺人心
刺人心 2020-12-12 10:48

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 fr

相关标签:
19条回答
  • 2020-12-12 11:11

    Improving on a prior answer. Gives ip address instead of hostname. --ips not available on OS X.

    who am i --ips|awk '{print $5}' #ubuntu 14
    

    more universal, change $5 to $6 for OS X 10.11:

    WORKSTATION=`who -m|awk '{print $5}'|sed 's/[()]//g'`
    WORKSTATION_IP=`dig +short $WORKSTATION`
    if [[ -z "$WORKSTATION_IP" ]]; then WORKSTATION_IP="$WORKSTATION"; fi
    echo $WORKSTATION_IP
    
    0 讨论(0)
  • 2020-12-12 11:11

    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)}'

    0 讨论(0)
  • 2020-12-12 11:13

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

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

    0 讨论(0)
  • 2020-12-12 11:15
     who | cut -d"(" -f2 |cut -d")" -f1
    
    0 讨论(0)
  • 2020-12-12 11:17

    netstat will work (at the top something like this) tcp 0 0 10.x.xx.xx:ssh someipaddress.or.domainame:9379 ESTABLISHED

    0 讨论(0)
  • 2020-12-12 11:18

    I'm getting the following output from who -m --ips on Debian 10:

    root pts/0 Dec 4 06:45 123.123.123.123

    Looks like a new column was added, so {print $5} or "take 5th column" attempts don't work anymore.

    Try this:

    who -m --ips | egrep -o '([0-9]{1,3}\.){3}[0-9]{1,3}'
    

    Source:

    • @Yvan's comment on @AlexP's answer
    • @Sankalp's answer
    0 讨论(0)
提交回复
热议问题