saltstack实例

saltstack实例

实现功能:通过http调用模块和runner。

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
import json
import requests


class SaltServer(object):
    def __init__(self):
        self.session = requests.session()
        self.token = self.gettoken()
        print(self.token)

    def gettoken(self):
        url = "http://192.168.145.129:8000/login"
        header = {"Accept": "application/json"}
        data = {
            "username": "saltapi",
            "password": "saltapi",
            "eauth": "pam"
        }
        res = self.session.post(url=url, headers=header, data=data)
        text = res.text
        result = json.loads(text)
        token = result.get("return")[0].get("token")
        return token

    def runmodules(self, minionid, func, args=None):
        url = "http://192.168.145.129:8000"
        data = {
            "tgt": minionid,
            "client": "local",
            "fun": func,
            "arg": args
        }
        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'] = 1
            resultBean['message'] = 'failed'
            resultBean['data'] = e
        finally:
            return resultBean

    def runrunner(self, func, args=None):
        url = "http://192.168.145.129:8000"
        data = {
            "client": "runner",
            "fun": func,
            "arg": args
        }
        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'] = 1
            resultBean['message'] = 'failed'
            resultBean['data'] = e
        finally:
            return resultBean

通过test.py调用查看结果

1
2
3
4
5
6
7
from saltstack_api.util.saltapi import SaltServer

saltServer = SaltServer()
data = saltServer.runmodules("slave", "test.ping")
print(data)
data1 = saltServer.runrunner("manage.status")
print(data1)

注意:需要有安装saltstack的服务器存在且服务已启用。







你可能感兴趣的:(saltstack实例)