48 lines
1.3 KiB
Python
48 lines
1.3 KiB
Python
#!/usr/bin/python
|
|
import requests
|
|
import base64
|
|
|
|
class ElasticsearchApi:
|
|
def __init__(self, url, user, password):
|
|
self.url = url
|
|
self.headers = {}
|
|
if user and password:
|
|
token = base64.b64encode('{}:{}'.format(user, password))
|
|
self.headers = { 'Authorization': 'Basic {}'.format(token) }
|
|
|
|
def check_password(self, user, password):
|
|
token = base64.b64encode('{}:{}'.format(user, password))
|
|
headers = { 'Authorization': 'Basic {}'.format(token) }
|
|
|
|
r = requests.get(self.url, headers=headers)
|
|
if r.status_code != 401:
|
|
return True
|
|
|
|
return False
|
|
|
|
def get(self, path):
|
|
r = requests.get(
|
|
'{}/{}'.format(self.url, path),
|
|
headers=self.headers
|
|
)
|
|
|
|
if r.status_code == 500:
|
|
raise Exception('Server return 500 error: {}'.format(r.text))
|
|
elif r.status_code == 401:
|
|
raise Exception('Authentification has failed')
|
|
|
|
return r.status_code, r.json()
|
|
|
|
def put(self, path, data):
|
|
r = requests.put(
|
|
'{}/{}'.format(self.url, path),
|
|
headers=self.headers,
|
|
json=data
|
|
)
|
|
|
|
if r.status_code == 500:
|
|
raise Exception('Server return 500 error: {}'.format(r.text))
|
|
elif r.status_code == 401:
|
|
raise Exception('Authentification has failed')
|
|
elif r.status_code != 200:
|
|
raise Exception('Server return an unknown error: {}'.format(r.text))
|