-
Notifications
You must be signed in to change notification settings - Fork 44
Expand file tree
/
Copy pathaxl_addGateway.py
More file actions
339 lines (270 loc) · 10.6 KB
/
Copy pathaxl_addGateway.py
File metadata and controls
339 lines (270 loc) · 10.6 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
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
"""AXL <addGateway>, <addGatewayEndpointAnalogAccess> sample script, using the Zeep SOAP library
Creates a VG310 MGCP gateway with unit VG-2VWIC-MBRD and subunit 24FXS, then
adds a new analog/POTS port/line to the subunit. Once the gateway is created
the gateway and endpoint data is retrieved to produce a simple report of the
gateway/unit/subunit/port/line configuration. Finally all created
objects are deleted.
Copyright (c) 2023 Cisco and/or its affiliates.
Permission is hereby granted, free of charge, to any person obtaining a copy
of this software and associated documentation files (the 'Software'), to deal
in the Software without restriction, including without limitation the rights
to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
copies of the Software, and to permit persons to whom the Software is
furnished to do so, subject to the following conditions:
The above copyright notice and this permission notice shall be included in all
copies or substantial portions of the Software.
THE SOFTWARE IS PROVIDED 'AS IS', WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
SOFTWARE.
"""
from lxml import etree
from requests import Session
from requests.auth import HTTPBasicAuth
from zeep import Client, Settings, Plugin, xsd
from zeep.transports import Transport
from zeep.exceptions import Fault
import sys
import urllib3
# Edit .env file to specify your Webex site/user details
import os
from dotenv import load_dotenv
load_dotenv()
# Change to true to enable output of request/response headers and XML
DEBUG = False
# The WSDL is a local file in the working directory, see README
WSDL_FILE = "schema/AXLAPI.wsdl"
# This class lets you view the incoming and outgoing http headers and XML
class MyLoggingPlugin(Plugin):
def egress(self, envelope, http_headers, operation, binding_options):
# Format the request body as pretty printed XML
xml = etree.tostring(envelope, pretty_print=True, encoding="unicode")
print(f"\nRequest\n-------\nHeaders:\n{ http_headers }\n\nBody:\n{ xml }")
def ingress(self, envelope, http_headers, operation):
# Format the response body as pretty printed XML
xml = etree.tostring(envelope, pretty_print=True, encoding="unicode")
print(f"\nResponse\n-------\nHeaders:\n{ http_headers }\n\nBody:\n{ xml }")
# The first step is to create a SOAP client session
session = Session()
# We avoid certificate verification by default
# And disable insecure request warnings to keep the output clear
session.verify = False
urllib3.disable_warnings(urllib3.exceptions.InsecureRequestWarning)
# To enable SSL cert checking (recommended for production)
# place the CUCM Tomcat cert .pem file in the root of the project
# and uncomment the two lines below
# CERT = 'changeme.pem'
# session.verify = CERT
session.auth = HTTPBasicAuth(os.getenv("AXL_USERNAME"), os.getenv("AXL_PASSWORD"))
transport = Transport(session=session, timeout=10)
# strict=False is not always necessary, but it allows Zeep to parse imperfect XML
settings = Settings(strict=False, xml_huge_tree=True)
# If debug output is requested, add the MyLoggingPlugin callback
plugin = [MyLoggingPlugin()] if DEBUG else []
# Create the Zeep client with the specified settings
client = Client(WSDL_FILE, settings=settings, transport=transport, plugins=plugin)
# Create the Zeep service binding to AXL at the specified CUCM
service = client.create_service(
"{http://www.cisco.com/AXLAPIService/}AXLAPIBinding",
f'https://{os.getenv( "CUCM_ADDRESS" )}:8443/axl/',
)
# # Create an gateway object specifying VG310 MGCP gateway with
# # VG-2VWIC-MBRD unit and 24FXS subunit
domain = "testVG310"
unit = 0
subunit = 0
gateway = {
"domainName": domain,
"product": "VG310",
"protocol": "MGCP",
"callManagerGroupName": "Default",
"units": {
"unit": [
{
"index": unit,
"product": "VG-2VWIC-MBRD",
"subunits": {
"subunit": [{"index": subunit, "product": "24FXS", "beginPort": 0}]
},
}
]
},
}
# To add vendorConfig items, create lxml Element objects and append to
# an array named vendorConfig, a child element under <units>
ModemPassthrough = etree.Element("ModemPassthrough")
ModemPassthrough.text = "Disable"
T38FaxRelay = etree.Element("T38FaxRelay")
T38FaxRelay.text = "Enable"
DtmfRelay = etree.Element("DtmfRelay")
DtmfRelay.text = "NTE-CA"
# Append each top-level element to an array
vendorConfig = []
vendorConfig.append(ModemPassthrough)
vendorConfig.append(T38FaxRelay)
vendorConfig.append(DtmfRelay)
# Create a Zeep xsd type object of type XVendorConfig from the client object
xvcType = client.get_type("ns0:XVendorConfig")
# Use the XVendorConfig type object to create a vendorConfig object
# using the array of vendorConfig elements from above, and set as
# phone.vendorConfig
gateway["vendorConfig"] = xvcType(vendorConfig)
# Execute the addGateway request
try:
resp = service.addGateway(gateway)
except Fault as err:
print(f"Zeep error: addGateway: { err }")
sys.exit(1)
print("\naddGateway response:\n")
print(resp, "\n")
input("Press Enter to continue...")
# Create a line which will be added to the gateway port
line = {
"pattern": "9876543210",
"description": "Test Line",
"usage": "Device",
"routePartitionName": None,
}
# Execute the addLine request
try:
resp = service.addLine(line)
except Fault as err:
print(f"Zeep error: addLine: { err }")
sys.exit(1)
print("\naddLine response:\n")
print(resp, "\n")
input("Press Enter to continue...")
# Create a gateway analog access endpoint object
# This should be close to the minimum possible fields
portName = f"AALN/S{ unit }/SU{ subunit }/0@{ domain }"
endpoint = {
"domainName": domain,
"unit": unit,
"subunit": subunit,
"endpoint": {
"index": 0,
"name": portName,
"product": "Cisco MGCP FXS Port",
"class": "Gateway",
"protocol": "Analog Access",
"protocolSide": "User",
"devicePoolName": "Default",
"locationName": "Hub_None",
"port": {
"portNumber": 1,
"callerIdEnable": False,
"callingPartySelection": "Originator",
"expectedDigits": 10,
"sigDigits": {"_value_1": 10, "enable": False},
"lines": {
"line": [
{
"index": 1,
"dirn": {"pattern": "9876543210", "routePartitionName": None},
}
]
},
"presentationBit": "Allowed",
"silenceSuppressionThreshold": "Disable",
"smdiPortNumber": 2048,
"trunk": "POTS",
"trunkDirection": "Bothways",
"trunkLevel": "ONS",
"trunkPadRx": "NoDbPadding",
"trunkPadTx": "NoDbPadding",
"timer1": 200,
"timer2": 0,
"timer3": 100,
"timer4": 1000,
"timer5": 0,
"timer6": 0,
},
"trunkSelectionOrder": "Top Down",
},
}
# Execute the addGatewayEndpointAnalogAccess request
try:
resp = service.addGatewayEndpointAnalogAccess(endpoint)
except Fault as err:
print(f"Zeep error: addGatewayEndpointAnalogAccess: { err }")
sys.exit(1)
print("\naddGatewayEndpointAnalogAccess response:\n")
print(resp, "\n")
input("Press Enter to continue...")
# Get the gateway details
try:
resp = service.getGateway(domainName=domain)
except Fault as err:
print(f"Zeep error: getGateway: { err }")
sys.exit(1)
gateway = resp["return"]["gateway"]
print("\ngetGateway: Success\n")
print(f"\n==> Gateway uuid: { gateway['uuid'] }\n")
input("Press Enter to continue...")
# There is currently not a good way to retrieve the endpoints associated
# a MGCP gateway using regular AXL requests - <executeSQLQuery> will be used.
# Raw UUID values in the CUCM database are stored without braces ("{}")
# and in lower case - regular AXL requests normalize these by uppercasing
# and surrouding with braces. This must be undone to use the uuid in
# an <executeSQLQuery> request.
raw_uuid = gateway["uuid"].lower()[1:-1]
sql = f"SELECT * FROM mgcpdevicemember WHERE fkmgcp='{raw_uuid}'"
try:
resp = service.executeSQLQuery(sql=sql)
except Fault as err:
print(f"Zeep error: executeSQLQuery: { err }")
sys.exit(1)
ports = resp["return"]["row"]
print("\nexecuteSQLQuery: Success")
print(f"\n==> Port count: { len(ports) }\n")
input("Press Enter to continue...")
# Print report header
print("\nGateway Details")
print("===============")
print(f"Domain: { gateway['domainName']}\n")
print("End-Point Name Port DN ")
print("----------------------- ------------")
# Get details for each port and print the details
# <executeSQLQuery> return is an "xsd:any" type, which Zeep models
# as a array of rows, with database column name as the tag property.
# We'll create a function to access this data in a more intuitive way
def get_column(tag, row):
element = list(filter(lambda x: x.tag == tag, row))
return element[0].text if len(element) > 0 else None
for port in ports:
try:
resp = service.getGatewayEndpointAnalogAccess(uuid=get_column("fkdevice", port))
except Fault as err:
print(f"Zeep error: getGatewayEndpointAnalogAccess: { err }")
sys.exit(1)
name = resp["return"]["gatewayEndpointAnalogAccess"]["endpoint"]["name"]
dn = resp["return"]["gatewayEndpointAnalogAccess"]["endpoint"]["port"]["lines"][
"line"
]["dirn"]["pattern"]
print(f"{name.rjust(23)} {dn.rjust(12)}")
input("\nPress Enter to continue...")
# Cleanup the objects we just created
try:
resp = service.removeGatewayEndpointAnalogAccess(name=portName)
except Fault as err:
print(f"Zeep error: removeGatewayEndpointAnalogAccess: { err }")
sys.exit(1)
print("\nremoveGatewayEndpointAnalogAccess response:")
print(resp, "\n")
try:
resp = service.removeLine(pattern="9876543210", routePartitionName=None)
except Fault as err:
print(f"Zeep error: removeLine: { err }")
sys.exit(1)
print("\nremoveLine response:")
print(resp, "\n")
try:
resp = service.removeGateway(domainName="testVG310")
except Fault as err:
print(f"Zeep error: removeGateway: { err }")
sys.exit(1)
print("\nremoveGateway response:")
print(resp, "\n")