Skip to content
Advertisement

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. In a term, the “env” command shows SSH_CONNECTION line. Accessed in Python in one of two ways:

JavaScript

But, if the user has ran my program using SUDO (as they will need to), env$ dooesn’t show SSH_CONNECTION. So Python can’t see it:

JavaScript

The aim is to achieve the following:

JavaScript

How do I retrieve SSH_CONNECTION environment variable under SUDO, when its not present in env$ ?

Or more precisely: how can I detect if the current session is via SSH when sudo?

I’m not a natural at Linuxy-type things, so be gentle with me…

[EDIT:] METHOD 2: Giving up on env$, I’ve tried the following:

JavaScript

If it returns anything then it means that the SSH daemon sits above the session. Ergo, it’s a SSH connection. And the results are showing me the PIDs of the SSH daemons. Results of the pstree cmd:

JavaScript

But I’m struggling to get a src IP from the PID. Any ideas on this avenue?

[EDIT] METHOD 3: /run/utmp contains details of SSH logins. In python:

JavaScript

So far, so good. This gives the following results (I’ve changed the IP and username to USERNAME)

JavaScript

So, when it comes to extracting the IP from the file, there’s some bumf inbetween the occurances of pts/10 and the 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?

Advertisement

Answer

GOT IT AT LAST!!!

The “last” command has list of users and their IPs!! So simple.

It has “still logged in” marked against sessions. Filter by these And then filter by current pts ID

To get the IP for the current SSH session in Python, do this:

JavaScript

For readability, across multiple lines:

JavaScript
User contributions licensed under: CC BY-SA
9 People found this is helpful
Advertisement