Skip to content Skip to sidebar Skip to footer

How To Check If Python Script Is Being Called Remotely Via Ssh

So I'm writing a command line utility and I've run into a problem I'm curious about. The utility can be called with file arguments or can read from sys.stdin. Originally I was usin

Solution 1:

You can tell if you're being invoked via SSH by checking your environment. If you're being invoked via an SSH connection, the environment variables SSH_CONNECTION and SSH_CLIENT will be set. You can test if they are set with, say:

if"SSH_CONNECTION"inos.environ:
    # do something

Another option, if you wanted to just stick with your original approach of sys.stdin.isatty(), would be to to allocate a pseudo-tty for the SSH connection. Normally SSH does this by default if you just SSH in for an interactive session, but not if you supply a command. However, you can force it to do so when supplying a command by passing the -t flag:

ssh -t server utility

However, I would caution you against doing either of these. As you can see, trying to detect whether you should accept input from stdin based on whether it's a TTY can cause some surprising behavior. It could also cause frustration from users if they wanted a way to interactively provide input to your program when debugging something.

The approach of adding an explicit - argument makes it a lot more explicit and less surprising which behavior you get. Some utilities also just use the lack of any file arguments to mean to read from stdin, so that would also be a less-surprising alternative.

Solution 2:

According to this answer the SSH_CLIENT or SSH_TTY environment variable should be declared. From that, the following code should work:

import os

def running_ssh():
    return'SSH_CLIENT'inos.environ or'SSH_TTY'inos.environ

A more complete example would examine the parent processes to check if any of them are sshd which would probably require the psutil module.

Post a Comment for "How To Check If Python Script Is Being Called Remotely Via Ssh"