Skip to content

Instantly share code, notes, and snippets.

@Ara4Sh
Created May 11, 2019 09:31
Show Gist options
  • Select an option

  • Save Ara4Sh/f0e08fc4584c12d4a69bde6ff43ce7b3 to your computer and use it in GitHub Desktop.

Select an option

Save Ara4Sh/f0e08fc4584c12d4a69bde6ff43ce7b3 to your computer and use it in GitHub Desktop.
Simple class to run salt commands using salt-api
'''
A Python library for working with Salt's REST API
'''
import json
import requests
import ssl
from urllib.parse import urljoin
import urllib3
urllib3.disable_warnings(urllib3.exceptions.InsecureRequestWarning)
class SaltApi:
'''
A thin wrapper for making HTTP calls to the salt-api.
'''
def __init__(self, api_url='https://172.18.8.100:8001'):
'''
Initialize the class with the URL of the API
:param api_url: Host or IP address of the salt-api URL;
include the port number
'''
self.api_url = api_url
self.auth = {}
def _url(self, path):
rpath = path.lstrip('/')
return urljoin(self.api_url, rpath)
def req_post(self, path, data=None):
'''
A thin wrapper around python-requests to send requests and return the response
:rtype: dictionary
'''
headers = {
'Content-Type': 'application/json',
'Accept' : 'application/json',
}
if data is not None:
postdata = json.dumps(data).encode()
clen = str(len(postdata))
else:
postdata = None
url = self._url(path)
if data is not None:
headers["Content-Length"] = clen
if path != '/run' and self.auth and 'token' in self.auth and self.auth['token']:
headers['X-Auth-Token'] = self.auth['token']
try:
req = requests.post(url, data=postdata, headers=headers, verify=False)
ret = json.loads(req.text)
except requests.exceptions.HTTPError as err:
print(err)
return
print(req)
print(ret)
return str(req)
def _auth(self, path, **kwargs):
return self.req_post(path, kwargs)
def login(self, username=None, password=None, eauth=None, **kwargs):
'''
Authenticate with salt-api and return the user permissions and
authentication token or an empty dict
'''
local = locals()
kwargs.update(
dict(
(key, local[key]) for key in (
'username',
'password',
'eauth',
) if local.get(key, None) is not None
)
)
#self.auth = self._auth('/login', **kwargs).get('return', [{}])[0]
self.auth = self._auth('/login', **kwargs)
return self.auth
def token(self, **kwargs):
'''
Get an eauth token from Salt for use with the /run URL
'''
self.auth = self._auth('/token', **kwargs)[0]
return self.auth
def low(self, lowstate, path='/'):
return self.req_post(path, lowstate)
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment