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

能否通过Capistrano远程执行Dir.glob获取远程服务器目录列表

核心结论

Dir.glob 是Ruby标准库的本地文件系统API,无法直接读取远程服务器的文件结构,你需要先在远程服务器执行命令获取匹配glob规则的目录列表,再做后续下载操作。

修正后的可用代码

desc 'Download generated folders'
task :download_folders do
  # 定义你要匹配的glob规则
  glob_pattern = 'path/*/*'
  remote_folders = []

  # 在远程目标服务器执行命令获取匹配的目录列表
  on roles(:app) do |host|
    # 用bash glob匹配路径,输出结果后转为数组,glob规则放到引号里避免本地提前解析
    raw_output = capture "cd #{fetch(:deploy_to)}/current && ls -d #{glob_pattern} 2>/dev/null || true"
    remote_folders = raw_output.split("\n").reject(&:empty?)

    run_locally do
      remote_folders.each do |p|
        info "Downloading remote folder: #{p}"
        # 本地创建对应目录
        execute :mkdir, '-p', p
        # 用Capistrano内置的download!方法下载,比手动拼scp更稳定、兼容多服务器配置
        download! "#{fetch(:deploy_to)}/current/#{p}/", p, recursive: true
      end
    end
  end
end

注意事项

  • 代码中加2>/dev/null || true是为了避免没有匹配到路径时报错中断任务
  • 如果你的glob规则比较复杂,也可以替换成find命令实现更灵活的匹配,比如要仅匹配文件夹的话可以将捕获命令替换为:capture "cd #{fetch(:deploy_to)}/current && find #{glob_pattern} -type d -maxdepth 0 2>/dev/null || true"

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.10.01 02:48:02