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

问题描述

Capistrano 3不再使用命令cap env shell

现在我们应该使用cap env console

但是它不是交互式的,例如,我们不能使用箭头键来记录或tab按钮上的自动完成

那我该怎么办?

解决方法

我建议编写自己的小耙子任务来完成。使用readline宝石 首先要感谢以下材料:

  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,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


做点什么,加油! =))

相关问答

依赖报错 idea导入项目后依赖报错,解决方案:https://blog....
错误1:代码生成器依赖和mybatis依赖冲突 启动项目时报错如下...
错误1:gradle项目控制台输出为乱码 # 解决方案:https://bl...
错误还原:在查询的过程中,传入的workType为0时,该条件不起...
报错如下,gcc版本太低 ^ server.c:5346:31: 错误:‘struct...