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