zl程序教程

您现在的位置是:首页 >  Python

当前栏目

运维前线:一线运维专家的运维方法、技巧与实践2.4 如何利用Python获取Facts

2023-03-09 22:21:56 时间

2.4 如何利用Python获取Facts


2.4.1 工作原理

通过2.3节的学习可以知道Facts可以获取主机的系统信息,并以K-V形式进行存储,我们只需要处理Puppet Server收集的Agent Facts信息、入库,然后通过Django来读取数据库信息即可,如图2-6所示。

 

图2-6 Facts信息获取流程图

2.4.2 利用Python脚本获取Facts

首先要确定系统中已经安装了Puppet,如果没有,可以从http://yum.puppetlabs.com/下载,并参考https://docs.puppetlabs.com/puppet/latest/reference/install_pre.html进行安装,接下来看看如何通过Python程序来获取Facts信息(注意:下面的程序是查看当前机器的fact信息,下面的这个程序对结果不会做过多的处理,在后面进行CMDB项目的时候将详细讲解fact的数据处理),实例程序facter_message.py的内容如下:

#!/usr/bin/python

# encoding: utf-8

__authors__     = ['LiuYu']

__version__     = 1.0

__date__        = '2015-08-19 14:34:44'

__licence__     = 'GPL licence'

 

# 导入模块

import commands

import re

# 定义一个变量

command = 'facter'

# 定义要打印的列表

show_list = [('fqdn', u'主机名'),

             ('domain', u'域名'),

             ('uptime', u'运行时间'),

             ('operatingsystem', u'系统'),

             ('kernelrelease', u'内核版本'),

             ('ipaddress', u'IP'),

             ('macaddress', u'MAC'),

             ('memorysize_mb', u'内存MB'),

             ('processors', u'CPU'),

             ('blockdevices', u'磁盘'),

]

# 定义一个处理命令的函数

def handle_command_message(command):

    status, content = commands.getstatusoutput(command)

    if status == 0:

        return content

    else:

        return

# 通过函数处理名称,然后打印结果

if __name__ == '__main__':

    result_dict = {}

    result = handle_command_message(command)

    if result:

        for line in result.strip().split('\n'):

            if re.findall('=>', line):

                key, value = line.split('=>', 1)

                result_dict[key.strip()] = value.strip()

        for f_k, f_s in show_list:

            if f_k in result_dict:

                print f_s, ':', result_dict[f_k]

下面我们来运行facter_message.py程序,打印结果:

$ python facter_message.py

主机名 : puppetclient.domain.com

域名 : domain.com

运行时间 : 1 day

系统 : CentOS

内核版本 : 2.6.32-431.1.2.0.1.el6.x86_64

IP: 10.20.122.111

MAC : 00:22:E2:5E:4D:10

内存 MB : 996.48

CPU : {"count"=>1, "models"=>["QEMU Virtual CPU version 1.1.2"], "

磁盘 : sr0,vda,vdb,vdc

通过如上的简单代码就可以将Facts的信息进行集中处理。