Cisco Unity Connection Provisioning Interface (CUPI) API

Hey people,

Coming back to the DEV topics, today I’m going to give you a quick overview of Unity API.
It’s very simple, but it will give different perspectives of what you can automate on Unity.

CUPI is a provisioning API for Cisco Unity Connection that has been designed to be stable and simple to use. It is based on leading industry standards for web-based API development, and provides access to the most commonly provisioned data on Connection systems (users, contacts, distribution lists, and call handlers).

By using CUPI, you can securely do the following:

  • Create, read, update, and delete users and user configurations
  • Reset passwords
  • Create, read, and update distribution lists
  • Create, read, update, and delete call handlers
  • Create, read, update, and delete contacts

Getting the Schema Details

All the schema details for all supported object types can be obtained by going to the REST schema page using the URL:
                                                          http://{server name}/vmrest/schema

In the case of users the schema shows what will come back when fetching the full user data using a URL like this:
                                                   http://{server name}/vmrest/users/{object_id}

Authentication

CUPI uses the same authentication and authorization scheme that the administration console uses. This means that the objects an administrator has access to when authenticated are determined by the roles to which the administrator is assigned.

Basic Operations

Searching For an user:
This request gives us all details about an specific user, searching it by the alias.

To search for a user account, do the following GET request:
GET http://<connection-server>/vmrest/users?query=(alias%20startswith%20ab)

You can have your results in XLM or JSON. It’s up to you. The only difference will be on how you manipulate that, to achieve your goal.
In XML, you will see this:

imageimage

If you want to change, or create something new, you need to send a PUT or a POST request.
And, depending on your request, you have to search the user via user-objectID, instead of Alias. In this case, you have to send a request to get information from an user, save its ObjectID, and then use it in another request. See some samples below:

Listing User PIN Settings
Shows information about user’s PIN:  

                           GET https://<Connection-server>/vmrest/users/<user-objectid>/credential/pin

The following is the response from the above *GET* request and the actual response will depend upon the information given by you:

image

Changing PIN
In this case, we are going to use PUT, and we also have to send the new PIN in the Body:                    

PUT https://<Connection-server>/vmrest/users/<user-objectid>/credential/pin
<Credential>
      <Credentials>ciscfo1234</Credentials>
</Credential>

This must be your response, indicating a success: Response Code: 204

Creating a User

To create a user account, do the following POST request:

POST http://<connection-server>/vmrest/users?templateAlias=voicemailusertemplate
<?xml version=”1.0″ encoding=”UTF-8″ standalone=”yes”?>
<User>
    <Alias>jdoe</Alias>
    <DtmfAccessId>7890</DtmfAccessId>
</User>

The following is the result of the above POST request: 201 Created

Modifying a User

To modify a user account, do the following PUT request:

PUT http://<connection-server>/vmrest/users/{objectid}

<?xml version=”1.0″ encoding=”UTF-8″ standalone=”yes”?>
<User>
<DisplayName>johnd</DisplayName>
</User>

The following is the result of the above PUT request: 204 Accepted

Deleting a User

To delete a user account, do the following DELETE request:

                                           DELETE http://<connection-server>/vmrest/users/{objectid}

The following is the result of the above DELETE request: 200 OK

These were only some samples of what you can do using CUPI. Of course, there are dozes, or hundreds of types of request.
Any specific request you want to do and don’t know how, let me know in the comments.

I hope you enjoy this post! Smile

See ya!

Bruno

Cisco CUCM – AXL API requests using Python

Hey guys,

Following my post about the overview of Cisco CUCM – SOAP (read it HERE), I’m going to show you now how to send some basic requests using Python.

To be able to do that, you will need to have:

  • Python installed (download it here)
  • AXLSQLToolkit
  • Python Libraries (Zeep, urllib3 , requests – installed via PIP)

After installing Python and its libraries, let’s go to the codes!

To run my codes, I use PyCharm….but you can use any other software of your preference.

Firstly, you have to declare your libraries:
*Code will be passed at the end of the article Smile

image

Now you have to enter your CUCM information, such as IP, username and password.
We are going to use ZEEP to create SOAP requests. In case of any fault, Zeep will show what SOAP envelope that was sent and the response from CUCM AXL.
If you’re not disabling SSL verification, host should be the FQDN of the server rather than IP.


image

To start with a simple request, I’ll show you how to list Phones.
Have in hands the  Cisco DevNet AXL Schema Reference. It will help you to understand each request, which argument you must send as a searchCriteria and which arguments you must expect as returnedTags.
Only declared arguments in the returnedTags will be displayed. The rest will be showed as none.

For example, I want to list a phone, based on the Device Name, and want to have the arguments namedescription, model and device pool being returned to me.
The code will look like this:

image

The result will like this:

{
     ‘return’: {
         ‘phone’: [
             {
                 ‘name’: ‘SEP0004F2F01F1A’,
                 ‘description’: ‘Meeting Room’,
                 ‘product’
: None,
                 ‘model’: ‘Cisco 7937’,
                 ‘class’: None,
                 ‘protocol’: None,
                 ‘protocolSide’: None,
                 ‘callingSearchSpaceName’: None,
                 ‘devicePoolName’: {
                     ‘_value_1’: ‘BE_KNO_DP’,
                     ‘uuid’: ‘{960A36D4-C7ED-49B8-A53C-B188BE30635A}’
                 },
                 ‘commonDeviceConfigName’: None,
                 ‘commonPhoneConfigName’: None,
                 ‘networkLocation’: None,
                 ‘locationName’: None,
                 ‘mediaResourceListName’: None,
                 ‘networkHoldMohAudioSourceId’: None,
                 ‘userHoldMohAudioSourceId’: None,
                 ‘automatedAlternateRoutingCssName’: None,
                 ‘aarNeighborhoodName’: None,
                 ‘loadInformation’: None,
                 ‘traceFlag’: None,
                 ‘mlppIndicationStatus’: None,
                 ‘preemption’: None,
                 ‘useTrustedRelayPoint’: None,
                 ‘retryVideoCallAsAudio’: None,
                 ‘securityProfileName’: None,
                 ‘sipProfileName’: None,
                 ‘cgpnTransformationCssName’: None,
                 ‘useDevicePoolCgpnTransformCss’: None,
                 ‘geoLocationName’: None,
                 ‘geoLocationFilterName’: None,
                 ‘sendGeoLocation’: None,
                 ‘numberOfButtons’: None,
                 ‘phoneTemplateName’: None,
                 ‘primaryPhoneName’: None,
                 ‘ringSettingIdleBlfAudibleAlert’: None,
                 ‘ringSettingBusyBlfAudibleAlert’: None,
                 ‘userLocale’: None,
                 ‘networkLocale’: None,
                 ‘idleTimeout’: None,
                 ‘authenticationUrl’: None,
                 ‘directoryUrl’: None,
                 ‘idleUrl’: None,
                 ‘informationUrl’: None,
                 ‘messagesUrl’: None,
                 ‘proxyServerUrl’: None,
                 ‘servicesUrl’: None,
                 ‘softkeyTemplateName’: None,
                 ‘loginUserId’: None,
                 ‘defaultProfileName’: None,
                 ‘enableExtensionMobility’: None,
                 ‘currentProfileName’: None,
                 ‘loginTime’: None,
                 ‘loginDuration’: None,
                 ‘currentConfig’: None,
                 ‘singleButtonBarge’: None,
                 ‘joinAcrossLines’: None,
                 ‘builtInBridgeStatus’: None,
                 ‘callInfoPrivacyStatus’: None,
                 ‘hlogStatus’: None,
                 ‘ownerUserName’: None,
                 ‘ignorePresentationIndicators’: None,
                 ‘packetCaptureMode’: None,
                 ‘packetCaptureDuration’: None,
                 ‘subscribeCallingSearchSpaceName’: None,
                 ‘rerouteCallingSearchSpaceName’: None,
                 ‘allowCtiControlFlag’: None,
                 ‘presenceGroupName’: None,
                 ‘unattendedPort’: None,
                 ‘requireDtmfReception’: None,
                 ‘rfc2833Disabled’: None,
                 ‘certificateOperation’: None,
                 ‘authenticationMode’: None,
                 ‘keySize’: None,
                 ‘keyOrder’: None,
                 ‘ecKeySize’: None,
                 ‘authenticationString’: None,
                 ‘certificateStatus’: None,
                 ‘upgradeFinishTime’: None,
                 ‘deviceMobilityMode’: None,
                 ‘roamingDevicePoolName’: None,
                 ‘remoteDevice’: None,
                 ‘dndOption’: None,
                 ‘dndRingSetting’: None,
                 ‘dndStatus’: None,
                 ‘isActive’: None,
                 ‘isDualMode’: None,
                 ‘mobilityUserIdName’: None,
                 ‘phoneSuite’: None,
                 ‘phoneServiceDisplay’: None,
                 ‘isProtected’: None,
                 ‘mtpRequired’: None,
                 ‘mtpPreferedCodec’: None,
                 ‘dialRulesName’: None,
                 ‘sshUserId’: None,
                 ‘digestUser’: None,
                 ‘outboundCallRollover’: None,
                 ‘hotlineDevice’: None,
                 ‘secureInformationUrl’: None,
                 ‘secureDirectoryUrl’: None,
                 ‘secureMessageUrl’: None,
                 ‘secureServicesUrl’: None,
                 ‘secureAuthenticationUrl’: None,
                 ‘secureIdleUrl’: None,
                 ‘alwaysUsePrimeLine’: None,
                 ‘alwaysUsePrimeLineForVoiceMessage’: None,
                 ‘featureControlPolicy’: None,
                 ‘deviceTrustMode’: None,
                 ‘earlyOfferSupportForVoiceCall’: None,
                 ‘requireThirdPartyRegistration’: None,
                 ‘blockIncomingCallsWhenRoaming’: None,
                 ‘homeNetworkId’: None,
                 ‘AllowPresentationSharingUsingBfcp’: None,
                 ‘confidentialAccess’: None,
                 ‘requireOffPremiseLocation’: None,
                 ‘allowiXApplicableMedia’: None,
                 ‘enableCallRoutingToRdWhenNoneIsActive’: None,
                 ‘ctiid’: None,
                 ‘uuid’: ‘{81F827A6-3B58-F7F0-39BF-DBA51E81B606}’
             }
         ]
     },
     ‘sequence’: None
}

As I mentioned, if you don’t declare you want to have your argument being returned, it will be displayed as None.

Right. Now, you have to use your Python skills to take any action based on your output.
For example, if you want to isolate the returned tags to save them in a variable, you can use a For Loop to do something like that:

image
And the result will be this:

image

Now, you can use the Cisco DevNet AXL Schema Reference to explore all possibilities you have.

You can, for example, add new phones, new lines…

Adding Lines

According to the Schema, you don’t have Search Criteria or Returned Tags in the addLine request.
So, the code you be like this:

image

This is the line we’ve just added:

image

As I always say…now, sky is the limit!
You can do whatever you want by following the Schema….like add/delete/list Phones, lines, Device Pool, Device Profile, etc, etc, etc…

Hope you liked it Smile

See you!

Whole Code

from zeep import Client
from zeep.cache import SqliteCache
from zeep.transports import Transport
from zeep.exceptions import Fault
from zeep.plugins import HistoryPlugin
from requests import Session
from requests.auth import HTTPBasicAuth
from urllib3 import disable_warnings
from urllib3.exceptions import InsecureRequestWarning
from lxml import etree

disable_warnings(InsecureRequestWarning)

username = ‘admin’
password = ‘Cisco123’

hostIP = ‘192.168.1.10’
location = ‘https://192.168.1.10:8443/axl/’.format(host=hostIP)
binding = “{http://www.cisco.com/AXLAPIService/}AXLAPIBinding”
wsdl = ‘file://C:/Users/user123/AppData/Local/Programs/Python/Python38-32/axlsqltoolkit/schema/11.5/AXLAPI.wsdl’

session = Session()
session.verify = False
session.auth = HTTPBasicAuth(username, password)

transport = Transport(cache=SqliteCache(), session=session, timeout=20)
history = HistoryPlugin()
client = Client(wsdl=wsdl, transport=transport, plugins=[history])
service = client.create_service(binding, location)

def show_history():
     for hist in [history.last_sent, history.last_received]:
         print(etree.tostring(hist[“envelope”], encoding=”unicode”, pretty_print=True))

try:
     resp = service.listPhone(searchCriteria={‘name’: ‘SEP0004F2F01F1A’},
                              returnedTags={‘name’: ”, ‘description’: ”,
                                            ‘model’: ”, ‘devicePoolName’: ”})
     print(resp)
except Fault:
     show_history()

phone_list = resp[‘return’].phone
for phone in phone_list:
     print(phone[‘name’])
     print(phone[‘description’])
     print(phone[‘model’])
     print(phone[‘devicePoolName’]._value_1)

try:
     resp = service.addLine(line={‘pattern’: ‘707080’, ‘usage’: ‘Device’,
                                  ‘description’: ‘Test’, ‘routePartitionName’: ‘ONCLUSTER’})
     print(resp)
except Fault:
     show_history()

UCCX – Queries using Python Script

Hey guys,

As promised in my post about ODBC Connection, (you can read it HERE), I’m going to show you how to create a basic Script using Python to query some information from UCCX, which can be useful to create some personalized Dashboards.

Even though we have many types of reports on CUIC, sometime they don’t meet our expectations by having too much unnecessary information or by lack of information.

I’ have decided to use Python, along with HTML, to create my own Dashboard. So I can have only information I know is 100% useful.

First of all, you have to create the ODBC connection to the server where you are going to place the script.
Again, you can use THIS POST to help you out.

Once you have the ODBC Connection working, it’s time to work on your script.

To be able to connect your script to your ODBC, you need to have a PYODBC python Library installed. To be able to better manipulate date and time, I’m also using datetime library.

The first part of the script is used to establish a connection to your ODBC. So you need to fill all its information in the connection strings. It’s important to mention that pyodbc does not even look at the connection string. It is passed directly to the database driver.

To start off my code, I’ll call the libraries and use the command conn = pyodbc.connect to connect to my ODBC.

image

Connection is now ready!
Now it’s time to choose a query to be sent. That query is sent using SQL commands.
This means you can use your SQL skills to play with queries and create interesting reports

Smile

In the below example, I wanted to know how many licenses are being consumed daily.
To do that, I’ll use the SQL command: ” {call sp_license_utilization(‘2021-05-05 00:00:01′,’2021-05-05 23:00:01′,’0′,’1’)}”. The line in the script will be like that:

cursor.execute(” {call sp_license_utilization(‘2021-05-05 00:00:01′,’2021-05-05 23:00:01′,’0′,’1’)}”)

If you print the result, you will see something like that:

[(datetime.datetime(2021, 4, 16, 0, 0, 1), 1, 0, 3), (datetime.datetime(2021, 4, 16, 1, 0, 1), 0, 0, 4), (datetime.datetime(2021, 4, 16, 2, 0, 1), 0, 0, 4), (datetime.datetime(2021, 4, 16, 3, 0, 1), 0, 0, 4), (datetime.datetime(2021, 4, 16, 4, 0, 1), 1, 0, 6), (datetime.datetime(2021, 4, 16, 5, 0, 1), 0, 0, 18), (datetime.datetime(2021, 4, 16, 6, 0, 1), 2, 0, 43), (datetime.datetime(2021, 4, 16, 7, 0, 1), 4, 0, 58), (datetime.datetime(2021, 4, 16, 8, 0, 1), 9, 0, 63), (datetime.datetime(2021, 4, 16, 9, 0, 1), 6, 0, 64), (datetime.datetime(2021, 4, 16, 10, 0, 1), 5, 0, 62), (datetime.datetime(2021, 4, 16, 11, 0, 1), 4, 0, 51), (datetime.datetime(2021, 4, 16, 12, 0, 1), 5, 0, 51), (datetime.datetime(2021, 4, 16, 13, 0, 1), 4, 0, 49), (datetime.datetime(2021, 4, 16, 14, 0, 1), 4, 0, 39), (datetime.datetime(2021, 4, 16, 15, 0, 1), 3, 0, 27), (datetime.datetime(2021, 4, 16, 16, 0, 1), 2, 0, 15), (datetime.datetime(2021, 4, 16, 17, 0, 1), 0, 0, 10), (datetime.datetime(2021, 4, 16, 18, 0, 1), 1, 0, 8), (datetime.datetime(2021, 4, 16, 19, 0, 1), 0, 0, 6), (datetime.datetime(2021, 4, 16, 20, 0, 1), 0, 0, 6), (datetime.datetime(2021, 4, 16, 21, 0, 1), 0, 0, 6), (datetime.datetime(2021, 4, 16, 22, 0, 1), 0, 0, 5), (datetime.datetime(2021, 4, 16, 23, 0, 1), 0, 0, 5)]

Then, use Python to manipulate the results according to your needs. In my case, I’m using the datetime to get today’s date. I also created a list to save the values, as this code will check the license each hour, and give me the maximum as a final result.

The full code for this sample is:

image

 

import pyodbc
from datetime import datetime

conn = pyodbc.connect(‘DRIVER={IBM INFORMIX ODBC DRIVER};’
‘UID=uccxhruser;PWD=123456;’
‘DATABASE=db_cra;’
‘HOST=uccxlab.com;’
‘SERVER=uccxlab_uccx;’
‘SERVICE=1504;PROTOCOL=onsoctcp;CLIENT_LOCALE=en_US.UTF8;DB_LOCALE=en_US.UTF8’)
cursor = conn.cursor()

listItem = []
listLicCCX = []
timestampStr = datetime.now().strftime(“%Y-%m-%d”)

try:
cursor.execute(” {call sp_license_utilization(‘” + str(timestampStr) + ” 00:00:01′,'” + str(timestampStr) + ” 23:59:59′,’0′,’1’)}”)
rows = cursor.fetchall()
LicenseUsage = rows
for hourly in LicenseUsage:
if hourly[3] != None:
listItem.insert(0, hourly[3])
else:
listItem.insert(0, 0)
except pyodbc.Error as ex:
print(“An exception occurred”)
listItem.insert(0, 0)
listLicCCX.insert(0, (max(listItem)))

print(listLicCCX)

And this is the final result:

image

Remember you can use any SQL Query!

For example, this is the SQL query to get a list of Agents by Team:select s.resourceLoginID,s.resourceFirstName,s.resourceLastName,s.extension, t.teamname from Resource s inner join team t on s.assignedTeamID = t.teamid where s.active = ‘t’ and t.active = ‘t’ and t.teamname = ‘UCCX_TEAM’ order by t.teamname, s.resourceloginid

Using a simple Select * from rtcsqssummary here csqname = ‘<CSQ Name>’ query you can display more information as this query will return the following information.

csqname
loggedinagents
availableagents
unavailableagents
totalcalls
oldestcontact
callshandled
callsabandonded
callsdequeued
avgtalkduration
avgwaitduration
longesttalkduration
longestwaitduration
callswaiting
enddatetime
workingagents
talkingagents
reservedagents
startdatetime
convavgtalkduration
convavgwaitduration
convlongestwaitduration
convlongestwaitduration
convoldestcontact

The sky is the limit!

Smile

Now that you now how to use SQL queries in Python, you can start creating your own script!

Enjoy!

Bruno

Cisco CUCM – SOAP Overview

Hey guys,

Today I’m going to talk about SOAP AXL. A powerful and useful type of communication model. Most of the Cisco Unified Communications Manager (CUCM) APIs are exposed via SOAP-based XML Web Services.
I’ve been using it to create some Dashboards for CUCM!

The Administrative XML Web Service (AXL) is a XML/SOAP based interface that provides a mechanism for inserting, retrieving, updating and removing data from the Unified Communication configuration database.
Developers can use AXL and the provided WSDL to Create, Read, Update, and Delete objects such as gateways, users, devices, route-patterns and much more.

SOAP provides an XML-based communication protocol and encoding format for communication. For example, to describe a phone using XML, you would define the following structure.

image

Now, how do you know what types of requests you are allowed to make, what types of data those requests require, and what type of response you expect to receive?
This is where the Web Services Description Language (WSDL) comes into play. A WSDL file (along with any associated XML schema files) can be used to fully describe the capabilities of a SOAP API.

Luckily  CUCM provides a WSDL file for each of the SOAP-based APIs it supports and there are tools to read WSDL files and then make the SOAP API service methods available easily. The eventual goal is to leverage a programing language such as Python (I’ll cover that in future posts) to interface with the various SOAP API’s, but it helps to manually explore the API using a visual tool that can understand the WSDL file. One of these tools is SoapUI, and you can download it from here HERE.

Let’s see now step by step how to use SOAP and send some requests.

Step 1 – Download the AXL API WSDL File

The CUCM AXL API WSDL file is published on the CUCM server itself, as part of the Cisco AXL Toolkit plugin.

  • Access your CUCM
  • Navigate to ApplicationPlugins and click Find
  • Next to Cisco AXL Toolkit, click Download. The file axlsqltoolkit.zip is downloaded.
  • From your Downloads folder, extract this downloaded file (right-click Extract All…) to the default location (should be in the Downloads\axlsqltoolkit folder)
  • Once extracted, in the schema folder you will notice there are a number of folders. These are for various older CUCM versions. For this lab, we are interested in current. That folder contains the current CUCM’s AXL WSDL (AXLAPI.wsdl) and schema (.xsd) files.

Step 2 – Start SoapUI

Now you can load this WSDL into SoapUI, get things configured, and start sending queries. Follow these steps to load the WSDL into SoapUI.

  • Launch the SoapUI application.
  • Close any open Endpoint Explorer or other windows that may show up when launching SoapUI.
  • Click FileNew SOAP Project

image

  • For the Project Name enter UCMSOAP
  • Below that field, for the Initial WSDL file, click Browse. Navigate to your current AXL WSDL file extracted earlier:

Step 3 – Run an AXL Request from SoapUI

Once the API is loaded, you must set some of the default parameters, specifically the CUCM hostname or IP address and the credentials so that they don’t have to be re-entered for every query.

  • In SoapUI, in the Navigator pane on the left, you’ll see the new project folder named UCMSOAP and the AXLAPIBinding object. Right-click on the AXLAPIBinding and click Show Interface Viewer (same as double-clicking or pressing Enter).

image

  • In the AXLAPIBinding properties, select the Service Endpoints tab.

image

  • You’ll notice the Endpoint is set to https://CCMSERVERNAME:8443/axl/ (with blank username and password)
  • Double-click on CCMSERVERNAME so it can be edited and replaced by the hostname of your CUCM. Press Enter
  • Double-click on the Username and Password to enter the credentials. Be sure to press Enter for the field to be saved.
  • Close the AXLAPIBinding window by clicking the X in the right of its blue title bar .

So now SOAP is all set up and ready for issuing queries.
I’ll give you now an example of how to do that.

For example, a basic thing as getting the CUCM Version:

  • Choose AXLAPIBinding
  • Scroll Down till getCCMVersion. Expand it and you will find Request 1.
  • Double-click to open it, and you will find its XML Request.

image

You will observe there is a ?  in the processNodeName field. When a new request is created for an operation in SoapUI, all available options are presented, so there are often many that either need to be removed or filled in with valid data (instead of the default ? placeholder).

So, remove it, and click in the green button to send this request. The Response will show up at right:

image

You have successfully sent an AXL/SOAP request to CUCM and received a valid response!!
From now on you can start playing with other types of requisitions, like add, update or delete.

Enjoy it Smile

Bruno