Capistrano 3 在远程服务器上执行任意命令

Capistrano 3 execute arbitrary command on remote server

Capistrano 3 不再使用命令 cap env shell

现在我们应该使用cap env console

但它不是交互式的,我们不能在 tab 按钮

上使用箭头键进行历史记录或自动完成

那我该怎么办?

我建议编写您自己的小 rake 任务来完成它。使用 readline gem 首先感谢以下资料:

  1. https://thoughtbot.com/blog/tab-completion-in-gnu-readline-ruby-edition

  2. How to write a Ruby command line app that supports tab completion?


desc "Remote console" 
task :console do
  require 'readline'
  # https://thoughtbot.com/blog/tab-completion-in-gnu-readline-ruby-edition

  host_args = (ENV['HOSTS'] || '').split(',').map { |r| r.to_sym }
  role_args = (ENV['ROLES'] || '').split(',').map { |r| r.to_sym }

  LIST = `ls /usr/bin`.split("\n").sort + `ls /bin`.split("\n").sort

  comp = proc { |s| LIST.grep(/^#{Regexp.escape(s)}/) }

  Readline.completion_append_character = " "
  Readline.completion_proc = comp

  while line = Readline.readline('cap> ', true)
    begin
      next if line.strip.empty?
      exec_cmd(line, host_args, role_args)
    rescue StandardError => e
      puts e
      puts e.backtrace
    end
  end
end

def exec_cmd(line, host_args, role_args)
  line = "RAILS_ENV=#{fetch(:stage)} #{line}" if fetch(:stage)
  cmd = "bash -lc '#{line}'"
  puts "Final command: #{cmd}"
  if host_args.any?
    on hosts host_args do
      execute cmd
    end
  elsif role_args.any?
    on roles role_args do
      execute cmd
    end
  else
    on roles :all do
      execute cmd
    end
  end
end


随心所欲,干杯! =))