1.编写接口,使之能够接受并返回结果。
#调用模块
import json import requests #定义类的名字 class SaltServer(object):
#声明类的属性 def __init__(self): self.session = requests.session() self.token = self.getToken() #定义getToken模块用来获取token def getToken(self):
#定义URL url = "http://192.168.1.131:8001/login"
#定义头信息 headers = {"Accept":"application/json"}
#定义数据信息 data = { "username":"saltapi", "password":"123456", "eauth":"pam" }
#连接 res = self.session.post(url=url,headers=headers,data=data)
#获取返回内容 text = res.text
#获取token result = json.loads(text) token = result.get("return")[0].get("token") return token #定义执行module模块,及相关参数 def runModules(self,minionid,fun,arg=None): url = "http://192.168.1.131:8001" data = { "client":"local", "tgt":minionid, "fun":fun, "arg":arg } resultBean = dict()
#try捕获异常信息,并且继续往下执行 try: res = self.session.post(url=url, data=data) text = res.text data = json.loads(text).get("return") resultBean['code'] = 0 resultBean['message'] = "success" resultBean['data'] = data
#捕获异常,并进行输出 except Exception as e: resultBean['code'] = 0 resultBean['message'] = "success" resultBean['data'] = e
#无论是否异常都继续执行 finally: return resultBean def runRunner(self, fun, arg=None): url = "http://192.168.1.131:8001" data = { "client": "runner", "fun": fun, "arg": arg } resultBean = dict() try: res = self.session.post(url=url, data=data) text = res.text data = json.loads(text).get("return") resultBean['code'] = 0 resultBean['message'] = "success" resultBean['data'] = data except Exception as e: resultBean['code'] = 0 resultBean['message'] = "success" resultBean['data'] = e finally: return resultBean
写好之后测试一下:
#调用
from saltstac.util.saltapi import SaltServer saltServer = SaltServer() print(saltServer.runModules("minion-2","test.ping")) print(saltServer.runRunner("manage.status"))
运行:
{'code': 0, 'message': 'success', 'data': [{'minion-2': True}]}
{'code': 0, 'message': 'success', 'data': [{'down': [], 'up': ['minion-2']}]}