我试图在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)
默认情况下,
SSHClient.exec_command
不会在“登录”模式下运行shell,也不会为会话分配伪终端。因此,与常规交互式SSH会话(特别是对于非交互式会话,.bash_profile
没有来源)相比,您(可能)获得了一组不同的启动脚本。和/或根据TERM
环境变量的缺失/存在,在脚本中采取不同的分支可能的解决方案(按优先顺序):
修复命令,使其不依赖于特定环境。在命令中使用
sesu
的完整路径。例如:如果您不知道完整路径,在通用*nix系统上,可以在交互式SSH会话中使用
which sesu
命令修复启动脚本,将交互式和非交互式会话的
PATH
设置为相同尝试通过登录shell显式运行脚本(对公共*nix shell使用
login
开关):如果命令本身依赖于特定的环境设置,并且无法修复启动脚本,则可以在命令本身中更改环境。其语法取决于远程系统和/或shell。在通用*nix系统中,此功能可以:
另一种(不推荐)方法是使用
get_pty
参数强制为“exec”通道分配伪终端:使用伪终端自动执行命令可能会带来严重的副作用。参见示例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
和定位共享对象方面有类似的问题另见:
相关问题 更多 >
编程相关推荐