Add and Delete a Group with Zone and Subnet Data
This example creates (or deletes and recreates if it already exists) a Group, then adds distinct Zones and subnets to it.
#!/usr/bin/env -S uv run --script
# /// script
# requires-python = ">=3.12"
# dependencies = [
# "requests",
# ]
# ///
"""Creates/recreates a Group and adds Zones and subnets to it"""
import requests
import json
import urllib.parse
# Enter your rWeb address here
BASE_URL = 'https://rweb.local.com'
HEADERS = {'Content-Type':'application/json',
'Accept': 'application/json'}
# Enter your user credentials here
CREDENTIALS = {'login':'admin', 'password':'admin123'}
def url(resource, params=None):
"""Turn a resource into a url.
Uses BASE_URL and optionally encodes a hash of parameters"""
querystring = ""
if params != None:
querystring = "?"+urllib.parse.urlencode(params)
return BASE_URL + resource + querystring
def wrap(data):
"""Convert an object to an rWeb suitable json string
Wraps the data in the standard rweb {'data': } object """
return json.dumps({'data': data})
def login(session):
"""Log in to a session.
The authentication cookie is saved to the session"""
result = session.post(url('/authentication'),
wrap(CREDENTIALS))
if result.status_code != requests.codes.created:
print(f"Expected status code: {requests.codes.created}")
raise Exception(f"Login failed with status code {result.status_code}")
def logout(session):
"""Close a session"""
session.delete(url('/authentication'))
def get_test_group(session):
"""Creates/Recreates a test group.
The group 'AUTOTESTgroup' will be deleted if it exists. It will
then be recreated as a blank group"""
result = session.get(url('/groups', {'name': 'AUTOTESTgroup'}))
assert(result.status_code == requests.codes.ok)
group_list = json.loads(result.content)
assert(group_list['rows'] <= 1)
if group_list['rows'] != 0:
for group in group_list['data']:
result = session.delete(url(group['group_resource']))
assert(result.status_code == requests.codes.ok)
result = session.post(url('/groups'),
wrap({'name':'AUTOTESTgroup'}))
assert(result.status_code == requests.codes.created)
group = json.loads(result.content)
return group
def main():
with requests.session() as session:
session.headers = HEADERS
# This is insecure but may be needed if you haven't set up an SSL certificate for rWeb yet
session.verify = False
login(session)
# Create/Recreate group
group = get_test_group(session)
for i in range(1,10):
zone_name = 'Zone {0}'.format(i)
print("Creating '{0}'".format(zone_name))
# Create zone
result = session.post(url(group['zones_resource']),
wrap({'name':zone_name}))
assert(result.status_code == requests.codes.created)
zone = json.loads(result.content)
# Create a single subnet
result = session.post(url(zone['subnets_resource']),
wrap({'subnet':'240.{0}.0.0/24'.format(i)}))
assert(result.status_code == requests.codes.created)
# Create multiple subnets at once
ips = ['240.{0}.{1}.0/24'.format(i,j) for j in range(1, 10)]
subnets = [{'subnet':ip} for ip in ips]
result = session.post(url(zone['subnets_resource']),
wrap(subnets))
assert(result.status_code == requests.codes.created)
logout(session)
if __name__ == '__main__':
main()