以下代码实现的功能:
通过saltstack的httpapi在minion上安装软件。
vim saltapi.py #!/usr/bin/env python # -*- coding: utf-8 -*- import json import requests class SaltServer(object): def __init__(self): self.session = requests.session() self.token = self.getToken() # 获取token def getToken(self): url = "http://192.168.127.165: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 # 执行modules def runModules(self, minionid, fun, arg=None): url = "http://192.168.127.165:8000" data = { "client": "local", "tgt": minionid, "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 # 执行runner def runRunner(self, fun, arg=None): url = "http://192.168.127.165:8000" 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
vim installAPP.py #!/usr/bin/env python # -*- coding: utf-8 -*- # nginx.sh里面就写了一句简单的yum install -y nginx import SaltServer saltServer = SaltServer() result1 = saltServer.runModules('192.168.127.166', 'cp.get_file', ['salt://_shell/app/nginx.sh', '/usr/local/src/installnginx.sh']) # 把安装nginx脚本同步到minion端 print(result1) result2 = saltServer.runModules('192.168.127.166', 'installApp.nginx') print(result2)
执行 python installApp.py之后,就可以在192.168.127.166上面看到nginx已经安装好了。