目标效果:

[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()

最新文章

  1. Unity5 AssetBundle
  2. 10条建议提高PHP代码性能
  3. VC++ 模块与资源分离
  4. linux下实时监测tomcat关闭并启动
  5. Fastreport使用经验(转)在Delphi程序中访问报表对象
  6. 对石家庄铁道大学官网UI设计的分析
  7. c# js调用AjaxPro方法出错解析
  8. UVa11235 RMQ
  9. 读【10问PHP程序员】 有感
  10. 开启IIS Express可以调试X64项目
  11. 关于CentOS
  12. 2018-软工机试-F-庙会
  13. hibernate框架学习第五天:数据查询、投影等
  14. dojo.js --dojo Quick Start/dojo入门手册1
  15. HDU 5583 Kingdom of Black and White(暴力)
  16. Java堆外内存管理
  17. 在MySQL中创建cm-hive使用的数据库及账号
  18. web应用配置虚拟路径映射方式一配置不成功问题解决办法
  19. Shell笔记-03
  20. TED_Topic3:The hidden reason for poverty the world needs to address now

热门文章

  1. 集合框架二(Collection接口实现类常用遍历方法)
  2. js-对象深度克隆方法
  3. 关于Mysql数据库的知识总结
  4. SAP FI/CO 基本概念
  5. 分享一个 jsPDF的简单使用以及中文编码问题的解决
  6. Java java jdk在Linux下安装与环境变量的配置
  7. 【jdk源码2】Objects源码学习
  8. 耐克的定制页用canvas如何实现....跪求前端大神指点。
  9. MySQL 命令行操作集合
  10. Spark job 部署模式