我通过终端(在Mac上)连接到SSH,并运行一个Paramiko Python脚本,由于某些原因,这两个会话的行为似乎不同。在这些情况下,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())你知道为什么环境变量不同吗?
我怎么才能修复它呢?
发布于 2015-08-16 03:49:22
使用Channel对象而不是SSHClient对象解决了我的问题。
chan=ssh.invoke_shell()
chan.send('echo $PATH\n')
print (chan.recv(1024))有关更多详细信息,请参阅documentation
发布于 2015-08-12 21:19:32
默认情况下,SSHClient.exec_command不会为会话分配伪终端。因此,一组不同的启动脚本是(可能是)来源的(特别是对于非交互式会话,.bash_profile不是来源)。和/或基于TERM环境变量的缺失/存在而采用脚本中的不同分支。
要使用ssh模拟默认的Paramiko行为,请使用-T开关:
ssh -T myuser@host请参阅ssh man
-T禁用伪tty分配。
相反,要使用Paramiko模拟默认的ssh行为,请将exec_command的get_pty参数设置为True
def exec_command(self, command, bufsize=-1, timeout=None, get_pty=False):不过,您应该更好地修复启动脚本,为所有会话设置相同的PATH,而不是通过在Paramiko中分配伪终端来解决此问题。
有关这一点,请参阅Some Unix commands fail with " not found", when executed using Python Paramiko exec_command。
https://stackoverflow.com/questions/31964108
复制相似问题