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

CMDB_调用salt-api执行命令

#!/usr/bin/env python
# -*- coding: utf-8 -*-
# @Time    : 2019-1-19 20:45
# @Author  : zhdya@zhdya.cn
# @File    : salt_api.py


import requests
import json
try:
    import cookielib
except:
    import http.cookiejar as cookielib

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

# 使用requests请求https出现警告,做的设置
from requests.packages.urllib3.exceptions import InsecureRequestWarning
requests.packages.urllib3.disable_warnings(InsecureRequestWarning)
salt_api = "https://192.168.171.173:8001/"


class SaltApi:
    """
    定义salt api接口的类
    初始化获得token
    """
    def __init__(self, url):        # 初始化saltapi参数
        self.url = url
        self.username = "saltapi"
        self.password = "password"      ##配置时候使用的密码
        self.headers = {        ##模拟Agent的浏览器参数,注意Content-type这个参数,不添加会失败
            "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 = salt_api + "login"         ##做个拼接:https://192.168.171.173:8001/login
        self.login_params = {'username': self.username, 'password': self.password, 'eauth': 'pam'}      ##对登录的参数进行封装,打个包,作为一个变量
        self.token = self.get_data(self.login_url, self.login_params).get('token')      #获取token,调用如下定义的get_data函数,并传入值
        self.headers['X-Auth-Token'] = self.token

    def get_data(self, url, params):
        send_data = json.dumps(params)      # 先将字典 通过json 变成 str格式
        request = requests.post(url, data=send_data, headers=self.headers, verify=False)    #发送请求
        response = request.json()       # 将返回的数据 字符串 str 转成 json格式  response
        # print('AA--->>',response)
        result = dict(response)      # 再转换成字典
        # print('result集合--->', result['return'][0])
        return result['return'][0]      ##返回很多值,其中第一个就是token值,将需要的tokenreturn回去

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

        else:
            #salt内置key,定义params参数(salt固定格式)
            params = {'client':'local', 'fun': method, 'tgt': tgt}
        # print ('命令参数: ', params)
        result = self.get_data(self.url, params)
        # print ('result--->',result)
        return result

def main():
    print ('@@@@@@@@@@@@@@@@@@@@@@@@@')
    print ('开始执行命令')
    salt = SaltApi(salt_api)        #实例化对象
    # print('token-->',salt.token)
    # salt_client = 'python_minion'       # 这里是minion端的ID 多个值可以是 '*'
    salt_client = '*'
    salt_test = 'test.ping'     ## salt  'python_minion' test.ping
    salt_method = 'cmd.run'     ## salt  'python_minion' cmd.run
    salt_params = 'free -h'     ## salt  'python_minion' cmd.run  'free -h'
    # 下面只是为了打印结果好看点
    result1 = salt.salt_command(salt_client, salt_test)     # 传入两个值, 一个是minionID 'python_minion' ,二个是salt执行的命令 'test.ping'
    for i in result1.keys():
        print (i, ': ', result1[i])
    result2 = salt.salt_command(salt_client, salt_method, salt_params)
    for i in result2.keys():
        print (i)
        print (result2[i])
        print


if __name__ == '__main__':
    main()

结果输出:

D:\djangolearn\Scripts\python.exe D:/untitled/demo/salt_api.py
@@@@@@@@@@@@@@@@@@@@@@@@@
开始执行命令
python_master :  True
python_minion :  True
python_master
              total        used        free      shared  buff/cache   available
Mem:           972M        582M        203M        7.6M        186M        210M
Swap:            0B          0B          0B
python_minion
              total        used        free      shared  buff/cache   available
Mem:           974M        154M        662M        7.6M        158M        655M
Swap:            0B          0B          0B

Process finished with exit code 0
赞 (0)

发表评论