且构网

分享程序员开发的那些事...
且构网 - 分享程序员编程开发的那些事

在Ruby中检测Linux发行版/平台

更新时间:2023-11-17 21:50:58

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

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.