#!/usr/bin/env python
#coding=utf-8
import json,re
import urllib
import urllib2
#import ssl
#ssl._create_default_https_cOntext= ssl._create_unverified_context
class SaltAPI(object):
def __init__(self,url,username,password):
self.__url = url #salt-api监控的地址和端口
self.__user = username #salt-api用户名
self.__password = password #salt-api用户密码
self.__token_id = self.salt_login()
def salt_login(self):
'''获取token'''
params = {'eauth': 'pam', 'username': self.__user, 'password': self.__password}
print(params)
encode = urllib.urlencode(params)
obj = urllib.unquote(encode)
headers = {'X-Auth-Token':''}
url = self.__url + '/login'
print("url:",url)
req = urllib2.Request(url, obj, headers)
opener = urllib2.urlopen(req)
print (opener)
content = json.loads(opener.read())
try:
token = content['return'][0]['token']
print("token:",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
def saltCmd(self, params):
'''命令执行'''
obj = urllib.urlencode(params)
obj, number = re.subn("arg\d", 'arg', obj)
res = self.postRequest(obj)
return res['return']
def main():
sapi = SaltAPI(url='https://192.168.0.104:8888',username='saltapi',password='123456')
#params = {'client':'local', 'fun':'test.ping', 'tgt':'某台服务器的key'}
params = {'client':'local', 'fun':'test.ping', 'tgt':'*'}
#params = {'client':'local', 'fun':'cmd.run', 'tgt':'*','arg1':'ifconfig'}
test = sapi.saltCmd(params)
print (test)
if __name__ == '__main__':
main()