首页 » Python » python3 高级篇 » 正文

CMDB_salt-api参数请求等

具体的项目目录结构如下:

mark

目录详情:

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

settings.py

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.171.173:8001/"
SALT_USERNAME = 'saltapi'
SALT_PASSWORD = 'XXXXXX'

run.py作为获取资源的主程序,代码如下:

import importlib
import os, sys
BASEDIR = os.path.dirname(os.path.dirname(os.path.abspath(__file__)))
sys.path.append(BASEDIR)        ##将文件path加入环境变量
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)

/func/task/get_data.py

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': '192.168.171.172', 'tgt': 'test.ping'})

/func/task/salt_client.py

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:

    def __init__(self, url, params):        ##定义salt api接口的类,初始化获得token
        self.url = url
        self.username = SALT_USERNAME
        self.password = SALT_PASSWORD
        self.params = params
        self.headers = {        ##设置初始化header头信息
            "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

mem.py

from func.hosts.main import Base              #加载自定义的一个类

class Disk(Base):
    def run(self):
        self.method="cmd.run"
        self.tgt="*"
        self.arg="free -m"

        return {"client":"local", "fun":self.method, "tgt":self.tgt, "arg":self.arg}

cpu.py

from func import Main
Class Cpu(Mian)

    def run(self)
        self.method = 'cmd.run'
        self.tgt = 'hc-02'
        self.agr = 'cat /proc/cpuinfo'
        #print ('run...cpu')

        retrun {'client':'local', 'func':self.method, 'tgt':self.tgt, 'arg':self.arg}

/func/hosts/main.py

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

class Base(object):

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

    def run(self):
        raise NotImplementedError('Not run func')
赞 (0)

发表评论