[英]In Python, how do I get user's remote IP (their last hop) if they're connected over SSH?
I want to detect if the user is connected over SSH.我想检测用户是否通过 SSH 连接。 In a term, the "env" command shows SSH_CONNECTION line.
总而言之,“env”命令显示 SSH_CONNECTION 行。 Accessed in Python in one of two ways:
通过以下两种方式之一在 Python 中访问:
#python:
import os
print os.getenv("SSH_CONNECTION") #works
print os.environ.get("SSH_CONNECTION") #works
But, if the user has ran my program using SUDO (as they will need to), env$ dooesn't show SSH_CONNECTION.但是,如果用户使用 SUDO 运行了我的程序(因为他们需要),env$ 不会显示 SSH_CONNECTION。 So Python can't see it:
所以Python看不到它:
#sudo python:
import os
print os.getenv("SSH_CONNECTION") #not set
print os.environ.get("SSH_CONNECTION") #not set
The aim is to achieve the following:目标是实现以下目标:
#Detect if user is over remote IP
lRemoteIP="" #Is set if user on SSH
lStr=os.environ.get("SSH_CONNECTION") #Temp var
if lStr: lRemoteIP=lStr.split()[0].split("=")[1] #Store user's lasthop IP
#Later on in the code, for multiple purposes:
if lRemoteIP: pass #Do stuff (or not) depending on if they're on SSH
How do I retrieve SSH_CONNECTION environment variable under SUDO, when its not present in env$ ?当 env$ 中不存在 SSH_CONNECTION 环境变量时,如何在 SUDO 下检索 SSH_CONNECTION 环境变量?
Or more precisely: how can I detect if the current session is via SSH when sudo?或者更准确地说:如何在 sudo 时检测当前会话是否通过 SSH?
I'm not a natural at Linuxy-type things, so be gentle with me...我不擅长 Linux 类型的东西,所以对我温柔一点......
[EDIT:] METHOD 2: Giving up on env$, I've tried the following: [编辑:] 方法 2:放弃 env$,我尝试了以下方法:
pstree -ps $$ | grep "sshd("
If it returns anything then it means that the SSH daemon sits above the session.如果它返回任何内容,则意味着 SSH 守护进程位于会话之上。 Ergo, it's a SSH connection.
因此,这是一个 SSH 连接。 And the results are showing me the PIDs of the SSH daemons.
结果向我展示了 SSH 守护进程的 PID。 Results of the pstree cmd:
pstree cmd 的结果:
init(1)---sshd(xxx)---sshd(xxx)---sshd(xxx)---bash(xxx)-+-grep(xxx)
But I'm struggling to get a src IP from the PID.但是我正在努力从 PID 中获取 src IP。 Any ideas on this avenue?
关于这条路的任何想法?
[EDIT] METHOD 3: /run/utmp contains details of SSH logins. [编辑] 方法 3:/run/utmp 包含 SSH 登录的详细信息。 In python:
在蟒蛇中:
import os
import sys
lStr=open("/var/run/utmp").read().replace('\x00','') #Remove all those null values which make things hard to read
#Get the pseudo-session ID (pts) minus the /dev/ that it starts with:
lCurSess=os.ttyname(sys.stdout.fileno()).replace('/dev/','')
#Answer is like pts/10 (pseudo-term session number 10)
#Search lStr for pts/10
lInt=lStr.find(lCurSess.replace('/dev/',''))
#Print /var/utmp starting with where it first mentions current pts:
print lStr[lInt:]
So far, so good.到目前为止,很好。 This gives the following results (I've changed the IP and username to USERNAME)
这给出了以下结果(我已将 IP 和用户名更改为 USERNAME)
pts/10/10USERNAME\x9e\x958Ym\xb2\x05\x0 74\x14pts/10s/10USERNAME192.168.1.1\xbf\x958Y\xf8\xa3\r\xc0\xa88\x01
So, when it comes to extracting the IP from the file, there's some bumf inbetween the occurances of pts/10 and the IP.因此,在从文件中提取 IP 时,在 pts/10 和 IP 之间存在一些问题。 What's the best way to parse it, given that (I reckon) the precise distance from the match to the IP will be different under different circumstances?
考虑到(我认为)从匹配到 IP 的精确距离在不同情况下会有所不同,解析它的最佳方法是什么?
The OpenSSH daemon writes an entry to /var/run/utmp with the current terminal, the IP and the name of the user. OpenSSH 守护进程使用当前终端、IP 和用户名将条目写入 /var/run/utmp。 Check the output of the
w
or who
commands that parse /var/run/utmp.检查解析 /var/run/utmp 的
w
或who
命令的输出。
It's just a question of getting the current terminal (similar to the tty
command) and extracting the information you want.这只是获取当前终端(类似于
tty
命令)并提取您想要的信息的问题。
Use pyutmp like this:像这样使用pyutmp :
from pyutmp import UtmpFile
import os
import sys
for utmp in UtmpFile():
if os.ttyname(sys.stdout.fileno()) == utmp.ut_line:
print '%s logged from %s on tty %s' % (utmp.ut_user, utmp.ut_host, utmp.ut_line)
Then filter by using ut_pid
field to parse the /proc/ ut_pid
/cmdline file which should contain:然后使用
ut_pid
字段进行过滤以解析 /proc/ ut_pid
/cmdline 文件,该文件应包含:
sshd: ut_user [priv]
sshd: ut_user [priv]
GOT IT AT LAST!!!终于搞定了!!!
The "last" command has list of users and their IPs!! “last”命令包含用户及其 IP 的列表!! So simple.
如此简单。
It has "still logged in" marked against sessions.它针对会话标记了“仍然登录”。 Filter by these And then filter by current pts ID
按这些过滤然后按当前pts ID过滤
To get the IP for the current SSH session in Python, do this:要在 Python 中获取当前 SSH 会话的 IP,请执行以下操作:
import os,sys,subprocess
(out, err) = subprocess.Popen(['last | grep "still logged in" | grep "' + os.ttyname(sys.stdout.fileno()).replace('/dev/','') + '"'], stdout=subprocess.PIPE, shell=True).communicate()
RemoteIP=out.split()[2].replace(":0.0","") #Returns "" if not SSH
For readability, across multiple lines:为了可读性,跨多行:
import os,sys,subprocess
pseudoTermID = os.ttyname(sys.stdout.fileno()).replace('/dev/','')
cmdStr = 'last | grep "still logged in" | grep "'+pseudoTermID+'"'
sp = subprocess.Popen([cmdStr], stdout=subprocess.PIPE, shell=True)
(out, err) = sp.communicate()
RemoteIP = out.split()[2].replace(":0.0","") #Returns "" if not SSH
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.