cmdb之客户端代码梳理

前面完成了python 调用 salt-api 和批量执行通用类的抽象,下面继续客户端代码的整理

  • 主要需要完成的内容
    区分不同的 disk, cpu, mem 等参数,通过传递不同的参数给 salt-api 并获取数据

新建项目 cmdb_client_demo,新建应用 demo02,项目目录结构如下



cmdb-client-demo1
  • 程序结构说明
    /bin/run.py 程序主入口
    /conf/settings.py 配置文件,用于保存用户名、密码、url 等数据
    /func/hosts/.py 定义各个参数获取的方法
    /func/task/
    .py 调用 salt-api 执行命令

代码示例
/bin/run.py

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
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()
JG1 = send_main(func)

/conf/settings.py

1
2
3
4
5
6
7
8
9
10
11
12
13
HOST_FUNC_DIC = {
'disk': 'func.hosts.disk.Disk',
'mem': 'func.hosts.mem.Mem',
'cpu': 'func.hosts.cpu.Cpu',
'os': 'func.hosts.os.Os',
'ip': 'func.hosts.ip.Ip',
}

HOST_LI = ['mem']

SALT_API_CON = "https://192.168.16.2:8001/"
SALT_USERNAME = 'saltapi'
SALT_PASSWORD = 'salt2019'

/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')

说明: main.py 定义基类,该类中定义 run 方法,其余的参数类均继承该类
若其余类未定义 run 方法,则会调用父类的 run 方法,从而给出提示信息
/func/hosts/mem.py

1
2
3
4
5
6
7
8
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'
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
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)
result1 = salt.salt_command()


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
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.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, tgt, method, arg=None):
"""远程执行命令,相当于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