【问题标题】:How to run a command on multiple hosts in Ruby using NEXEC如何使用 NEXEC 在 Ruby 中的多个主机上运行命令
【发布时间】:2015-09-11 23:58:48
【问题描述】:

我想在 Ruby 中使用 net/ssh gem 在多台服务器上运行命令。 所有主机名都保存在一个文件中,我从保存的文件中一一读取主机名,并希望使用 NEXEC 执行命令。

例如:对于单个主机,我运行了这个命令

$NEXEC="/data/bladelogic-7.3/bin/nexec"

$INSTANCE=`#{$NEXEC} hostname ls -ltr mypath` 

如何使用 NEXEC 处理多个主机名

下面是我的代码:

require 'rubygems'
require 'net/ssh'
require 'net/ssh/multi'
puts "Enter the username"
@username=gets.chomp

File.open("path for multiple host file names","r") do |s|
s.each_line do |line|
Net::SSH.start(line.chomp,@username) do |ssh|
result=ssh.exec!("ls -ltr")
result1=`#{$NEXEC} line ls -ltr`
puts result
end
end
end

错误:

访问主机行时出错:远程主机未知

【问题讨论】:

    标签: ruby-on-rails ruby ruby-on-rails-4 rubygems server


    【解决方案1】:

    这早就过了,但我刚刚遇到了类似的问题,让我们从这个开始:

    • 你的缩进很糟糕,每个缩进两个空格根据 Ruby Styleguide
    • net/ssh gem 还需要一个类似于 :password => 'your_pass_here' 的密码参数
    • 在 Ruby 中有一个名为 etc 的库,您可以自动获取登录的用户名,这样您就不必输入用户名,只需输入密码
    • Ruby 使用File.read 可以更轻松地读取文件

    建议修改:

    require 'rubygems'
    require 'net/ssh'
    require 'etc'
    
    print "Enter password: "
    @password = gets.chomp #<= You can get rid of the echo so they can't see your keystrokes if you want, see below
    @username = Etc.getlogin
    
    File.read(path/to/file.file) do |s|
      s.each_line do |line|
        Net::SSH.start(line.chomp, @username, :password => @password) do |ssh|
          result = ssh.exec!("ls -la")
          result1=`#{$NEXEC} line ls -ltr`
          puts result
        end
      end
    end
    

    要消除密码的回声,一种方法是使用系统调用:

    system "stty -echo"
    @password = gets.chomp
    system "stty echo"
    

    总是回忆回声,否则您将看不到程序中输入的任何内容。

    【讨论】:

    • 使用read 时要非常小心。它不可扩展,如果您读取的文件大于系统可以处理的文件,它可能会使程序崩溃。
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2018-11-17
    • 2019-10-05
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多