Find the IP address of the client in an SSH session

后端 未结 19 1072
刺人心
刺人心 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条回答
  •  旧时难觅i
    2020-12-12 11: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.

提交回复
热议问题