调用saltapi接口实例
2021-03-30 08:27
import requests def resBean(self, datas): #定义res接口规范函数,方便下面调用,一般都使用这个规范! def runModules(self, minionid, fun, arg=None): #定义module函数,三个参数分别是客户端,函数和参数
class SaltServer(object):
def __init__(self):
self.session = requests.session()
self.token = self.getToken() #获取token,如果这里不写的话可以在下面函数调用也一样
self.url = "http://192.168.137.130:8000"
# print(self.session.cookies) #通过resquests模块也可以获取到token,不过需要再执行过滤,这个看具体使用
def getToken(self): #定义获取token的函数
url = "http://192.168.137.130:8000/login"
headers = {"Accept": "application/json"}
data = {
"username": "saltapi",
"password": "saltapi",
"eauth": "pam"
}
res = self.session.post(url=url, headers=headers, data=data)
text = res.text
result = json.loads(text)
token = result.get("return")[0].get("token")
return token
resultBean = dict()
try:
res = self.session.post(url=self.url, data=datas)
text = res.text
data = json.loads(text).get("return")
resultBean[‘code‘] = 0
resultBean[‘message‘] = "success"
resultBean[‘data‘] = data
except Exception as e:
resultBean[‘code‘] = -1
resultBean[‘message‘] = "error"
resultBean[‘data‘] = e
finally:
return resultBean
# url = "http://192.168.137.130:8000"
data = {
# "X-Auth-Token": self.getToken(), #在上面构造函数里定义了这里就可以不用再写这个参数了
"client": "local", #调用module使用local
"tgt": minionid, #定义minion的id
"fun": fun, #使用的函数
"arg": arg #函数使用的参数
}
return self.resBean(data)
def runRunner(self, fun, arg=None): #定义runner函数,两个参数分别是函数和参数
# url = "http://192.168.137.130:8000"
data = {
# "X-Auth-Token": self.getToken(),
"client": "runner",
"fun": fun,
"arg": arg
}
return self.resBean(data)
上一篇:c#基础学习(0708)之静态类
下一篇:C# 简介