当使用 Python Paramiko exec_command 执行时,某些 Unix 命令失败并显示“<command> 未找到”

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

我正在尝试在 Paramiko exec_command 的帮助下从 Python 在 Unix 服务器中执行 运行 sesu 命令。但是,当我 运行 执行此命令 exec_command('sesu test') 时,我得到

sh: sesu: not found

当我运行宁简单ls命令它给了我想要的输出。只有 sesu 命令不能正常工作。

我的代码是这样的:

import paramiko

host = host
username = username
password = password
port = port

ssh=paramiko.SSHClient()
ssh.set_missing_host_key_policy(paramiko.AutoAddPolicy())
ssh.connect(ip,port,username,password)
stdin,stdout,stderr=ssh.exec_command('sesu test')
stdin.write('Password')
stdin.flush()
outlines=stdout.readlines()
resp=''.join(outlines)
print(resp)

默认情况下SSHClient.exec_command不会运行 shell处于“登录”模式并且不会为会话分配伪终端。因此,与您的常规交互式 SSH 会话(特别是对于非交互式会话,.bash_profile 未被获取)相比,(可能)获取了一组不同的启动脚本。 And/or 根据 absence/presence 的 TERM 环境变量,采用脚本中的不同分支。

可能的解决方案(按优先顺序):

  1. 修复命令不依赖于特定环境。在命令中使用 sesu 的完整路径。例如:

    /bin/sesu test
    

    如果您不知道完整路径,在常见的 *nix 系统上,您可以在交互式 SSH 会话中使用 which sesu 命令。

  2. 修复您的启动脚本,为交互式和非交互式会话设置相同的PATH

  3. 通过登录 shell 尝试 运行 显式地使用脚本(使用 --login 开关与通用 *nix shells):

    bash --login -c "sesu test"
    
  4. 如果命令本身依赖于特定的环境设置并且您无法修复启动脚本,则可以在命令本身中更改环境。那取决于远程系统的语法 and/or shell。在常见的 *nix 系统中,这有效:

    PATH="$PATH;/path/to/sesu" && sesu test
    
  5. 另一种(不推荐)方法是使用 get_pty 参数强制为“exec”通道分配伪终端:

    stdin,stdout,stderr = ssh.exec_command('sesu test', get_pty=True)
    

    使用伪终端自动执行命令会给您带来严重的副作用。例如参见 [​​=23=]


您可能对 LD_LIBRARY_PATH 和查找共享对象有类似的问题。


另请参阅: