-
Notifications
You must be signed in to change notification settings - Fork 3
/
restconf_cli.py
350 lines (307 loc) · 15.7 KB
/
restconf_cli.py
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
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
#!/usr/bin/env python
import click
import requests
from rich import print
# Disable InsecureRequestWarning: Unverified HTTPS request is being made.
requests.packages.urllib3.disable_warnings()
# Creating click group as parent function for other click commands to be attached with
@click.group()
def restconf_cli():
""" CLI tool to interact with the restconf APIs currently supported
for IOSXE, NXOS and NSO.
\b
This library uses the following root URL for the restconf with port 443 as default port.
https://<hostname/ip>:<port>/restconf/data/
Default Headers for Accept and Content-Type are the following. \n
\b
Accept: application/yang-data+json
Content-Type: application/yang-data+json
\b
Since default headers are using 'application/yang-data+json',
therefore, you will retrieve the output in following formats
for the below type of devices unless specified for the GET operation.
\b
| Device Type | IOSXE | NXOS | NSO |
| :-------------------: | :--------------------------: | :--------------------------: | :-------------------------: |
| Default Accept | application/yang-data+json | application/yang-data+json | application/yang-data+json |
| Default Content-Type | application/yang-data+json | application/yang-data+json | application/yang-data+json |
| Default Output Format | JSON | XML | JSON |
\b
Same for the POST, PUT and PATCH operation if you do not specify the
header fields, it assumes you are sending the data in the formats
mentioned above.
\b
Disclaimer: This module uses Insecure Requests which is not recommended, use
certificates where possible.
"""
pass
# Click command 'GET'
@click.option("--hostname", "-n", type=str, required=True, help="Device hostname or IP address for the restconf API")
@click.option("--username", "-u", type=str, required=True, help="Username for restconf api")
@click.option('--password', prompt=True, hide_input=True, confirmation_prompt=False, help="Password for restconf api")
@click.option("--path", "-p", type=str, required=True, help="Path for restconf api call")
@click.option("--port", "-pn", type=int, required=False, default=443, help="Port number for restconf api, default is 443")
@click.option("--accept", "-a", type=str, required=False, default='application/yang-data+json', help="Accept header for restconf api, default is application/yang-data+json")
@click.option("--content-type", "-c", type=str, required=False, default='application/yang-data+json', help="Content-Type header for restconf api, default is application/yang-data+json")
@click.option("--output", "-o", type=click.File('w'), required=False, default=None, help="Output will be written to a file")
@click.command(name="GET", context_settings=dict(help_option_names=['-h', '--help']))
def restconf_get(hostname, username, password, path, port, accept, content_type, output):
"""
Method to retrieve operational or config data from the devices. \n
Default header for the requests are 'application/yang-data+json'
Examples:\n
\b
# Display output on the terminal \b
$ restconf-cli GET -u developer -n sandbox-iosxe-latest-1.cisco.com \ \b
-p Cisco-IOS-XE-native:native/version \ \b
-a application/yang-data+json \ \b
-c application/yang-data+json \b
\b
# Display output on the terminal and save the output on a file defined with --output or -o flag \b
$ restconf-cli GET -u developer -n sandbox-iosxe-latest-1.cisco.com \ \b
-p Cisco-IOS-XE-native:native/interface \ \b
-o interfaces.json
"""
try:
headers = {'Accept': accept, 'Content-Type': content_type}
url = f"https://{hostname}:{port}/restconf/data/{path}"
response = requests.get(url,
auth=(username, password),
headers=headers,
verify=False)
if response.status_code == 200:
click.echo(print(f'{response.text}'))
click.echo(print(f"\nStatus: {response.status_code} OK"))
if output:
click.echo(f'{response.text}', file=output)
click.echo(print(f'Output has been saved to a file "{output.name}"\n'))
else:
click.echo(print(f"\nRequest Failed: {response}"))
except requests.RequestException as e:
click.echo(print(e))
# Click command 'POST'
@click.option("--hostname", "-n", type=str, required=True, help="Device hostname or IP address for the restconf API")
@click.option("--username", "-u", type=str, required=True, help="Username for restconf api")
@click.option('--password', prompt=True, hide_input=True, confirmation_prompt=False, help="Password for restconf api")
@click.option("--path", "-p", type=str, required=True, help="Path for restconf api call")
@click.option("--port", "-pn", type=int, required=False, default=443, help="Port number for restconf api, default is 443")
@click.option("--accept", "-a", type=str, required=False, default='application/yang-data+json', help="Accept header for restconf api, default is application/yang-data+json")
@click.option("--content-type", "-c", type=str, required=False, default='application/yang-data+json', help="Content-Type header for restconf api, default is application/yang-data+json")
@click.option("--data", "-d", type=str, default='', help="Playload to be sent for POST, PUT and PATCH methods")
@click.option("--from-file", "-ff", type=click.File('r'), required=False, default=None, help="Read the playload from file for POST operation")
@click.command(name="POST", context_settings=dict(help_option_names=['-h', '--help']))
def restconf_post(hostname, username, password, path, port, data, from_file, accept, content_type):
'''
Sends data to the devices to create a new data resource.\n
\b
Example:
\b
# Configure via raw data for POST operation
$ restconf-cli POST -u developer -n sandbox-iosxe-latest-1.cisco.com \ \b
-p ietf-interfaces:interfaces \ \b
-d '{
"interface":[
{
"name":"Loopback999",
"description":"created by python click - POST",
"type":"iana-if-type:softwareLoopback",
"enabled":true,
"ietf-ip:ipv4":{
"address":[
{
"ip":"10.0.1.10",
"netmask":"255.255.255.255"
}
]
}
}
]
}'
\b
# Configure from file for POST operation
$ restconf-cli POST -u developer \ \b
-n sandbox-iosxe-latest-1.cisco.com \ \b
-p ietf-interfaces:interfaces -ff interface.json
'''
try:
headers = {'Accept': accept, 'Content-Type': content_type}
url = f"https://{hostname}:{port}/restconf/data/{path}"
if from_file:
payload = from_file.read()
else:
payload = data
response = requests.post(url,
auth=(username, password),
headers=headers,
data=payload,
verify=False)
if response.status_code == 201:
click.echo(print(f"\nResource has been created successfully: {response.status_code} OK"))
else:
click.echo(print(f"\nRequest Failed: {response}"))
except requests.RequestException as e:
click.echo(print(e))
# Click command 'PUT'
@click.option("--hostname", "-n", type=str, required=True, help="Device hostname or IP address for the restconf API")
@click.option("--username", "-u", type=str, required=True, help="Username for restconf api")
@click.option('--password', prompt=True, hide_input=True, confirmation_prompt=False, help="Password for restconf api")
@click.option("--path", "-p", type=str, required=True, help="Path for restconf api call")
@click.option("--port", "-pn", type=int, required=False, default=443, help="Port number for restconf api, default is 443")
@click.option("--accept", "-a", type=str, required=False, default='application/yang-data+json', help="Accept header for restconf api, default is application/yang-data+json")
@click.option("--content-type", "-c", type=str, required=False, default='application/yang-data+json', help="Content-Type header for restconf api, default is application/yang-data+json")
@click.option("--data", "-d", type=str, default='', help="Playload to be sent for POST, PUT and PATCH methods")
@click.option("--from-file", "-ff", type=click.File('r'), required=False, default=None, help="Read the playload from file for PUT operation")
@click.command(name="PUT", context_settings=dict(help_option_names=['-h', '--help']))
def restconf_put(hostname, username, password, path, port, data, from_file, accept, content_type):
'''
Send data to the devices to create or update the data resource.
\b
Example:
\b
# Configure via raw data for PUT operation
$ restconf-cli PUT -u developer -n sandbox-iosxe-latest-1.cisco.com \ \b
-p ietf-interfaces:interfaces \ \b
-d '{
"interface":[
{
"name":"Loopback999",
"description":"created by python click - PUT",
"type":"iana-if-type:softwareLoopback",
"enabled":true,
"ietf-ip:ipv4":{
"address":[
{
"ip":"10.0.1.10",
"netmask":"255.255.255.255"
}
]
}
}
]
}'
\b
# Configure from file for PUT operation
$ restconf-cli PUT -u developer \ \b
-n sandbox-iosxe-latest-1.cisco.com \ \b
-p ietf-interfaces:interfaces/interface=Loopback999 -ff interface.json
'''
try:
headers = {'Accept': accept, 'Content-Type': content_type}
url = f"https://{hostname}:{port}/restconf/data/{path}"
if from_file:
payload = from_file.read()
else:
payload = data
response = requests.put(url,
auth=(username, password),
headers=headers,
data=payload,
verify=False)
if response.status_code == 204:
click.echo(print(f"\nResource has been created/updated successfully: {response.status_code} OK"))
else:
click.echo(print(f"\nRequest Failed: {response}"))
except requests.RequestException as e:
click.echo(print(e))
# Click command 'PATCH'
@click.option("--hostname", "-n", type=str, required=True, help="Device hostname or IP address for the restconf API")
@click.option("--username", "-u", type=str, required=True, help="Username for restconf api")
@click.option('--password', prompt=True, hide_input=True, confirmation_prompt=False, help="Password for restconf api")
@click.option("--path", "-p", type=str, required=True, help="Path for restconf api call")
@click.option("--port", "-pn", type=int, required=False, default=443, help="Port number for restconf api, default is 443")
@click.option("--accept", "-a", type=str, required=False, default='application/yang-data+json', help="Accept header for restconf api, default is application/yang-data+json")
@click.option("--content-type", "-c", type=str, required=False, default='application/yang-data+json', help="Content-Type header for restconf api, default is application/yang-data+json")
@click.option("--data", "-d", type=str, default='', help="Playload to be sent for POST, PUT and PATCH methods")
@click.option("--from-file", "-ff", type=click.File('r'), required=False, default=None, help="Read the playload from file for PATCH operation")
@click.command(name="PATCH", context_settings=dict(help_option_names=['-h', '--help']))
def restconf_patch(hostname, username, password, path, port, data, from_file, accept, content_type):
'''
same as PUT, except if the resource does not exist,
the devices MUST NOT create one.
\b
Example:
\b
# Configure via raw data for PATCH operation
$ restconf-cli PATCH -u developer -n sandbox-iosxe-latest-1.cisco.com \ \b
-p ietf-interfaces:interfaces \ \b
-d '{
"interface":[
{
"name":"Loopback999",
"description":"created by python click - PATCH",
"type":"iana-if-type:softwareLoopback",
"enabled":true,
"ietf-ip:ipv4":{
"address":[
{
"ip":"10.0.1.10",
"netmask":"255.255.255.255"
}
]
}
}
]
}'
\b
# Configure from file for PATCH operation
$ restconf-cli PATCH -u developer \ \b
-n sandbox-iosxe-latest-1.cisco.com \ \b
-p ietf-interfaces:interfaces/interface=Loopback999 -ff interface.json
'''
try:
headers = {'Accept': accept, 'Content-Type': content_type}
url = f"https://{hostname}:{port}/restconf/data/{path}"
if from_file:
payload = from_file.read()
else:
payload = data
response = requests.patch(url,
auth=(username, password),
headers=headers,
data=payload,
verify=False)
if response.status_code == 204:
click.echo(print(f"\nResource has been updated successfully: {response.status_code} OK"))
else:
click.echo(print(f"\nRequest Failed: {response}"))
except requests.RequestException as e:
click.echo(print(e))
# Click command 'DELETE'
@click.command(name="DELETE", context_settings=dict(help_option_names=['-h', '--help']))
@click.option("--hostname", "-n", type=str, required=True, help="Device hostname or IP address for the restconf API")
@click.option("--username", "-u", type=str, required=True, help="Username for restconf api")
@click.option('--password', prompt=True, hide_input=True, confirmation_prompt=False, help="Password for restconf api")
@click.option("--path", "-p", type=str, required=True, help="Path for restconf api call")
@click.option("--port", "-pn", type=int, required=False, default=443, help="Port number for restconf api, default is 443")
@click.option("--accept", "-a", type=str, required=False, default='application/yang-data+json', help="Accept header for restconf api, default is application/yang-data+json")
@click.option("--content-type", "-c", type=str, required=False, default='application/yang-data+json', help="Content-Type header for restconf api, default is application/yang-data+json")
def restconf_delete(hostname, username, password, path, port, accept, content_type):
'''
Method to delete the target resource
\b
Example:
\b
$ restconf-cli DELETE -u developer -n sandbox-iosxe-latest-1.cisco.com \ \b
-p ietf-interfaces:interfaces/interface=Loopback999
'''
try:
headers = {'Accept': accept, 'Content-Type': content_type}
url = f"https://{hostname}:{port}/restconf/data/{path}"
response = requests.delete(url,
auth=(username, password),
headers=headers,
verify=False)
if response.status_code == 204:
click.echo(print(f"\nResource has been deleted: {response.status_code} OK"))
else:
click.echo(print(f"\nRequest Failed: {response}"))
except requests.RequestException as e:
click.echo(print(e))
# attach child commands to the parent function
restconf_cli.add_command(restconf_get)
restconf_cli.add_command(restconf_post)
restconf_cli.add_command(restconf_put)
restconf_cli.add_command(restconf_patch)
restconf_cli.add_command(restconf_delete)
if __name__ == '__main__':
restconf_cli()