python 通过ansible 获取服务器基本信息:

  1. 利用ansible的 setup 模块可以返回服务器的详细信息

 所有的信息都是以字典的格式显示的

[root@e tmp]# ansible 192.168.137.152 -m setup 
192.168.137.152 | SUCCESS => {
    "ansible_facts": {
        "ansible_all_ipv4_addresses": [
            "192.168.137.152", 
            "192.168.137.156", 
            "172.17.42.1", 
            "192.168.122.1"
        ], 
        "ansible_all_ipv6_addresses": [
            "fe80::20c:29ff:fe29:eb74", 
            "fe80::20c:29ff:fe29:eb7e", 
            "fe80::1c62:8ff:fe8d:e9a2"
        ], 
        "ansible_architecture": "x86_64"
      ..........



2.利用subprocess模块执行命令,获取数据Disk、Memory、cpu等基础信息

#!/usr/bin/env python
#coding:utf-8
import json
import shlex
from subprocess import *


def server_info(ip):
  cmd = "/usr/bin/ansible {ip} -m setup".format(ip=ip)
  raw_info = subprocess.check_output(shlex.split(cmd))  #  check_output函数在python2.7以后版本才存在
  base_info = json.loads(raw_info.split('=>')[1])['ansible_facts']
  cpu = base_info['ansible_processor_vcpus']
  memory = round(int(base_info['ansible_memtotal_mb'])/1024.0,1)
  disk_info = base_info['ansible_devices']
  disk_volume = sum([int(disk_info[disk]['sectors'])*int(disk_info[disk]['sectorsize']) for disk in disk_info])/1024**3
  hostname = base_info['ansible_hostname']
  os = base_info['ansible_lsb']['description']
  print cpu,memory,disk_info,disk_volume,hostname,os
if __name__=="__main__":
  ip = "192.168.137.152"
  sever_info(ip)