python - 使用 Paramiko 时的环境变量差异

标签 python ssh environment-variables paramiko

我正在通过终端(在 Mac 上)连接到 SSH 并运行 Paramiko Python 脚本,出于某种原因,这两个 session 的行为似乎不同。 PATH 环境变量在这些情况下是不同的。

这是我运行的代码:

import paramiko
ssh = paramiko.SSHClient()
ssh.set_missing_host_key_policy(paramiko.AutoAddPolicy())
ssh.connect('host', username='myuser',password='mypass')
stdin, stdout, stderr =ssh.exec_command('echo $PATH')
print (stdout.readlines())

知道为什么环境变量不同吗?

我该如何解决?

最佳答案

默认情况下,SSHClient.exec_command 不会为 session 分配伪终端。因此,(可能)获取了一组不同的启动脚本(特别是对于非交互式 session ,.bash_profile 未获取)。和/或根据 TERM 环境变量的存在/不存在,采用脚本中的不同分支。


要使用 ssh 模拟默认的 Paramiko 行为,请使用 -T 开关:

ssh -T myuser@host

参见 ssh man :

-T Disable pseudo-tty allocation.


相反,要使用 Paramiko 模拟默认的 ssh 行为,请将 exec_commandget_pty 参数设置为 True:

def exec_command(self, command, bufsize=-1, timeout=None, get_pty=False):

虽然不是通过在 Paramiko 中分配伪终端来解决这个问题,您应该更好地修复您的启动脚本,为所有 session 设置相同的 PATH

请参阅 Some Unix commands fail with "<command> not found", when executed using Python Paramiko exec_command .

关于python - 使用 Paramiko 时的环境变量差异,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/31964108/

相关文章:

python 预期: SSHing then updating the date

java - Ubuntu中如何配置环境变量?

python - 当我未超出速率限制时收到 Github APi 403 错误

python - 如何使用数据生成器训练自动编码器?

java - 如何在远程 Windows 计算机上从 java 运行批处理脚本

swift - 在 Swift 中引用环境变量

environment-variables - 如何在 Sapper 的 template.html 中使用环境变量?

python - Django View 中的 "request"是什么

python - 如何将字符串转换为字典

windows - 在 Windows 上通过 ssh 连接到 Git 失败