在屏幕会话中访问SSH客户端IP地址 [英] Access SSH client IP address, within a screen session

查看:153
本文介绍了在屏幕会话中访问SSH客户端IP地址的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

可以通过环境变量(例如SSH_CONNECTION)访问连接的SSH客户端的IP地址,如

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

>找到客户端的IP地址在SSH会话中

尽管如此,在GNU屏幕会话中,那些环境变量是由启动屏幕的人定义的.对于以后进入已经存在的屏幕会话的人(例如从另一台主机),是否还有任何方法可以保持SSH连接信息?

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.

推荐答案

如果以root用户身份启动了屏幕会话,则可以,但是并不是绝对可靠的

  1. 如果两个用户在同一个屏幕窗口中键入内容,则他们将在同一个shell中进行交互.一个人可以写一条命令.另一个可以按<enter>键.

您必须具有对环境变量SSH_CONNECTION(或更好的SSH_CLIENT)的访问权限,只有在您是root用户或在屏幕会话中使用同一用户的情况下,才可以访问该变量.

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.

假设您是屏幕会话的root用户,则可以使用ps命令并找到最后一个活动会话,从而知道屏幕会话中最后一个活动的用户.

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

通过使用pid并访问/proc/<pid>/environ文件,您可以获得SSH_CLIENT变量.

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

所有这些都假定您的屏幕以root用户身份执行

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=\0' -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

请注意,如果发现更简单,也可以解析ps eh -C screen kstime -o args命令的结果.

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

这是一个有效的Debian命令,用于使当前所有用户都连接到同一屏幕会话:

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 "%h\n"
      | cut -f2 -d-

这篇关于在屏幕会话中访问SSH客户端IP地址的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆