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

时间:2014-09-22 09:06:34

标签: ruby linux operating-system platform

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

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

3 个答案:

答案 0 :(得分:3)

正如评论部分所指出的那样,似乎没有确定的"在每个发行版中都有效。"这样做的方式。以下是我用来检测脚本正在运行的环境类型的内容:

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,尽管它们是两个完全不同的野兽。此外,即使只有一些发行版,它也是一个非常意大利面。但它可能是人们可以建立起来的东西。

您可以从 source code Facter找到更完整的分布式检测示例,其中包括将事实提供给配置管理系统Puppet

答案 1 :(得分:1)

Linux发行版是软件的集合,通常可以通过其软件包管理器,窗口系统,窗口管理器和桌面环境加以区分。那是很多可互换的部分。如果系统保留了程序包管理器,但更改了窗口系统和桌面环境,我们是否将其称为新发行版?没有确定的答案,因此各种工具将给出略有不同的答案。

Train 拥有whole hierarchy个发行系列,可能是其中最复杂的发行版。快速比较Train和Ohai is here。它设计为可以通过网络连接运行,但在本地也可以正常运行,如下所示:

# gem install train
Train.create('local').connection.os[:name] #=> eg. "centos", "linuxmint"
Train.create('local').connection.os[:family] #=> eg. "redhat", "debian"

Facter osfamily fact返回,例如Ubuntu的“ Debian”。使用Facter,检索事实的一般形式为Facter[factname].value

# gem install facter
require 'facter'
puts Facter['osfamily'].value

Ohai platform事实返回,例如"debian" for Ubuntu和CentOS的“ rhel”。对于Ohai,检索事实的一般形式是node[factname]

# gem install ohai
node['platform'] #=> eg. "ubuntu" or "mint"
node['platform_family'] #=> eg. "debian" for Ubuntu and Mint

无法区分平台的Ruby系统信息库

Platform 检索一些基本数据,并且可以很好地区分各种Unix平台。但是,它根本无法处理Linux的不同发行版。 Platform::IMPL将返回:freebsd,:netbsd,:hpux等,但是所有Linux发行版都只是:linux。 sys-uname sysinfo 类似。 utilinfo 更为基本,它将在Windows,Mac和Linux以外的任何系统上失败。

答案 2 :(得分:-1)

require 'facter'

puts Facter['osfamily'].value