cmdb之客户端代码及流程总结

前面基本完成了客户端代码的主机参数获取功能,后续需要实现服务端的工具 API,然后通过工具 API将数据保存到数据库。

下面是基于cmdb之客户端代码梳理进行改进的代码示例
/bin/run.py

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
import importlib
import os, sys
BASEDIR = os.path.dirname(os.path.dirname(os.path.abspath(__file__)))
sys.path.append(BASEDIR)
from conf.settings import HOST_FUNC_DIC
from conf.settings import HOST_LI
from func.task.get_data import send_main


for host in HOST_LI:
path = HOST_FUNC_DIC.get(host)
module_path, class_name = path.rsplit('.', maxsplit=1)
module = importlib.import_module(module_path)
disk_class = getattr(module, class_name)

JG = disk_class()
func = JG.run()
# print(func)
JG1 = send_main(func)
print('JG1-->', JG1)

func/hosts/main.py

1
2
3
4
5
6
7
8
9
class Base(object):

def __init__(self):
self.method = ''
self.tgt = ''
self.arg = ''

def run(self):
raise NotImplementedError('Not run')

/func/hosts/mem.py

1
2
3
4
5
6
7
8
9
from func.hosts.main import Base

class Mem(Base):
def run(self):
self.method = 'cmd.run'
self.tgt = '*'
self.arg = 'dmidecode -q -t 17 2>/dev/null'
# free -m|grep Mem |awk -F ' ' '{print $2}'
return {'client': 'local', 'fun': self.method, 'tgt': self.tgt, 'arg': self.arg}

/func/task/get_data.py

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
import requests
import json
try:
import cookielib
except:
import http.cookiejar as cookielib

# 使用urllib2请求https出错,做的设置
import ssl
context = ssl._create_unverified_context()

from func.task.salt_client import SaltApi
from conf.settings import SALT_API_CON

# 使用requests请求https出现警告,做的设置
from requests.packages.urllib3.exceptions import InsecureRequestWarning
requests.packages.urllib3.disable_warnings(InsecureRequestWarning)


def send_main(params):
salt = SaltApi(SALT_API_CON, params)
# print(params)
# salt_client = '*'
# salt_test = 'test.ping'
# salt_method = 'grains.get'
# salt_params = ['ip_interfaces',]
# result2 = salt.salt_command(salt_client, salt_method, salt_params)
# for k, v in params.items():
# fun = v
# tgt = v
# arg = v
result_data = salt.salt_command(params)
# print(result_data)

# 以内存为例,处理数据
JG_dic = {}
for host, value in result_data.items():
if not value:
print(host, '内存信息获取失败,请检查dmidecode工具')
continue
if host not in JG_dic.keys():
JG_dic[host] = {}
memory = 0
li = value.split('\n\t')
print('li-->', li)
for item in li:
if 'Memory Device' in item:
continue
k, v = item.split(':')
if k == 'Size':
num, company = v.rsplit(' ', maxsplit=1)
print('num--->', num)
try:
num = int(num)/1024
except ValueError:
continue
memory += num
JG_dic[host]['memory'] = memory
return JG_dic


if __name__ == '__main__':
send_main({'client': 'local', 'fun': '*', 'tgt': 'test.ping'})

/func/task/salt_client.py

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
import json
import requests
# from conf.settings import SALT_API_CON
from conf.settings import SALT_USERNAME
from conf.settings import SALT_PASSWORD


class SaltApi:
"""
定义salt api接口的类
初始化获得token
"""
def __init__(self, url, params):
self.url = url
self.username = SALT_USERNAME
self.password = SALT_PASSWORD
self.params = params
self.headers = {
"User-Agent": "Mozilla/5.0 (Windows NT 10.0; WOW64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/50.0.2661.102 Safari/537.36",
"Content-type": "application/json"
}
# self.params = {'client': 'local', 'fun': '', 'tgt': ''}
self.login_url = url + "login"
self.login_params = {'username': self.username, 'password': self.password, 'eauth': 'pam'}
# self.token = self.get_data(self.login_url, self.login_params)['token']
self.token = self.get_data(self.login_url, self.login_params).get('token')
self.headers['X-Auth-Token'] = self.token

def get_data(self, url, params):
send_data = json.dumps(params)
request = requests.post(url, data=send_data, headers=self.headers, verify=False)
response = request.json()
result = dict(response)
# print result
return result['return'][0]

def salt_command(self, params):
"""远程执行命令,相当于salt 'client1' cmd.run 'free -m'"""
# if arg:
# params = {'client': 'local', 'fun': method, 'tgt': tgt, 'arg': arg}
# else:
# params = {'client': 'local', 'fun': method, 'tgt': tgt}
result = self.get_data(self.url, params)
return result

Recommended Posts