-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathpslrestful.py
More file actions
executable file
·186 lines (152 loc) · 5.91 KB
/
pslrestful.py
File metadata and controls
executable file
·186 lines (152 loc) · 5.91 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
#!/usr/bin/python3
"""
Generic access to Perle RESTful API
Provides get/put/post methods and automatic authorization.
Look at the main() for sample code.
"""
import os
import time
import requests
import tempfile
import pickle
__all__ = ['PSL_RESTfulAPI']
class PSL_RESTfulAPI:
'''
Generic access to Perle RESTful API
Provides get/put/post methods and automatic authorization.
Useful class attributes:
COOKIEFILE: where the login cookies are persisted.
VERIFY_TLS: whether or not TLS connection should be validated.
'''
# Storage for the login cookie
COOKIEFILE = os.path.join(os.getenv('HOME', tempfile.gettempdir()),
'.pslcookie')
# Do not verify TLS by default.
VERIFY_TLS = False
def __init__(self, username, password, host, port=8080,
schema='http', ver='v1.1', retries=10, logcb=None):
'''
Initialize with given username/password at host.
port: port to use
schema: http or https
ver: API version
retries: how many connection retry attempts
logcb: a log callback function which takes a single str.
'''
self.url_prefix = f'{schema}://{host}:{port}/api/{ver}/managed-devices'
self.username = username
self.password = password
self.cookie = None
self.retries = max(1, retries)
if logcb is not None and not callable(logcb):
raise TypeError('logcb must be callable')
self.logcb = logcb
self.__loadcookie()
if not self.cookie:
self.login()
def __requestop(self, op, url, *args, **kwargs):
'''Run a generic request operation, retrying login if required'''
def badlogin(resp):
return ((resp.status_code == 401) or
(b'Missing authorization' in resp.content) or
(b'User is not authorized for this api' in resp.content))
url = self.url_prefix + url
kwargs['cookies'] = self.cookie
kwargs['verify'] = self.VERIFY_TLS
# Try the request, retrying on any IO error (RESTful probably down)
sleeptime = 1
for retry in range(self.retries):
conerr = None
try:
resp = op(url=url, *args, **kwargs)
break
except (ConnectionError, requests.RequestException) as e:
if self.logcb is not None:
self.logcb(f'Connection failed - retrying '
f'({retry} of {self.retries}): {e}')
conerr = e
time.sleep(sleeptime)
sleeptime = min(sleeptime*2, 16)
if conerr is not None:
# Give up
raise conerr
if badlogin(resp):
# Redo login and try again
self.login()
kwargs['cookies'] = self.cookie
resp = op(url=url, *args, **kwargs)
if badlogin(resp):
raise Exception(resp.content)
return resp
def get(self, url, *args, **kwargs):
'''Perform a GET.'''
return self.__requestop(requests.get, url, *args, **kwargs)
def put(self, url, cmd={}, *args, **kwargs):
'''Perform a PUT. cmd must be a json-like dict.'''
if not isinstance(cmd, dict):
raise TypeError('dict-like object required for cmd')
kwargs['json'] = cmd
return self.__requestop(requests.put, url, *args, **kwargs)
def post(self, url, cmd={}, *args, **kwargs):
'''Perform a POST. cmd must be a json-like dict.'''
if not isinstance(cmd, dict):
raise TypeError('dict-like object required for cmd')
kwargs['json'] = cmd
return self.__requestop(requests.post, url, *args, **kwargs)
def __loadcookie(self):
'''Load cached cookie'''
try:
with open(self.COOKIEFILE, 'rb') as fp:
self.cookie = pickle.load(fp)
except Exception:
self.cookie = None
def __savecookie(self, cookie):
'''Save current cookie in persistent storage'''
if not cookie:
return
self.cookie = cookie
with open(self.COOKIEFILE, 'wb') as fp:
pickle.dump(self.cookie, fp)
def __delcookie(self):
'''Delete cookie data'''
try:
os.remove(self.COOKIEFILE)
except FileNotFoundError:
pass
self.cookie = None
def login(self):
'''Perform a login. This is done automatically as needed.'''
# Do not use self.post() to avoid login recursion.
credentials = {'username': self.username, 'password': self.password}
self.__delcookie()
resp = requests.post(self.url_prefix + '/login',
json=credentials, verify=self.VERIFY_TLS)
if not resp.ok:
raise PermissionError('Invalid login')
self.__savecookie(resp.cookies.get_dict())
def main():
'''
Sample usage of PSL_RESTfulAPI.
Do not modify this file. Normal usage would be to write your own
separate python3 script and do:
from pslrestful import PSL_RESTfulAPI
...in it to import the API class and use it in a similar
way as this main().
'''
USER = os.getenv('USER', 'admin')
PASS = os.getenv('PASS', 'mypass')
IP = os.getenv('IP', '192.168.0.123')
print(f'Connecting as {USER}/{PASS} to host {IP}')
# See PSL_RESTfulAPI __init__() for more possible parameters
# (e.g. port, schema, retries)
irg = PSL_RESTfulAPI(USER, PASS, IP, retries=3, logcb=print)
data = irg.get('/system/general/clock').json()
now = data['clock']
print(f'api clock: {now}')
data = irg.put('/cli', {'show': 'show clock'}).json()
now = data['cliCommands'][0]['commandOutput'].strip()
print(f'show clock: {now}')
data = irg.get('/network/cellular').json()
print(f'cellular: {data["connectionInfo"]["cellularStatus"]}')
if __name__ == '__main__':
main()