Python操作Saltstack

Posted MASCOT

tags:

篇首语:本文由小常识网(cha138.com)小编为大家整理,主要介绍了Python操作Saltstack相关的知识,希望对你有一定的参考价值。

1.代码

# -*- coding:utf-8 -*-
import urllib.request
import urllib.parse
import json


class saltAPI():

    def __init__(self):
        self.url = http://192.168.174.128:8000
        self.data = {username : saltapi,
                     password : saltapi,
                     eauth : pam}
        self.headers = {User-Agent:Mozilla/5.0 (X11; Fedora; Linux x86_64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/58.0.3029.110 Safari/537.36}
        self.token = self.get_token()
        self.headers[X-Auth-Token] = self.token

    #发送post
    def post_request(self,prefix=/,postdata=None):
        request = urllib.request.Request(self.url+ prefix,postdata,headers=self.headers)
        reponse = urllib.request.urlopen(request).read()
        content  = json.loads(reponse.decode(utf8))
        return content

    #获取token
    def get_token(self):
        postdata = urllib.parse.urlencode(self.data).encode(utf8)
        content = self.post_request(/login,postdata)
        try:
            token = content[return][0][token]
            return token
        except KeyError:
            raise KeyError

    #获取grains
    def get_grains(self,minion=‘‘):
        if minion and minion!=*:
            prefix = /minions/+minion
        else:
            prefix = /minions
        content = self.post_request(prefix)
        return content

    #执行命令->get_jid
    def SaltCmd(self,tgt,fun,client=local_async,expr_form=glob,arg=None,**kwargs):
        params = {client:client, fun:fun, tgt:tgt, expr_form:expr_form}
        if arg:
            a=arg.split(,) #参数按逗号分隔
            for i in a:
                b=i.split(=) #每个参数再按=号分隔
                if len(b)>1:
                    params[b[0]]==.join(b[1:]) #带=号的参数作为字典传入
                else:
                    params[arg%s%(a.index(i)+100)]=i
        if kwargs:
            params=dict(list(params.items())+list(kwargs.items()))
        obj = urllib.parse.urlencode(params).encode(UTF8)
        ret = self.post_request(prefix=/,postdata=obj)
        jid = ret[return][0][jid]
        prefix = /jobs/+jid
        content = self.post_request(prefix)
        return content[info][0][Result]

    def test(self):
        print(self.headers)

if __name__ == __main__:
    tester = saltAPI()
    token = tester.SaltCmd(*,test.ping)
    print(token)

 

以上是关于Python操作Saltstack的主要内容,如果未能解决你的问题,请参考以下文章

saltstack部署LAMP架构

通过Python利用saltstack进行生成服务器资产清单

57. Python saltstack 二次开发

SaltStack

通过Python利用saltstack进行生成服务器资产清单

学习笔记:python3,代码片段(2017)