获取token
#!/usr/bin/env python #-*-coding:utf-8-*- import urllib import urllib.parse import urllib.request # import urllib2 #python2.x需要引入 import ssl,json
context = ssl._create_unverified_context() ssl._create_default_https_context = ssl._create_unverified_context #ssl问题 class SaltAPI(object): __token_id = '' def __init__(self,url,username,password): #初始化 self.__url = url.strip() self.__user = username self.__password = password
#python2示例 # def token_id(self): # ''' user login and get token id ''' # params = {'eauth': 'pam', 'username': self.__user, 'password': self.__password} # encode = urllib.urlencode(params) # obj = urllib.unquote(encode) # content = self.postRequest(obj,prefix='/login') # try: # self.__token_id = content['return'][0]['token'] # print self.__token_id # 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 #python3.x示例 def token_id(self): #获取token params = {'eauth': 'pam', 'username': self.__user, 'password': self.__password} encode_params = urllib.parse.urlencode(params).encode(encoding='utf-8') content = self.postRequest(encode_params,prefix='/login') #表示获取token的时候访问/login self.__token_id = content['return'][0]['token']
print (self.__token_id)
def postRequest(self,params,prefix='/'): #构造http请求
url = self.__url + prefix
headers = {'X-Auth-Token':self.__token_id} req = urllib.request.Request(url,params,headers=headers) data = urllib.request.urlopen(req).read().decode("utf-8") content = json.loads(data) #由于获取的内容为str类型,所以用json处理一下方便操作 return content v = SaltAPI("https://192.168.132.148:8000",username="saltapi",password="saltapi") v.token_id()
示例(python3):
#在以上的基础上定义一个函数,获取所有的key名(主机名)
def list_all_key(self): params = {'client': 'wheel', 'fun': 'key.list_all'} #自定义saltstack要执行的相关参数 obj = urllib.parse.urlencode(params).encode(encoding="utf-8") self.token_id() #调用token_id函数,使执行post请求的时候加载当时的token_id content = self.postRequest(obj) #调用postRequest函数 minions = content['return'][0]['data']['return']['minions'] minions_pre = content['return'][0]['data']['return']['minions_pre'] #print (minions,minions_pre) return minions, minions_pre
其他函数示例(仅供参考,根据实际情况修改)
#!/usr/bin/env python # coding: utf8 import urllib2,urllib try: import json except ImportError: import simplejson as json class SaltAPI(object): __token_id = '' def __init__(self,url,username,password): self.__url = url.rstrip('/') self.__user = username self.__password = password def token_id(self): ''' user login and get token id ''' params = {'eauth': 'pam', 'username': self.__user, 'password': self.__password} encode = urllib.urlencode(params) obj = urllib.unquote(encode) content = self.postRequest(obj,prefix='/login') try: self.__token_id = content['return'][0]['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 list_all_key(self): ''' 获取包括认证、未认证salt主机 ''' params = {'client': 'wheel', 'fun': 'key.list_all'} obj = urllib.urlencode(params) self.token_id() content = self.postRequest(obj) minions = content['return'][0]['data']['return']['minions'] minions_pre = content['return'][0]['data']['return']['minions_pre'] return minions,minions_pre def delete_key(self,node_name): ''' 拒绝salt主机 ''' params = {'client': 'wheel', 'fun': 'key.delete', 'match': node_name} obj = urllib.urlencode(params) self.token_id() content = self.postRequest(obj) ret = content['return'][0]['data']['success'] return ret def accept_key(self,node_name): ''' 接受salt主机 ''' params = {'client': 'wheel', 'fun': 'key.accept', 'match': node_name} obj = urllib.urlencode(params) self.token_id() content = self.postRequest(obj) ret = content['return'][0]['data']['success'] return ret def salt_runner(self,jid): ''' 通过jid获取执行结果 ''' params = {'client':'runner', 'fun':'jobs.lookup_jid', 'jid': jid} obj = urllib.urlencode(params) self.token_id() content = self.postRequest(obj) ret = content['return'][0] return ret def salt_running_jobs(self): ''' 获取运行中的任务 ''' params = {'client':'runner', 'fun':'jobs.active'} obj = urllib.urlencode(params) self.token_id() content = self.postRequest(obj) ret = content['return'][0] return ret def remote_execution(self,tgt,fun,arg,expr_form): ''' 异步执行远程命令、部署模块 ''' params = {'client': 'local_async', 'tgt': tgt, 'fun': fun, 'arg': arg, 'expr_form': expr_form} obj = urllib.urlencode(params) self.token_id() content = self.postRequest(obj) jid = content['return'][0]['jid'] return jid def remote_localexec(self,tgt,fun,arg,expr_form): params = {'client': 'local', 'tgt': tgt, 'fun': fun, 'arg': arg, 'expr_form': expr_form} obj = urllib.urlencode(params) self.token_id() content = self.postRequest(obj) ret = content['return'][0] return ret def salt_state(self,tgt,arg,expr_form): ''' sls文件 ''' params = {'client': 'local', 'tgt': tgt, 'fun': 'state.sls', 'arg': arg, 'expr_form': expr_form} obj = urllib.urlencode(params) self.token_id() content = self.postRequest(obj) ret = content['return'][0] return ret def project_manage(self,tgt,fun,arg1,arg2,arg3,arg4,arg5,expr_form): ''' 文件上传、备份到minion、项目管理 ''' params = {'client': 'local', 'tgt': tgt, 'fun': fun, 'arg': arg1, 'expr_form': expr_form} # 拼接url参数 params2 = {'arg':arg2} arg_add = urllib.urlencode(params2) obj = urllib.urlencode(params) obj = obj + '&' + arg_add params3 = {'arg': arg3} arg_add = urllib.urlencode(params3) obj = obj + '&' + arg_add params4 = {'arg': arg4} arg_add = urllib.urlencode(params4) obj = obj + '&' + arg_add params5 = {'arg': arg5} arg_add = urllib.urlencode(params5) obj = obj + '&' + arg_add self.token_id() content = self.postRequest(obj) ret = content['return'][0] return ret def file_copy(self,tgt,fun,arg1,arg2,expr_form): ''' 文件上传、备份到minion、项目管理 ''' params = {'client': 'local', 'tgt': tgt, 'fun': fun, 'arg': arg1, 'expr_form': expr_form} # 拼接url参数 params2 = {'arg':arg2} arg_add = urllib.urlencode(params2) obj = urllib.urlencode(params) obj = obj + '&' + arg_add self.token_id() content = self.postRequest(obj) ret = content['return'][0] return ret def file_bak(self,tgt,fun,arg,expr_form): ''' 文件备份到master ''' params = {'client': 'local', 'tgt': tgt, 'fun': fun, 'arg': arg, 'expr_form': expr_form} obj = urllib.urlencode(params) self.token_id() content = self.postRequest(obj) ret = content['return'][0] return ret def file_manage(self,tgt,fun,arg1,arg2,arg3,expr_form): ''' 文件回滚 ''' params = {'client': 'local', 'tgt': tgt, 'fun': fun, 'arg': arg1, 'expr_form': expr_form} params2 = {'arg': arg2} arg_add = urllib.urlencode(params2) obj = urllib.urlencode(params) obj = obj + '&' + arg_add params3 = {'arg': arg3} arg_add_2 = urllib.urlencode(params3) obj = obj + '&' + arg_add_2 self.token_id() content = self.postRequest(obj) ret = content['return'][0] return ret def salt_alive(self,tgt): ''' salt主机存活检测 ''' params = {'client': 'local', 'tgt': tgt, 'fun': 'test.ping'} obj = urllib.urlencode(params) self.token_id() content = self.postRequest(obj) ret = content['return'][0] return ret def remote_server_info(self,tgt,fun): ''' 获取远程主机信息 ''' params = {'client': 'local', 'tgt': tgt, 'fun': fun} obj = urllib.urlencode(params) self.token_id() content = self.postRequest(obj) ret = content['return'][0][tgt] return ret def main(): sapi = SaltAPI(url='https://127.0.0.1:8000',username='saltapi',password='password') if __name__ == '__main__': main() 复制代码
jid 通过返回结果中的jid可以获取saltstack的执行状态(结果)
#获取jid
[root@k8s_master ~]# salt-run jobs.list_jobs|tail -n 20
runner.jobs.lookup_jid
StartTime:
2017, Nov 01 10:10:11.809798
Target:
k8s_master_master
Target-type:
User:
root
20171101102000983680:
----------
Arguments:
Function:
runner.jobs.list_jobs
StartTime:
2017, Nov 01 10:20:00.983680
Target:
k8s_master_master
Target-type:
User:
root
根据jid获取任务执行结果
[root@k8s_master ~]# salt-run jobs.lookup_jid 20171101035904902242 k8s_master: True
[root@k8s_master ~]# salt-run jobs.lookup_jid 20171101033119112939
k8s_master_master:
----------
_stamp:
2017-10-31T19:31:20.208453
fun:
wheel.key.list_all
jid:
20171101033119112939
return:
----------
local:
- master.pem
- master.pub
minions:
- k8s_master
- k8s_node1
- k8s_node2
minions_denied:
minions_pre:
minions_rejected:
success:
True
user:
UNKNOWN