zoukankan      html  css  js  c++  java
  • 从CMDB动态获取服务器列表,按照Ansible的约定

    目标效果:

    [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='za5121sbsb2az',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()

  • 相关阅读:
    SDNU 1123.Encoding
    SDNU 1120.ISBN号码
    SDNU 1119.Intelligent IME(水题)
    SDNU 1115.谁拿了最多奖学金(水题)
    解决Docker运行命令时提示"Got permission denied while trying to connect to the Docker daemon socket"类情况
    jupyter notebook修改默认浏览器
    CentOS切换用户命令su or su+username
    图像内插,双线性插值等
    python求最大公约数和最小公倍数
    Python split()方法
  • 原文地址:https://www.cnblogs.com/hixiaowei/p/8540311.html
Copyright © 2011-2022 走看看