且构网

分享程序员开发的那些事...
且构网 - 分享程序员编程开发的那些事

如何检查是否通过 ssh 远程调用 python 脚本

更新时间:2023-11-29 15:29:40

您可以通过检查您的环境来判断您是否通过 SSH 被调用.如果您通过 SSH 连接被调用,环境变量 SSH_CONNECTIONSSH_CLIENT 将被设置.您可以测试它们是否已设置,例如:

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" in os.environ:
    # do something

另一种选择,如果您只想坚持使用 sys.stdin.isatty() 的原始方法,那就是为 SSH 连接分配一个伪 tty.通常,如果您只是通过 SSH 进行交互式会话,SSH 会默认执行此操作,但如果您提供命令,则不会.但是,您可以在提供命令时通过传递 -t 标志来强制它这样做:

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

但是,我会告诫你不要做这些.如您所见,尝试根据是否是 TTY 来检测是否应该接受来自 stdin 的输入可能会导致一些令人惊讶的行为.如果用户想要一种在调试某些内容时以交互方式向您的程序提供输入的方式,这也可能会令用户感到沮丧.

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.