当使用Python Paramiko exec_命令执行时,某些Unix命令失败,并出现“<command>notfound”

2024-07-04 05:40:46 发布

您现在位置:Python中文网/ 问答频道 /正文

我试图在Paramikoexec_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)

Tags: test命令hostparamikoportstdinstdoutusername
1条回答
网友
1楼 · 发布于 2024-07-04 05:40:46

默认情况下,SSHClient.exec_command不会在“登录”模式下运行shell,也不会为会话分配伪终端。因此,与常规交互式SSH会话(特别是对于非交互式会话,.bash_profile没有来源)相比,您(可能)获得了一组不同的启动脚本。和/或根据TERM环境变量的缺失/存在,在脚本中采取不同的分支

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

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

     /bin/sesu test
    

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

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

  3. 尝试通过登录shell显式运行脚本(对公共*nix shell使用 login开关):

     bash  login -c "sesu test"
    
  4. 如果命令本身依赖于特定的环境设置,并且无法修复启动脚本,则可以在命令本身中更改环境。其语法取决于远程系统和/或shell。在通用*nix系统中,此功能可以:

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

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

    使用伪终端自动执行命令可能会带来严重的副作用。参见示例Is there a simple way to get rid of junk values that come when you SSH using Python's Paramiko library and fetch output from CLI of a remote machine?


您可能在LD_LIBRARY_PATH和定位共享对象方面有类似的问题


另见:

相关问题 更多 >

    热门问题