Skip to content

Instantly share code, notes, and snippets.

@letsbondiway
Last active February 17, 2020 18:18
Show Gist options
  • Save letsbondiway/df827da834b238921a7daaab9f41a24e to your computer and use it in GitHub Desktop.
Save letsbondiway/df827da834b238921a7daaab9f41a24e to your computer and use it in GitHub Desktop.
A python utility which can be run from command line to get list of already expired apps and list of apps to expire in coming n days on Workspace One.
# !/usr/bin/env python
import argparse
import requests
import json
from datetime import datetime, timedelta
def handle_response(response, expected_code):
if response.status_code != expected_code:
print('Status:', response.status_code, 'Headers:',
response.headers, 'Error Response:', response.json())
sys.exit(1)
return response.json()
def get(uri, expected_code, verify=True, headers=None):
return handle_response(requests.get(uri, verify=verify, headers=headers), expected_code)
def get_apps():
uri = args.api + f"/API/mam/apps/search?applicationtype=Internal&status=Active&platform=Apple"
response = get(uri, 200, headers=headers)
return response['Application']
def get_app_details(appId):
uri = args.api + f"/API/mam/apps/internal/{appId}"
response = get(uri, 200, headers=headers)
return response
# Parse arguments
parser = argparse.ArgumentParser()
parser.add_argument("-a", "-api", type=str, dest='api', required=True,
help="The WorkspaceONE enpoint of your organization")
parser.add_argument("-b", "-b64authstring", type=str, dest='b64authstring', required=True,
help="The base64 encoded auth string for you to access WorkspaceONE Console")
parser.add_argument("-ak", "-apikey", type=str, dest='apikey', required=True,
help="The authorization Api key or Tenant code")
parser.add_argument("-lgId", "-locationGroupId", type=int, dest='locationgroupid', required=True,
help="Location Group Identifier of the OG")
parser.add_argument("-td", "-timedelta", type=int, dest='timedelta', required=False, default=30,
help="Number of days to look for before apps getting expired")
parser.add_argument("-d", "-debug", type=bool, dest='debug', required=False, default=False,
help="Send True if you need to see debug logs")
args = parser.parse_args()
# Request headers
headers = {
"Content-Type": "application/json",
"Accept": "application/json",
"Authorization": "Basic " + args.b64authstring,
"aw-tenant-code": args.apikey
}
# Get all Active apps for Apple
apps = get_apps()
if args.debug: print("All apps count: ", len(apps))
if args.debug: print("All apps: ", json.dumps(apps, indent=2, sort_keys=True))
filtered_apps = [app for app in apps if app['LocationGroupId'] == args.locationgroupid]
if args.debug: print("Filtered apps count: ", len(filtered_apps))
if args.debug: print("Filtered apps: ", json.dumps(filtered_apps, indent=2, sort_keys=True))
expiredAppsTupleList = []
expiringAppTupleList = []
# Iterate each app and fetch its details
for app in filtered_apps:
appId = app['Id']['Value']
appDetails = get_app_details(appId)
appName = appDetails['ApplicationName']
renewalDate = datetime.strptime(appDetails['RenewalDate'], '%Y-%m-%dT%H:%M:%S.%f')
renewalDateFormatted = renewalDate.strftime('%b %d %Y')
if args.debug: print(f'\nRenewal date for app named {appName}: {renewalDateFormatted}')
thresholdDate = datetime.today() + timedelta(days=args.timedelta)
if renewalDate < datetime.today():
if args.debug: print(f'App named {appName} has already expired')
expiredAppTuple = (appName, renewalDateFormatted)
expiredAppsTupleList.append(expiredAppTuple)
elif renewalDate < thresholdDate:
if args.debug: print(f'App named {appName} is expiring within next {args.timedelta} days')
expiringAppTuple = (appName, renewalDateFormatted)
expiringAppTupleList.append(expiringAppTuple)
else:
if args.debug: print(f'App named {appName} will remain active even after {args.timedelta} days')
# Display list of apps which have already expired
if len(expiredAppsTupleList):
print("\nList of apps which have already expired:")
for expiredAppTuple in expiredAppsTupleList:
print(f'{expiredAppTuple[0]} - Expired on {expiredAppTuple[1]}')
print('\n')
# Display list of apps which are about to expire
if len(expiredAppsTupleList):
print(f"List of apps which are expiring within next {args.timedelta} days:")
for expiringAppTuple in expiringAppTupleList:
print(f'{expiringAppTuple[0]} - About to expire on {expiringAppTuple[1]}')
@letsbondiway
Copy link
Author

To use this utility, you need to have python3 along with a python package named requests installed on your system. Usage -

python3 get_expiring_ws1_apps.py -a "your-ws1-server-endpoint" -b "your-base64-encoded-auth-string" -ak "api-key" -lgId your-org-group-id -td number-of-days-for-expiry -d True

Different argument options are explained below -
-a :- WS1 Endpoint
-b :- base64 encoded auth string made out of your username and password.
-ak :- API Key
-lgId :- Organization Group ID
-td :- Number of coming days for which you are looking for apps expiry. It is an optional field and if not specified, defaults to 30 days
-d :- For Debug logs. It is an optional field and if not specified, defaults to False.

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment