版本更新发布WEB化(3)_小插曲自定义请求saltAPI的类

安装了saltAPI后就可以在任何一台服务器上调用saltAPI让saltstack执行相关的操作。之前用PHP和python写过相关的调用类,如果有兴趣可以移步以下文章:
《用PHP实现salt-api调用》《用Python实现salt-api调用》
思路都是一样的,不过这两篇代码不够优雅。下面再上一个后来用python用写的比较优雅的一个类,看上去会简洁美观很多。

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
#!/usr/bin/env python 
#coding=utf-8
# import urllib2, urllib, json, re


class saltAPI:
def __init__(self):
self.__url = 'https://saltAPI监控的地址和端口如:192.168.192.168:8000'
self.__user = '调用saltAPI时的用户名'
self.__password = '调用saltAPI时的密码'
self.__token_id = self.salt_login()

def salt_login(self):
params = {'eauth': 'pam', 'username': self.__user, 'password': self.__password}
encode = urllib.urlencode(params)
obj = urllib.unquote(encode)
headers = {'X-Auth-Token':''}
url = self.__url + '/login'
req = urllib2.Request(url, obj, headers)
opener = urllib2.urlopen(req)
content = json.loads(opener.read())
try:
token = content['return'][0]['token']
return token
except KeyError:
raise KeyError

def postRequest(self, obj, prefix='/'):
url = self.__url + prefix
headers = {'X-Auth-Token' : self.__token_id}
req = urllib2.Request(url, obj, headers)
opener = urllib2.urlopen(req)
content = json.loads(opener.read())
return content['return']

def saltCmd(self, params):
obj = urllib.urlencode(params)
obj, number = re.subn("arg\\d", 'arg', obj)
res = self.postRequest(obj)
return res

def main():
# 以下是用来测试saltAPI类的部分
sapi = saltAPI()
params = {'client':'local', 'fun':'test.ping', 'tgt':'某台服务器的key'}
# params = {'client':'local', 'fun':'test.echo', 'tgt':'某台服务器的key', 'arg1':'hello'}
# params = {'client':'local', 'fun':'test.ping', 'tgt':'某组服务器的组名', 'expr_form':'nodegroup'}
test = sapi.saltCmd(params)
print test

if __name__ == '__main__':
main()
----------------本文结束 感谢阅读----------------