How can I know if the user is connected to the local machine via ssh in my python script?
views:
59answers:
3Am 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.
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
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.