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