saltstack的rest接口salt-api開發—基於flask-restful

以前官方給的salt-api在前期用着也還不錯,後來發現貌似不支持timeout選項(也許我太弱,也沒研究過它cherrypy的框架),搞來搞去實在沒辦法就拿着flask從新封裝了一層webapi。
python


剛學的flask,寫的很差勿噴(徹底是爲了公司需求啊!!)nginx


代碼都放在github上了,基本功能OK,只去掉了根據公司需求自定義的一些功能類。git

地址:https://github.com/lustlost/saltstack-api-Flaskgithub


簡單的搞了一個token驗證,經過rest傳過去的。這裏就講下具體的認證方式:web


首先雙方協商一個key,加上當先時間,到小時爲止,而後hash出一個值做爲最終的token,因此這個token是每小時都會變化的,雙方協商好key就會自動生成。也能夠精確到每十分之或者每分鐘,具體看不一樣需求了。flask


class Token():
    def __init__(self):
        self.now_time = time.strftime('%Y-%m-%d-%H',time.localtime(time.time()))
    def getToken(self,key):
        md5 = hashlib.md5()
        md5.update(self.now_time+key)
        return md5.hexdigest()
    def authToken(self,one_token,two_token):
        if one_token == two_token:
            return True
        else:
            return False



這是一個請求的demo,本身修改para_dict裏的value就好了,能夠根據需求在para_dict中能夠加上timeout的值api

import commands,urllib
import time,sys
import hashlib
now_time = time.strftime('%Y-%m-%d-%H',time.localtime(time.time()))
key = 'haha'
md5 = hashlib.md5()
md5.update(now_time+key)
token = md5.hexdigest()
"""
para_dict={
    "tgt":"200-119-0.jh.qszg.uuzu.idc",
    "server_config":"true",
    "token":token
}
"""
para_dict={
    "tgt":"200-119-0.jh.qszg.uuzu.idc",
    "fun":"cmd.run",
    "args":"uptime",
    "expr_form":"list",
    "token":token
}
api_url = "http://10.0.5.201:5000/api"
                                                                                                                                                                      
post_para = urllib.urlencode(para_dict)
api_info=urllib.urlopen(api_url,post_para).read()
print "Now Token : %s" % token
print api_info


最後經過uwsgi和nginx整合,提供一下uwsgi.xmlapp

<uwsgi>
     <pythonpath>/root/test</pythonpath>
     <module>api</module>
     <callable>app</callable>
     <socket>/tmp/uwsgi.sock</socket>
     <master/>
     <processes>4</processes>
     <memory-report/>
</uwsgi>


看下效果:框架

wKiom1MUVjTwgKm-AACBybSdDKE584.jpg

相關文章
相關標籤/搜索