在Ruby中检测Linux发行版/平台 [英] Detecting Linux distribution/platform in Ruby

查看:83
本文介绍了在Ruby中检测Linux发行版/平台的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我可以通过几种方式检查正在运行我的Ruby代码的平台的操作系统:

I can check the operating system of the platform that is running my Ruby code in a several ways:

  • RUBY_PLATFORM: https://stackoverflow.com/a/171011/462015
  • RbConfig::CONFIG['host_os']: https://stackoverflow.com/a/13586108/462015

是否可以知道正在运行什么Linux发行版?例如,基于Debian或基于Red Hat的发行版.

Is it possible to know what Linux distribution is running? For example a Debian based or a Red Hat based distribution.

推荐答案

正如上面的注释部分所指出的那样,似乎没有确定在每个发行版中都能工作"的方式.接下来是我用来检测脚本正在什么样的环境中运行的东西:

As pointed above in the comment section, it seems that there is no sure "works in every distribution" way of doing this. What follows is what I've used to detect what kind of an environment a script is being run:

def linux_variant
  r = { :distro => nil, :family => nil }

  if File.exists?('/etc/lsb-release')
    File.open('/etc/lsb-release', 'r').read.each_line do |line|
      r = { :distro => $1 } if line =~ /^DISTRIB_ID=(.*)/
    end
  end

  if File.exists?('/etc/debian_version')
    r[:distro] = 'Debian' if r[:distro].nil?
    r[:family] = 'Debian' if r[:variant].nil?
  elsif File.exists?('/etc/redhat-release') or File.exists?('/etc/centos-release')
    r[:family] = 'RedHat' if r[:family].nil?
    r[:distro] = 'CentOS' if File.exists?('/etc/centos-release')
  elsif File.exists?('/etc/SuSE-release')
    r[:distro] = 'SLES' if r[:distro].nil?
  end

  return r
end

这不是处理地球上每个GNU/Linux发行版的完整解决方案.实际上,远非如此.例如,尽管OpenSUSE和SUSE Linux Enterprise Server是两个完全不同的野兽,但它们没有区别.此外,即使只有几个发行版,这也是一个意大利面条.但这也许是一个可以建立的基础.

This is not a complete solution to handle every GNU/Linux distribution on earth. Far from it, actually. For example it makes no distinction between OpenSUSE and SUSE Linux Enterprise Server, though they are two quite different beasts. Besides, it's quite a spaghetti even with just a few distros. But it might be something one might be able to build on.

您可以从木偶.

You can find a more complete example of distribution detection from the source code of Facter which is used, among other things, to feed facts to a configuration management system Puppet.

这篇关于在Ruby中检测Linux发行版/平台的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆