运维前线:一线运维专家的运维方法、技巧与实践2.4 如何利用Python获取Facts
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的信息进行集中处理。
相关文章
- 为什么我从Python转战到Node.js
- Python迭代和迭代器详解
- 重新认识生成器Generator
- 为什么用 Java:一个 Python 程序员告诉你
- 如何利用Python打造出适合自己的定制化Eclipse IDE?
- 手机超强Python编程神器,在手机上运行Python
- 四款工具顺利实现Python与JavaScript间的代码转换
- 深入解读Python解析XML的几种方式
- 打造自己的 Python 编码环境
- 深入理解立即执行函数
- Switch ... Case 语法你支不支持?
- 只需一行代码,就能导入所有的Python库?
- Python 3.10来了,switch语法终于出现
- Python 程序员最常犯的十个错误
- 学好 Python 的 11 个优秀资源
- 奇门武功:如何实现代码热更新
- Python中eval带来的潜在风险
- 7 款 Python 可视化工具对比
- 一篇文章带你了解Python运算符重载
- 复制并输出一个“数组”,Python 和 C++ 分别需要几步?