Skip to content
Advertisement

Access SSH client IP address, within a screen session

Accessing the IP address of a connecting SSH client is possible via environment variables (such as SSH_CONNECTION), as described in

Find the IP address of the client in an SSH session

In a GNU screen session though, those environment variables are defined by whoever started the screen to begin with. Is there any way to also get hold of the SSH connection information, for someone who enters an already-existing screen session later, like from another host?

I can’t think of a way to determine this, but this can be useful in cases where screen sessions are shared between different people, for example.

Advertisement

Answer

If the screen session is launched as root, you can but it won’t be perfectly reliable

  1. If two users type in the same screen window, they will both interact within the same shell. One can write a command. The other can press the <enter> key.

  2. You have to get access to the environment variable SSH_CONNECTION (or better SSH_CLIENT) which is only possible if you are root, or if you use the same user inside the screen session.

Supposing you are root inside the screen session, you can know the last user active in a screen session by using the ps command and finding the last active session.

ps h -C screen katime -o pid,user

By using the pid, and accessing the /proc/<pid>/environ file, you can get the SSH_CLIENT variable.

sed -z '/SSH_CLIENT/p;d' /proc/`ps h -C screen katime -o pid |head -1`/environ

--> SSH_CLIENT=257.31.120.12

All of this suppose that your screen is executed as root

You can also chose to log all the active connections. For such need, I would suggest you to store both the full list of connections and their last activity.

ps eh -C screen kstime -o pid,atime | while read pid stime; do echo -n "$stime: ";
    gawk -v 'RS=' -F= '$1=="SSH_CLIENT" {print $2}' /proc/$pid/environ; done

Result:
00:00:00: 257.31.120.12 61608 22
00:07:11: 258.1.2.3.4 49947 22

Note that you can also parse the result of the ps eh -C screen kstime -o args command if you find it easier.

EDIT:

This is a working Debian command to get all users currently connected to the same screen session:

 find /var/run/screen/
     -name $(pstree -sp $$ |sed 's/.*screen(([0-9]*)).*/1/;q').*
     -printf "%hn"
      | cut -f2 -d-
User contributions licensed under: CC BY-SA
7 People found this is helpful
Advertisement