环境:python3
如何调用
from utils.salt_util import SaltApi
salt = SaltApi("https://192.168.1.21:8001")
salt.remote_cmd_sync_test("bj-sjhl-c-app-test01-192.168.1.25,bj-sjhl-c-app-test02-192.168.1.26", "cmd.script", arg=["salt://scripts/test.sh","1 2 3 "])
#salt-api cmd.script 如何传入参数
- #!/usr/bin/python
- import requests
- import os,sys
- import yaml
- BASE_DIR = os.path.dirname(os.path.dirname(os.path.abspath(__file__)))
- sys.path.append(BASE_DIR)
- from conf import config
- import urllib3
- import datetime
- #urllib3.disable_warnings()
- requests.packages.urllib3.disable_warnings()
-
-
- class SaltApi(object):
-
- def __init__(self, salt_api_url):
- self.username = config.get_config_item('salt', 'salt_user')
- self.password = config.get_config_item('salt', 'salt_password')
- self.eauth = config.get_config_item('salt', 'salt_auth_method')
- self.verify = False
- self.salt_api_url = salt_api_url
-
- self.__header = dict()
- self.__header["Accept"] = "application/json"
- self.token_s_time = ''
- self.__token = self.get_token()
- print(self.__token)
-
- def get_token(self, prefix='/login'):
- """
- 登录获取token
- """
- data = {
- "username": self.username,
- "password": self.password,
- "eauth": "pam"
- }
- loginurl = self.salt_api_url + prefix
- req = requests.post(loginurl, data=data, headers=self.__header, verify=False)
- try:
- self.token = req.json()["return"][0]["token"]
- self.token_s_time = datetime.datetime.now()
- return self.token
- except KeyError:
- raise KeyError
-
- def salt_request(self, data, prefix='/'):
- """
- 接收请求,返回结果
- """
-
- token_e_time = datetime.datetime.now()
-
- if (token_e_time - self.token_s_time).seconds/3600 > 3:
- print("salt-api token is Expired")
- self.get_token()
-
- url = self.salt_api_url + prefix
- self.__header["X-Auth-Token"] = self.__token
-
- # 传入data参数字典,data为None 则方法为get,有date为post方法
- if data:
- req = requests.post(url, data=data, headers=self.__header, verify=False)
- else:
- req = requests.get(url, headers=self.__header,verify=False)
-
- return req.json()
-
- def list_key(self):
- """
- 获取包括认证、未认证salt主机
- """
-
- prefix = '/keys'
- content = self.salt_request(None, prefix)
-
- accepted = content['return']['minions']
- denied = content['return']['minions_denied']
- unaccept = content['return']['minions_pre']
- rejected = content['return']['minions_rejected']
- return {"accepted": accepted, "denied": denied, "unaccept": unaccept, "rejected": rejected}
-
- def accept_key(self, key_id):
- """
- 接受salt主机
- """
-
- data = {'client': 'wheel', 'fun': 'key.accept', 'match': key_id}
- content = self.salt_request(data)
- ret = content['return'][0]['data']['success']
- return ret
-
- def minions_status(self):
- """
- salt主机存活检测
- """
-
- data = {'client': 'runner', 'fun': 'manage.status'}
- content = self.salt_request(data)
- ret = content['return'][0]
-
- up = ret['up']
- down = ret['down']
- ups = []
- downs = []
- for host in up:
- ups.append({'hostname': host, 'status': 'up'})
- for host in down:
- downs.append({'hostname': host, 'status': 'down'})
- ret['up'] = ups
- ret['down'] = downs
- return ret
-
- def get_result(self, jid):
- """
- 通过jid获取执行结果
- """
-
- data = {'client': 'runner', 'fun': 'jobs.lookup_jid', 'jid': jid}
- content = self.salt_request(data)
- ret = content['return'][0]
- return ret
-
- def get_job_info(self, jid=''):
- """
- 获取任务的详细执行信息
- """
-
- if jid:
- prefix = '/jobs/' + jid
- else:
- prefix = '/jobs'
-
- content = self.salt_request(None, prefix)
- ret = content['return'][0]
- return ret
-
- def running_jobs(self):
- """
- 获取运行中的任务
- """
-
- data = {'client': 'runner', 'fun': 'jobs.active'}
- content = self.salt_request(data)
- ret = content['return'][0]
- return ret
-
- def check_job(self, jid):
- """
- 检查任务是否已经执行并成功退出
- """
-
- data = {'client': 'runner', 'fun': 'jobs.exit_success', 'jid': jid}
- content = self.salt_request(data)
- ret = content['return'][0]
- return ret
-
- def delete_key(self, minion_key):
- self.delete_header = {"Accept": "application/x-yaml","X-Auth-Token": self.token}
- self.delete_data = {"client": "wheel", "fun":"key.delete", "match": minion_key}
- result = requests.post(url=self.salt_api_url, headers=self.delete_header, data=self.delete_data,verify=self.verify)
- if yaml.load(result.text)['return'][0]['data']['success']:
- print("%s delete success" % minion_key)
- else:
- print("% delete falied" % minion_key)
-
- def remote_cmd_sync(self, tgt, fun, client='local', tgt_type='glob', arg='', **kwargs):
- """
- 执行远程命令、部署模块 glob - Bash glob completion - Default
- """
-
- try:
- data = {'client': client, 'tgt': tgt, 'fun': fun, 'arg': arg, 'tgt_type': tgt_type}
- content = self.salt_request(data)
- #print(content)
- for host_result in content['return'][0]:
- print('%s:\n%s'%(host_result,content['return'][0][host_result]))
- return content
- except Exception as e:
- print('ERROR:%s'%(e))
-
- def remote_cmd_sync_list(self, tgt, fun, client='local', tgt_type='list', arg='', **kwargs):
- """
- 执行远程命令、部署模块 list - Python list of hosts
- """
-
- try:
- data = {'client': client, 'tgt': tgt, 'fun': fun, 'arg': arg, 'tgt_type': tgt_type}
- content = self.salt_request(data)
- #print(content)
- for host_result in content['return'][0]:
- print('%s:\n%s'%(host_result,content['return'][0][host_result]))
- return content
- except Exception as e:
- print('ERROR:%s'%(e))
-
-
- def remote_state_sync(self, tgt, fun, client='local', tgt_type='list', arg='', **kwargs):
- """
- 执行state.sls 标准化格式输出
- """
- try:
- print ('===================================salt -L "%s" %s "%s"'%(','.join(tgt),fun,arg))
- data = {'client': client, 'tgt': tgt, 'fun': fun, 'arg': arg, 'tgt_type': tgt_type}
- content = self.salt_request(data)
- #print('==============content:%s'%content)
- return_info=content['return'][0]
- #print('==============return_info:%s'%return_info)
-
- for saltname in return_info:
- print(saltname)
- for key in return_info[saltname]:
- #key: pkg_|-supervisor_|-supervisor_|-removed:
- #value: {'comment': 'All specified packages are already absent', 'name': 'supervisor', 'start_time': '18:39:25.024440', 'result': True, 'duration': 334.819, '__run_num__': 0, '__sls__': 'soft.supervisord', 'changes': {}, '__id__': 'supervisor'}
- #print('======================= %s:\n %s'%(key,return_info[saltname][key]))
- return_info_comment=return_info[saltname][key]
- salt_result_format={'Result':return_info_comment['result'],'Name':return_info_comment['name'],'__sls__':return_info_comment['__sls__'],'start_time':return_info_comment['start_time']}
- s=' '
- for result_str,value in salt_result_format.items():
- s='%s %s:%s'%(s,result_str,value)
- if return_info_comment['changes'] != {} and 'diff' in return_info_comment['changes']:
- print(s)
- #print(return_info_comment['changes'])
- print(return_info_comment['changes']['diff'])
- return content
- except Exception as e:
- print('ERROR:%s'%(e))
-
-
-
- if __name__ == "__main__":
- salt = SaltApi("https://192.168.1.21:8001")
- salt.remote_cmd_sync_test("bj-sjhl-c-app-test01-192.168.1.25,bj-sjhl-c-app-test02-192.168.1.26", "cmd.script", arg=["salt://scripts/test.sh","1 2 3 "])
- #salt.remote_cmd_sync_test("bj-sjhl-c-app-test01-192.168.1.25", "cmd.run", arg="ls -l /home/worker/opt/tomcat/webapps/test.war ")
- #salt.remote_cmd_sync("bj-sjhl-c-app-test0*", "cmd.run", arg="ls -l /home/worker/opt/tomcat/webapps/test.war ")