【问题标题】:What is the proper way to input options from a file? | Ruby Scripts从文件中输入选项的正确方法是什么? |红宝石脚本
【发布时间】:2014-02-15 11:41:12
【问题描述】:

我正在尝试编写一个脚本,该脚本将从主机文件中获取 IP 地址,并从配置文件中获取用户名信息。我显然没有将文件名作为正确的哈希/值。

我的File.new(options[:config_file], 'r').each { |params| puts params } 应该打什么电话?我也尝试过当前设置的内容,并且

File.new(config_file, 'r').each { |params| puts params }File.new(:config_file, 'r').each { |params| puts params } 没有运气。

我应该一起做一些不同的事情吗?喜欢load(filename = nil)

options = {}

opt_parser = OptionParser.new do |opt|
  opt.banner = 'Usage: opt_parser COMMAND [OPTIONS]'
  opt.on('--host_file','I need hosts, put them here') do |host_file|
    options[:host_file] = host_file
  end
  opt.on('--config_file', 'I need config info, put it here') do |config_file|
    options[:config_file] = config_file
  end
  opt.on('-h', '--help', 'What your looking at') do |help|
    options[:help] = help
    puts opt
  end
end

opt_parser.parse!

if options[:config_file]
  File.new(options[:config_file], 'r').each { |params| puts params }
end

if options[:host_file]
  File.new(options[:host_file], 'r').each { |host| puts host }
end

【问题讨论】:

  • 您的文件是什么格式的?我会像这样直接使用 YAML 或 CSV。 YAML 为您提供哈希。从 CSV 你可以得到一个哈希值。
  • 现在只是标准的 txt 文件,但我对选项持开放态度。主机文件只是 IP 地址(或主机名),每行一个。配置文件是用户名=un,密码=pw,每行一个。我也不喜欢将密码存储在明文文件中,但我不确定在这方面我还能做什么。

标签: ruby


【解决方案1】:

解析主机文件

您可以编写自己的解析器或使用已经实现的 gem。

使用"hosts" gem的示例:(需要安装)

require 'hosts'

hosts = Hosts::File.read('/etc/hosts')

entries = hosts.elements.select{ |element| element.is_a? Hosts::Entry }
addresses = Hash[entries.map{ |entry| [entry.name, entry.address] }]

# You should get a hash of entry names and addresses
# {"localhost"=>"127.0.0.1", "ip6-localhost"=>"::1"}

解析配置文件

存储配置的常用方法是使用 YAML 文件。

考虑以下 YAML 文件(在 '/tmp/config.yml' 中):

username: foo
password: bar

你可以使用YAML module解析这个配置文件:

require 'yaml'

config = YAML.load_file('config.yml')

# You should get a hash of config values
# {"username"=>"foo", "password"=>"bar"}

如果您不希望密码以纯文本形式存储在配置文件中,您可以:

  • 如果您的上下文允许,请在运行时询问密码
  • 使用环境变量存储密码并在运行时检索它

编辑
如果您只需要从文本文件中提取主机名,考虑到每行一个主机名,您可以使用 hostnames = IO.readlines("config.yml").map{ |line| line.chomp } 之类的东西来获取一组主机名。您可以在遍历此数组后进行操作。

www.ruby-doc.org/core-2.1.0/IO.html#method-i-readline

【讨论】:

  • 感谢Parsing the config file 示例,这很有帮助。至于hosts 文件部分,我没有使用operating system's host files,而是一个每行都有IP 地址的文件(可以是任何名称)。我想在下面的脚本session = Net::SSH.start(@hostname, @username, :password => @password, :encryption => 'aes256-cbc', :host_key => 'ssh-rsa') 中使用每一行作为@hostname
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2013-10-17
  • 1970-01-01
  • 2019-06-22
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多