当使用Python Paramiko exec_命令执行时,某些Unix命令失败,并显示“<command>not found”

2024-07-04 05:29:43 发布

您现在位置: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:29:43

默认情况下,SSHClient.exec_command不会在“登录”模式下运行shell,也不会为会话分配伪终端。因此,与常规的交互式SSH会话相比,源代码是(可能)不同的一组启动脚本(尤其是对于非交互式会话,.bash_profile不是源代码)。和/或脚本中的不同分支将基于TERM环境变量的缺失/存在而执行。在

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

  1. 修正命令不依赖于特定的环境。在命令中使用sesu的完整路径。E、 g.:

    /bin/sesu test
    

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

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

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

    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?


另请参见:

相关问题 更多 >

    热门问题