0

我需要从远程服务器上的 ruby​​ 脚本中询问用户输入。我设法使用以下代码用 bash 执行它

class ConfirmHandler
  def on_data(command, stream_name, data, channel)
    puts "data received: #{data}"
    if data.to_s =~ /\?$/
      prompt = Net::SSH::Prompt.default.start(type: 'confirm')
      response = prompt.ask "Please enter your response (y/n)"
      channel.send_data "#{response}\n"
    end
  end
end

require 'sshkit'
require 'sshkit/dsl'
include SSHKit::DSL

on '<ssh-server-name>' do |host|
  cmd = <<-CMD
    echo 'Do something?';
    read response;
    echo response=$response
  CMD

  capture(cmd.squish , interaction_handler: ConfirmHandler.new)
end

当我在本地机器上运行这个脚本时,我看到

data received: Do something?
Please enter your response (y/n)
data received: response=y

我尝试将 bash CMD 代码包装到 ruby​​ 脚本中:

on '<ssh-server-name>' do |host|
  cmd = <<-CMD
    ruby -e "
      puts 'Do something?';
      require 'open3';
      response = Open3.capture3('read response; echo $response');
      puts 'response=' + response.to_s;
    "
  CMD

  capture(cmd.squish , interaction_handler: ConfirmHandler.new)
end

并得到以下结果:

data received: Do something?
Please enter your response (y/n)
data received: response=["\n", "", #<Process::Status: pid 9081 exit 0>]

我正在编写上面的代码,查看SSHKit Github 主页上的交互式命令部分

如何在远程服务器上使用 SSKKit 从 ruby​​ 脚本捕获用户响应?

4

1 回答 1

0

我能够使用以下代码从远程服务器上的 ruby​​ 脚本捕获用户响应:

# ask_response.rb

puts 'Do something?';
response = `read response; echo $response`;
puts 'response=' + response.to_s;

ask_response.rb是一个位于远程服务器上的 ruby​​ 脚本。在本地我运行:

on '<ssh-server-name>' do |host|
  capture("ruby ask_response.rb" , interaction_handler: ConfirmHandler.new)
end
于 2019-02-02T10:59:47.023 回答