You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

如何使用parallel-ssh在SFTP中列出目录文件?执行ls命令失败

解决SFTP服务器无法执行ls命令的问题

问题原因

你用run_command('ls')失败是因为SFTP服务器通常只启用了SFTP子系统,没有开放shell命令执行权限,服务器会直接拒绝你的shell通道请求,所以抛出ChannelRequestDenied错误。而copy_remote_file能正常工作,是因为它走的是SFTP协议的文件传输通道,和shell命令不是一回事。

正确的目录列表获取方法

别用shell命令,直接用pssh的SFTP功能来读取目录内容,示例代码如下:

import pssh.clients, pssh.utils

pssh.utils.enable_logger(pssh.utils.logger)
hosts = OPT['ftp']['host']
client = pssh.clients.SSHClient(hosts, port=OPT['ftp']['port'], user=OPT['ftp']['user'], password=OPT['ftp']['pass'])

# 开启SFTP会话
sftp = client.open_sftp()

# 列出远程目录内容,替换成你要查看的实际路径
remote_target_dir = '.'  # 示例:当前登录目录
file_names = sftp.listdir(remote_target_dir)
print("目录文件列表:", file_names)

# 如果需要更详细的文件信息(权限、大小、修改时间等),用listdir_attr
detailed_file_info = sftp.listdir_attr(remote_target_dir)
for file_item in detailed_file_info:
    print(f"文件名:{file_item.filename} | 权限:{file_item.permissions} | 文件大小:{file_item.size} | 修改时间:{file_item.mtime}")

# 用完记得关闭SFTP会话
sftp.close()

# 原有的文件复制功能不受影响,可以正常使用
cmds = client.copy_remote_file('1223d_ca.zip', '/dev/shm/hi.zip')

补充说明

  • listdir()只返回文件名列表,适合快速查看目录下有哪些文件
  • listdir_attr()返回包含文件元数据的对象,适合需要获取文件详细信息的场景
  • 确保你指定的远程路径是SFTP服务器允许访问的,避免出现权限不足的问题

内容的提问来源于stack exchange,提问作者Diego Alonso

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.07.28 13:28:12