生产实践:
用于获取节点和机器信息,输出结果用表格打出
脚本内容:
PrettyTable 是用于生成简单 ASCII 表的 Python 库。 它的灵感来自 PostgreSQL shell psql 中使用的 ASCII 表。 我们可以控制表格的许多方面,例如列填充的宽度,文本的对齐方式或表格边框。 我们可以对数据进行排序。我们还可以选择在最终输出中将显示哪些列和行。 PrettyTable 可以从 CSV,HTML 或数据库光标读取数据,并以 ASCII 或 HTML 输出数据。
使用prettytable可以让脚本的输出更简洁,漂亮。脚本内容如下:
#!/usr/bin/env python3
# -*- coding: utf-8 -*-
# @Time : 2019-09-04
# @Author : Anzhihe
# @Site : https://chegva.com
# @File : prettytable.py
import requests
import json
import sys
import prettytable as pt
import argparse
headers = {
'Accept': "application/json, text/javascript, */*; q=0.01",
'Referer': "http://chegva.com/static/index.html",
'X-Requested-With': "XMLHttpRequest",
'User-Agent': "Mozilla/5.0 (Macintosh; Intel Mac OS X 10_14_5) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/76.0.3809.100 Safari/537.36",
'cache-control': "no-cache",
'Connection': "keep-alive",
'Cookie': "yourcookie"
}
class Pdl:
arr = []
arr_su = []
arr_port = []
arr_level = []
arr_creator = []
arr_updated = []
def __init__(self):
pass
def get_host(host):
url = "http://chegva.com/api/v1/xxx/list"
querystring = {"hostnames": host}
response = requests.request("GET", url, headers=headers, params=querystring)
list_host = json.loads(response.text)
for n, host in enumerate(list_host):
tb.add_row([ host["hostname"], host["ip"], '\n'.join(host["nsList"])])
for tree in list_host[0]['nsList']:
Pdl.get_tree(host, tree)
tb.add_column('level',["\n".join('%s' %id for id in Pdl.arr_level)])
tb.add_column('su',["\n".join('%s' %id for id in Pdl.arr_su)])
tb.add_column('status',["\n".join('%s' %id for id in Pdl.arr)])
if any(Pdl.arr_port):
tb.add_column('port',["\n".join('%s' %id for id in Pdl.arr_port)])
if any(Pdl.arr_creator):
tb.add_column('last_deploy',["\n".join('%s' %id for id in Pdl.arr_creator)])
if any(Pdl.arr_updated):
tb.add_column('last_updated',["\n".join('%s' %id for id in Pdl.arr_updated)])
tb.align = "l"
print(tb)
def get_tree(host, treepath):
url = "http://chegva.com/api/xxx/info"
querystring = {"ns": treepath}
response = requests.request("GET", url, headers=headers, params=querystring)
treeinfo = json.loads(response.text)
parent_tree = treeinfo['parent']
Pdl.arr_su.append(treeinfo['su'])
Pdl.arr_level.append(treeinfo['serviceLevel'])
Pdl.arr_port.append(treeinfo['port'])
Pdl.get_deploy_info(parent_tree)
for key in treeinfo.keys():
if key == treeinfo['serviceLevel']:
print(treeinfo[key])
col_list = treeinfo[key].split()
print(col_list)
Pdl.arr_su.append(treeinfo[key].split())
url1 = "http://chegva.com/api/v3/xxx/query"
querystring1 = {"su": treeinfo['su']}
response = requests.request("GET", url1, headers=headers, params=querystring1)
hosts = json.loads(response.text)
host_info = ['hostname', 'ip', 'code_msg']
a = []
for i in hosts['instances']:
for key,value in i.items():
if key in host_info:
a.append(value)
idx = a.index(host['hostname'])
Pdl.arr.append(a[idx+2])
def show_tree(treepath):
url = "http://chegva.com/api/v1/xxx/info"
querystring = {"ns": treepath}
response = requests.request("GET", url, headers=headers, params=querystring)
treeinfo = json.loads(response.text)
parent_tree = treeinfo['parent']
Pdl.get_deploy_info(parent_tree)
tree_info = ['su', 'port', 'serviceLevel', 'name']
for key in treeinfo.keys():
if key in tree_info:
col_list = treeinfo[key].split(' ',0)
if any(col_list):
tb1.add_column(key,col_list)
Pdl.show_host(treeinfo['su'])
if any(Pdl.arr_creator):
tb1.add_column('last_deploy',["\n".join('%s' %id for id in Pdl.arr_creator)])
if any(Pdl.arr_updated):
tb1.add_column('last_updated',["\n".join('%s' %id for id in Pdl.arr_updated)])
tb1.align = "l"
print(tb1)
def show_host(su):
url = "http://chegva/api/v3/xxx"
querystring = {"su": su}
response = requests.request("GET", url, headers=headers, params=querystring)
hosts = json.loads(response.text)
host_info = ['hostname', 'ip', 'code_msg']
a = []
step = 3
for i in hosts['instances']:
for key,value in i.items():
if key in host_info:
a.append(value)
b = [ a[i:i+step] for i in range(0,len(a),step)]
tb1.add_column('host',["\n".join('%s' %id for id in b)])
def get_deploy_info(parent_tree):
url = "http://chegva.com/deploy/jobs/all/json"
querystring = {"limit":"1","ns": parent_tree}
response = requests.request("GET", url, headers=headers, params=querystring)
deployinfo = json.loads(response.text)
if deployinfo['data']:
Pdl.arr_creator.append(deployinfo['data'][0]['creator'])
if deployinfo['data']:
Pdl.arr_updated.append(deployinfo['data'][0]['updated'].split()[0])
if __name__ == '__main__':
parser = argparse.ArgumentParser(description="Query info of host or service tree")
parser.add_argument('para', nargs='+',
help='hostname | treepath')
args = parser.parse_args()
host_tree = args.para[0]
tb = pt.PrettyTable()
tb.field_names = [ "主机名", "IP", "节点列表"]
tb.align = "l"
tb.padding_width = 0
tb1 = pt.PrettyTable()
tb1.align = "l"
tb1.padding_width = 0
pdl = Pdl()
if str(host_tree).endswith('.com'):
Pdl.show_tree(host_tree)
else:
Pdl.get_host(host_tree)◎查看效果
参考:
