# _*_ coding: utf-8 _*_
import time
import os
import requests
from requests.packages.urllib3.exceptions import InsecureRequestWarning
requests.packages.urllib3.disable_warnings(InsecureRequestWarning)
class SaltApi(object):
def __init__(self, url, username, password, eauth='pam'):
self.url = url
self.__username = username
self.__password = password
self.eauth = eauth
self.__token = self.__login()
print self.__token['token']
def __login(self):
print "login"
data = {'username': self.__username, 'password': self.__password, 'eauth': self.eauth}
headers = {'Accept': 'application/json'}
try:
r = requests.post(self.url + 'login', data=data, headers=headers, verify=False)
response = r.json()
return {'token': response['return'][0]['token'], 'expire': response['return'][0]['expire']}
except Exception as e:
print "salt api login error. %s" % e
def __if_token_expired(self):
"""检查token是否可用,过期则重新登录"""
if self.__token['expire'] >= time.time():
self.__login()
def cmd(self, tgt, fun, arg=None, expr_form='glob'):
"""同步执行模块.
expr_form为salt target类型.可用的选项如下:
glob - Bash glob completion - Default
pcre - Perl style regular expression
list - Python list of hosts
grain - Match based on a grain comparison
grain_pcre - Grain comparison with a regex
pillar - Pillar data comparison
pillar_pcre - Pillar data comparison with a regex
nodegroup - Match on nodegroup
range - Use a Range server for matching
compound - Pass a compound match string
ipcidr - Match based on Subnet (CIDR notation) or IPv4 address.
"""
self.__if_token_expired()
data = {'tgt': tgt, 'fun': fun, 'expr_form': expr_form, 'client': 'local', 'arg': arg}
headers = {'X-Auth-Token': self.__token['token'], 'Accept': 'application/json'}
try:
r = requests.post(self.url, data=data, headers=headers, verify=False)
response = r.json()
print response
return response
except Exception as e:
print "run cmd error. %s" % e
def cmd_async(self, tgt, fun, arg=None, expr_form='glob'):
self.__if_token_expired()
data = {'tgt': tgt, 'fun': fun, 'expr_form': expr_form, 'client': 'local_async', 'arg': arg}
headers = {'X-Auth-Token': self.__token['token'], 'Accept': 'application/json'}
try:
r = requests.post(self.url, data=data, headers=headers, verify=False)
response = r.json()
return response
except Exception as e:
print "run cmd error. %s" % e
def get_return(self, jid):
self.__if_token_expired()
print "jid: " + jid
headers = {'X-Auth-Token': self.__token['token'], 'Accept': 'application/json'}
try:
r = requests.get(self.url + 'jobs/' + jid, headers=headers, verify=False)
response = r.json()
print response
except Exception as e:
print "get result error. %s" % e
if __name__ == '__main__':
url = settings.SALT_API['url']
saltapi = SaltApi(url=settings.SALT_API['url'],
username=settings.SALT_API['username'],
password=settings.SALT_API['password'])
saltapi.cmd('*', 'cmd.run', 'sleep 10 && uptime')
网友评论