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

Python 2.6用Paramiko通过glob匹配SFTP服务器通配符文件失败求助

问题根源

你遇到的问题很明确:glob.glob()是专门用来扫描本地文件系统的工具,它完全不知道你连接的远程SFTP服务器的文件结构,所以直接用它去匹配远程路径肯定不会有结果。

解决方案

下面给你两种可行的解决思路,你可以根据自己的场景选择:

方案一:用SFTP客户端+fnmatch匹配(推荐,更安全)

这种方法不需要在远程服务器上执行shell命令,完全通过SFTP协议操作,权限要求更低,也更安全。我们可以先通过SFTP列出目标目录的所有文件,再用fnmatch模块筛选符合通配符规则的文件。

修改后的代码如下:

import paramiko
import fnmatch

client = paramiko.SSHClient()
client.set_missing_host_key_policy(paramiko.AutoAddPolicy())
client.connect('hostname', username='test1234', password='test')

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

# 定义要匹配的远程路径模式
path_patterns = ['/home/test/*.txt', '/home/test1/*.file', '/home/check/*.xml']

for pattern in path_patterns:
    # 拆分目录路径和文件名匹配模式
    try:
        dir_path, file_pattern = pattern.rsplit('/', 1)
    except ValueError:
        print(f"无效的路径格式: {pattern}")
        continue
    
    try:
        # 列出远程目录下的所有内容
        remote_items = sftp.listdir(dir_path)
        # 筛选符合通配符的文件
        matched_files = [f"{dir_path}/{item}" for item in remote_items if fnmatch.fnmatch(item, file_pattern)]
        
        for file in matched_files:
            print(file)
    except IOError as e:
        print(f"访问目录 {dir_path} 失败: {str(e)}")

# 关闭连接
sftp.close()
client.close()

代码说明:

  1. 用rsplit('/',1)把每个路径拆分为目录部分和文件名通配符部分,比如/home/test/*.txt会拆成/home/test和*.txt
  2. 通过sftp.listdir()获取目标目录下的所有文件/目录
  3. 用fnmatch.fnmatch()逐个匹配文件名,筛选出符合规则的文件
  4. 增加了异常处理,避免目录不存在或权限不足时程序崩溃

方案二:通过SSH执行远程ls命令

如果你的远程服务器允许执行shell命令,这种方法更简单,直接利用服务器本身的shell通配符解析能力:

import paramiko

client = paramiko.SSHClient()
client.set_missing_host_key_policy(paramiko.AutoAddPolicy())
client.connect('hostname', username='test1234', password='test')

path_patterns = ['/home/test/*.txt', '/home/test1/*.file', '/home/check/*.xml']

for pattern in path_patterns:
    # 执行远程ls命令获取匹配的文件
    stdin, stdout, stderr = client.exec_command(f"ls {pattern}")
    # 读取命令输出并按行拆分
    matched_files = stdout.read().decode().splitlines()
    
    for file in matched_files:
        if file:  # 跳过空行
            print(file)
    
    # 检查命令执行是否有错误
    error_msg = stderr.read().decode().strip()
    if error_msg:
        print(f"处理模式 {pattern} 时出错: {error_msg}")

client.close()

注意事项:

  • 如果路径中包含空格、特殊字符(比如*、?之外的符号),需要对路径进行转义,避免shell解析出错
  • 依赖远程服务器的shell环境,权限要求比SFTP方法高

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.05.20 11:58:30