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

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

#!/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()

转载请注明出处:http://www.xiaomastack.com/2014/10/13/release-3/ 谢谢!

发表评论:

你的电子邮件地址将不会被公开.

2 + 7 =