91超碰碰碰碰久久久久久综合_超碰av人澡人澡人澡人澡人掠_国产黄大片在线观看画质优化_txt小说免费全本

溫馨提示×

溫馨提示×

您好,登錄后才能下訂單哦!

密碼登錄×
登錄注冊×
其他方式登錄
點擊 登錄注冊 即表示同意《億速云用戶服務條款》

通過 Ansible API 獲取主機信息

發布時間:2020-07-08 22:18:10 來源:網絡 閱讀:3665 作者:FanoLi 欄目:編程語言

在我上一篇文章中,編寫了 Ansible Ad-Hoc & Playbook 的 API,上篇文章 https://blog.51cto.com/784687488/2171821
這一篇將使用 Ansible API 獲取主機詳細信息,CMDB系統中最基本的功能

話不多說,還是直接上代碼

# - encoding:utf-8 -

import os
import sys

\# 因為我是在 django 中使用,所以我加上了下面這段代碼。自已測試時不用加
import django
Search_Path = os.path.dirname(os.path.dirname(os.path.dirname(os.path.abspath(__file__))))
sys.path.append(Search_Path)
os.environ.setdefault('DJANGO_SETTINGS_MODULE', 'AutoOPPlatform.settings')
django.setup()

import ansibleAPI
from collections import namedtuple

DEVICES = namedtuple('mount', ['device', 'point', "total_size", "free_size"])

class Resource(object):

def __init__(self, hostname=None, sshport=22, username=None, password=None, **kwargs):

    if hostname:
        self.hostname = hostname
        self.sshport = sshport
        self.username = username
        self.password = password
        self.group = None
    if kwargs:
        self.hostname = None
        self.group = kwargs
    self.info = self._get_info()

def _get_info(self):

    if self.hostname:
        execute = ansibleAPI.AnsibleAPI([dict(hostname=self.hostname, port=self.sshport,
                                              username=self.username, password=self.password)])
        execute.PrivateAdHoc('setup')
        msg = execute.adhoc_result()
        for k in msg.keys():
            if k == 'success' and msg['success']:
                return dict(success=msg['success'])
            elif k == 'unreachable' and msg['unreachable']:
                return dict(error=msg['unreachable'])
            elif k == 'failed' and msg['failed']:
                return dict(error=msg['failed'])
    if self.group:
        execute = ansibleAPI.AnsibleAPI(self.group)
        execute.PrivateAdHoc('setup')
        msg = execute.adhoc_result()
        return msg

def get_info(self):
    return self.info

def get_failed(self):
    return self.info['failed']

def get_unreachable(self):
    return self.info['unreachable']

def get_success(self):
    success = []
    for k in self.info['success']:
        success.append(k)
    return success

def get_hostname(self):
    return self.info['success'][self.hostname]['ansible_facts']['ansible_hostname']

def ip(self):
    return self.info['success'][self.hostname]['ansible_facts']['ansible_default_ipv4']['address']

def netmask(self):
    return self.info['success'][self.hostname]['ansible_facts']['ansible_default_ipv4']['netmask']

def gateway(self):
    return self.info['success'][self.hostname]['ansible_facts']['ansible_default_ipv4']['gateway']

def broadcast(self):
    return self.info['success'][self.hostname]['ansible_facts']['ansible_default_ipv4']['broadcast']

def mac(self):
    return self.info['success'][self.hostname]['ansible_facts']['ansible_default_ipv4']['macaddress']

def memory_cards(self):
    if self.hostname:
        execute = ansibleAPI.AnsibleAPI([dict(hostname=self.hostname, port=self.sshport,
                                              username=self.username, password=self.password)])
        execute.PrivateAdHoc('shell', 'dmidecode -t memory|grep Size|grep MB|wc -l')
        msg = execute.adhoc_result()
        for k in msg.keys():
            if k == 'success' and msg['success']:
                return msg['success'][self.hostname]['stdout']
            elif k == 'unreachable' and msg['unreachable']:
                return 0
            elif k == 'failed' and msg['failed']:
                return 0
    if self.group:
        execute = ansibleAPI.AnsibleAPI(self.group)
        execute.PrivateAdHoc('shell', 'dmidecode -t memory|grep Size|grep MB|wc -l')
        msg = execute.adhoc_result()
        return msg

def memory_total(self):
    return self.info['success'][self.hostname]['ansible_facts']['ansible_memtotal_mb']

def memory_free(self):
    return self.info['success'][self.hostname]['ansible_facts']['ansible_memfree_mb']

def memory_used(self):
    return self.info['success'][self.hostname]['ansible_facts']['ansible_memory_mb']['real']['used']

def swap_total(self):
    return self.info['success'][self.hostname]['ansible_facts']['ansible_swaptotal_mb']

def swap_free(self):
    return self.info['success'][self.hostname]['ansible_facts']['ansible_swapfree_mb']

def swap_used(self):
    return self.info['success'][self.hostname]['ansible_facts']['ansible_memory_mb']['swap']['used']

def memory(self):
    return self.info['success'][self.hostname]['ansible_facts']['ansible_memory_mb']

def cpu_brand_model(self):
    take_repetition = set(self.info['success'][self.hostname]['ansible_facts']['ansible_processor'])
    take_repetition.remove('GenuineIntel')
    if len(take_repetition) == 1:
        return list(take_repetition)[0]
    elif len(take_repetition) == 0:
        return None
    else:
        cpu = ""
        for n in take_repetition:
            cpu = str(cpu) + str(n) + "\n"
        return cpu

def cpu_number(self):
    return self.info['success'][self.hostname]['ansible_facts']['ansible_processor_count']

def cpu_core(self):
    return self.info['success'][self.hostname]['ansible_facts']['ansible_processor_cores']

def cpu_thread(self):
    return self.info['success'][self.hostname]['ansible_facts']['ansible_processor_vcpus']

def kernel(self):
    return self.info['success'][self.hostname]['ansible_facts']['ansible_kernel']

def device(self):
    device_size = dict()
    for dev, info in self.info['success'][self.hostname]['ansible_facts']['ansible_devices'].iteritems():
        if dev != 'sr0':
            device_size.setdefault(dev, info['size'])
    return device_size

def device_number(self):
    return len(self.device())

def device_total_size(self):
    return reduce(lambda x, y: x + y, self.device().values())

def partitions(self):
    partitions = dict()
    for dev, info in self.info['success'][self.hostname]['ansible_facts']['ansible_devices'].iteritems():
        if dev != 'sr0':
            partitions.setdefault(dev, dict())
            for partition, v in info['partitions'].iteritems():
                partitions[dev].setdefault(partition, v['size'])
    return partitions

def mounts(self):

    mount_list = []
    for dev in self.info['success'][self.hostname]['ansible_facts']['ansible_mounts']:
        mount = DEVICES(device=dev['device'], point=dev['mount'],
                          total_size=dev['size_total'], free_size=dev['size_available'])
        mount_list.append(mount)
    return mount_list

def system(self):
    return self.info['success'][self.hostname]['ansible_facts']['ansible_system']

def architecture(self):
    return self.info['success'][self.hostname]['ansible_facts']['ansible_machine']

def distribution(self):
    return "%s %s" % (self.info['success'][self.hostname]['ansible_facts']['ansible_distribution'],
                      self.info['success'][self.hostname]['ansible_facts']['ansible_distribution_version'])

def uuid(self):
    return self.info['success'][self.hostname]['ansible_facts']['ansible_product_uuid']

def vendor(self):
    return self.info['success'][self.hostname]['ansible_facts']['ansible_system_vendor']

def product_name(self):
    return self.info['success'][self.hostname]['ansible_facts']['ansible_product_name']

def serial_number(self):
    return self.info['success'][self.hostname]['ansible_facts']['ansible_product_serial']

if __name__ == '__main__':

host = Resource('10.10.181.132', sshport=20003, username='root', password=123456)
print host.memory_cards()
#hosts = [{'hostname': '10.0.2.6'}, {'hostname': '10.0.2.7'}, {'hostname': '10.0.2.8'}]
#group = Resource(group1=dict(hosts=hosts, vars={}))
#print group.get_failed()
#print group.get_unreachable()
#print group.get_success()
向AI問一下細節

免責聲明:本站發布的內容(圖片、視頻和文字)以原創、轉載和分享為主,文章觀點不代表本網站立場,如果涉及侵權請聯系站長郵箱:is@yisu.com進行舉報,并提供相關證據,一經查實,將立刻刪除涉嫌侵權內容。

AI

武定县| 司法| 宽城| 泸溪县| 凤翔县| 勃利县| 清流县| 兴山县| 新邵县| 吉安县| 文成县| 图们市| 盱眙县| 抚远县| 平遥县| 天柱县| 原平市| 神农架林区| 贡觉县| 金坛市| 隆回县| 玉田县| 建德市| 泌阳县| 武山县| 垣曲县| 磐石市| 长丰县| 德惠市| 井冈山市| 柘城县| 都安| 清原| 革吉县| 西乌| 江永县| 蓝山县| 哈尔滨市| 康保县| 南开区| 白玉县|