• 欢迎访问蜷缩的蜗牛博客 蜷缩的蜗牛
  • 微信搜索: 蜷缩的蜗牛 | 联系站长 kbsonlong@qq.com
  • 如果您觉得本站非常有看点,那么赶紧使用Ctrl+D 收藏吧
  • 本站已开通微信小程序,可以扫描底部二维码关注,或者搜索alongparty!!

Saltstack API


# -*- coding: utf-8 -*-
# @Time    : 2019-04-30 12:00
# @Author  : kbsonlong
# @Email   : kbsonlong@gmail.com
# @Blog    : www.alongparty.cn
# @File    : saltapi.py
# @Software: PyCharm

import requests
import json

import logging
import urllib3
urllib3.disable_warnings()
logging.captureWarnings(True)



class SaltAPI:
    def __init__(self,url,username,password):
        self.__url = url.rstrip('/')
        self.__username = username
        self.__password = password
        self.__token_id = self.token_id()
        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"
            # "Content-type": "application/x-yaml"
        }

    # 登陆获取 token
    def token_id(self):
        params = {'eauth': 'pam', 'username': self.__username, 'password': self.__password}
        headers = {'X-Auth-Token': ''}
        url = self.__url + '/login'
        req = requests.post(url=url,headers=headers,data=params,verify=False)
        content = json.loads(req.text)
        try:
            token = content['return'][0]['token']
            return token
        except KeyError:
            raise KeyError

    #推送请求
    def PostRequest(self, obj, prefix='/'):
        url = self.__url + prefix
        headers = {'X-Auth-Token': self.__token_id}
        if obj:
            data=obj
            req = requests.post(url=url, data=data, headers=headers, verify=False)
        else:
            req = requests.get(url=url, headers=headers, verify=False)
        print(req.text)
        content = json.loads(req.text)
        return content
    #执行命令
    def SaltCmd(self,tgt,fun,client='local',tgt_type='glob',arg=None,**kwargs):
        params = {'client':client, 'fun':fun, 'tgt':tgt, 'tgt_type':tgt_type}
        if arg:
            params['arg']=arg
        if kwargs:
            params=dict(list(params.items())+list(kwargs.items()))
        res = self.PostRequest(params)
        return res
        #{u'return': [{u'jid': u'20160331104340284003', u'minions': [u'saltminion01-41.ewp.com']}]}

    #获取 JOB ID 的详细执行结果
    def SaltJob(self,jid=''):
        if jid:
            prefix = '/jobs/'+jid
        else:
            prefix = '/jobs'
        res = self.PostRequest(None,prefix)

        return res
    #获取 grains
    def SaltMinions(self,minion=''):
        if minion and minion!='*':
            prefix = '/minions/'+minion
        else:
            prefix = '/minions'
        res = self.PostRequest(None,prefix)
        return res
    #获取 events
    def SaltEvents(self):
        prefix = '/events'
        res = self.PostRequest(None,prefix)
        return res

    def SaltRun(self,tgt,client,fun,tgt_type='glob',arg=None):
        prefix = '/run'
        params = {'client': client, 'fun': fun, 'tgt': tgt, 'tgt_type': tgt_type,'arg':arg}
        res = self.PostRequest(params,prefix)
        return res

    ## wheel
    def SaltWheel(self,tgt,fun,tgt_type='local',client='wheel'):
        params = {'client': client, 'fun': fun, 'tgt': tgt, 'tgt_type': tgt_type }
        res = self.PostRequest(params)
        return res


    #列出 KEY
    def ListKey(self):
        prefix = '/keys'
        content = self.PostRequest(None,prefix)
        accepted = content['return']['minions']
        denied = content['return']['minions_denied']
        unaccept = content['return']['minions_pre']
        rejected = content['return']['minions_rejected']
        data={'accepted':accepted,'denied':denied,'unaccept':unaccept,'rejected':rejected}
        return data
    #接受 KEY
    def AcceptKey(self, key_id):
        params = {'client': 'wheel', 'fun': 'key.accept', 'match': key_id}
        content = self.PostRequest(params)
        ret = content['return'][0]['data']['success']
        return ret
    # #删除 KEY
    def DeleteKey(self, key_id):
        params = {'client': 'wheel', 'fun': 'key.delete', 'match': key_id}
        content = self.PostRequest(params)
        ret = content['return'][0]['data']['success']
        return ret



#测试:python manager.py shell ; from SALT.SaltAPI import * ; main(),代码修改了要 ctrl+Z 退出重进
def main():
    sapi = SaltAPI(url="https://192.168.56.101:8000",username="kbson",password="kbson")
    # job = sapi.SaltCmd('192.168.56.101','ssh.cmd',client='local_async',arg='free -m' ,tgt_type='glob',timeout=20)
    # job_id = job['return'][0]['jid']
    # print(sapi.look_jid(job_id))
    print(sapi.SaltJob('20190510043632206140'))
    # print(job)
    # print(sapi.token_id())
    # roots = sapi.SaltWheel(tgt='192.168.56.101', client='wheel', fun='file_roots.list_roots')
    # print(roots)
    # print(sapi.SaltRun(tgt='*',client='ssh',fun='cmd.run',arg='free -m'))
    # print(sapi.SaltWheel('192.168.56.101',fun='file_roots.list_roots')['return'][0]['data']['return'])
    # print(sapi.SaltCmd(client='local', tgt= '192.168.56.101', fun='state.sls', arg= 'user_manage.fangjiayu'))
    # print(sapi.SaltCmd(client='local', tgt= '192.168.56.101', fun='cp.get_url', arg= ['http://192.168.56.1:8000/media/user/zengshenglong.sls','/tmp/test.sls']))
if __name__ == '__main__':
    main()

蜷缩的蜗牛 , 版权所有丨如未注明 , 均为原创丨 转载请注明Saltstack API
喜欢 (0)
[]
分享 (0)
蜷缩的蜗牛
关于作者:
IT运维工程师,熟练使用复制、粘贴技能;平时爱好打羽毛球,虽然很菜,也喜欢出去旅游!个人公众号:蜷缩的蜗牛,欢迎关注订阅~~网站小程序:alongparty,支持搜索博客内容,订阅专题,评论、点赞等等

您必须 登录 才能发表评论!