shino
shino

Reputation: 4734

How can I know if the user is connected to the local machine via ssh in my python script?

How can I know if the user is connected to the local machine via ssh in my python script?

Upvotes: 1

Views: 664

Answers (3)

BillThor
BillThor

Reputation: 7576

Check any of the SSH variables SSH_CONNECTION, SSH_CLIENT, or SSH_TTY. However, these can be unset by the user.

Check the output of who am i. It will end with the remote system identification in brackets if you are connected remotely. Make sure to handle x-term sessions which will have a colon (:) in the remote system id.

Upvotes: 0

Andrew
Andrew

Reputation: 13191

You can use the os module to check for the existence of the environment variable SSH_CONNECTION.

>>> import os
>>> using_ssh = 'SSH_CONNECTION' in os.environ

Upvotes: 6

warriorpostman
warriorpostman

Reputation: 2328

Am I correct in assuming you're running your script on some sort of UNIX/Linux system? If so, you can just type "users" on the command-line, and it will show you the currently logged in users.

Also, if you call the "lastlog" command, that will show you all the users on the system and the last time they all logged in to the machine.

Upvotes: 0

Related Questions