目标效果:

[root@ansible ~]# python query.py --list
{
"test": [
  "10.1.2.1",
  "10.1.2.2"
],
"www": [
  "1.2.3.4",
  "5.6.7.8"
]
}

[root@ansible ~]# python query.py --host 5.6.7.8
{
  "ansible_group": "www",
  "ansible_host": "5.6.7.8"
}

代码:

[root@ansible ~]# cat query.py
#!/usr/bin/python
# -*- coding: utf-8 -*-
#author: xiaoweige
import json
import pymysql
import argparse
from contextlib import contextmanager
from collections import defaultdict

#todo: parse the given --list without arg but --host '10.1.2.2'
def parse_args():
  parser = argparse.ArgumentParser(description='--list or --host 10.1.2.2')
  parser.add_argument('--list',action='store_true',help='--list without args')
  parser.add_argument('--host',help='--host 10.1.2.2')
  args = parser.parse_args()
  return args
#todo: to dump the dict into json
def to_json(indict):
  return json.dumps(indict,indent=3)
#todo: create a connection to the mysql
@contextmanager
def get_conn(**kwargs):
    conn = pymysql.connect(**kwargs)
    try:
      yield conn
    finally:
      conn.close()

#todo: list all the host
def get_all_list(conn):
  hosts = defaultdict(list)
  with conn as cur:
    cur.execute('select * from yunwei.hosts ' )
    rows = cur.fetchall()
    for no,host,group,user,port in rows:

      hosts[group].append(host)
  return hosts

#todo: query all details of a given hosts
def get_all_detail(conn,host):
  details = {}
  with conn as cur:
    cur.execute("select * from yunwei.hosts where host='{0}'".format(host))
    rows = cur.fetchall()
    for row in rows:
      no,host,group,user,port = row
      details.update(ansible_host=host,ansible_group=group)
  return details
#todo: define main function
def main():
  parser = parse_args()
  with get_conn(host='10.1.1.36',user='root',password='za5121101112az',port=3306) as conn:
    if parser.list:
      hosts = get_all_list(conn)
      print to_json(hosts)
    else:
      details = get_all_detail(conn,parser.host)
      print to_json(details)
if __name__ == '__main__':
  main()

从CMDB动态获取服务器列表,按照Ansible的约定的更多相关文章

  1. Zookeeper动态更新服务器列表

    -------------------------------------------------------------------------------------- [版权申明:本文系作者原创 ...

  2. diamond源码阅读-获取服务器列表

    serverAddressProcessor public synchronized void start() { if (isRun) { return; } isRun = true; initH ...

  3. Ansible 动态获取主机列表

    参考文献: http://www.linuxidc.com/Linux/2016-12/138111.htm 附加 这个 include_vars 变量,可以 动态分别环境或者其他条件- hosts: ...

  4. 【CMDB】获取服务器数据

    一.通过agent的方式 原理:服务器定制执行py文件通过subprocess模块采集数据发送给数据收集的机器 数据收集的机器:192.168.11.62 服务器:192.168.11.169 数据收 ...

  5. 通过zabbix的API接口获取服务器列表

    Zabbix API说明 1) 基于Web的API,作为Web前端的一部分提供,使用JSON-RPC 2.0协议 2) 身份认证Token:在访问Zabbix中的任何数据之前,需要登录并获取身份验证令 ...

  6. c# json转换成dynamic对象,然后在dynamic对象中动态获取指定字符串列表中的值

    using Newtonsoft.Json;using System;using System.Collections.Generic;using System.Linq;using System.T ...

  7. dedecms Ajax异步获取文章列表

    dedecms如何通过ajax(异步)动态获取文章列表数据. 第一步添加:服务端(PHP)代码 打开plus目录下面的list.php文件,在12行代码下面添加以下代码: if(isset($_GET ...

  8. Ajax 学习之动态获取,返回服务器的值

    <%@ page language="java" contentType="text/html; charset=UTF-8" pageEncoding= ...

  9. 解决使用IIS5.0配置的FTP服务器,客户端浏览器访问时无法获取目录列表的问题。

    我在windows xp sp3下利用iis构架了FTP服务器,允许且只允许匿名用户登陆.但刚开始配置好后,不管是使用命令行模式还是使用浏览器都发现无法访问. 于是怀疑防火墙屏蔽端口所致,果不其然,在 ...

随机推荐

  1. POJ3261(SummerTrainingDay10-G 后缀数组)

    Milk Patterns Time Limit: 5000MS   Memory Limit: 65536K Total Submissions: 15974   Accepted: 7041 Ca ...

  2. CSS 水平居中和垂直居中

    1.水平居中——行内元素 text-align: center; 2.水平居中——定宽块状元素 margin: auto,满足定宽和块状两个条件的元素是可以通过设置“左右margin”值为“auto” ...

  3. js-ES6学习笔记-数值的扩展

    1.ES6 提供了二进制和八进制数值的新的写法,分别用前缀0b(或0B)和0o(或0O)表示. 2.如果要将0b和0o前缀的字符串数值转为十进制,要使用Number方法. 3.ES6在Number对象 ...

  4. framework7中a标签没反应

    试试在a标签上加这个样式: class="external"

  5. C#与java中的AES加解密互解算法

    一.C#版AES加解密算法 public class AESCode { public string Key { get; set; } public string Encrypt(string va ...

  6. Cookie、Session 和 Token区别

    1 Cookie.Session 和 Token 都是用来做持久化处理的,目的就是让客户端和服务端相互认识.Http 请求默认是不持久的没有状态的,谁也不认识谁.   2 Cookie: 是存放在客户 ...

  7. Vue.js入门系列(一)

    Vue官网: https://cn.vuejs.org/v2/guide/forms.html#基础用法 [入门系列] (一)  http://www.cnblogs.com/gdsblog/p/78 ...

  8. Android Monkey的使用

    转载请标明出处:http://blog.csdn.net/zhaoyanjun6/article/details/71750907 本文出自[赵彦军的博客] 什么是 Monkey Monkey 是一个 ...

  9. 【Python】TypeError: a bytes-like object is required, not 'str'解决

    对所使用的字符串类型调用encode()方法进行转换即可

  10. windows7环境下使用pip安装MySQLdb for python3.7

    1.首先,需要确定你已经安装了pip.在Python2.7的安装包中,easy_install.py和pip都是默认安装的.可以在Python的安装目录先确认,如果\Python37\Scripts里 ...