def cancel_job(self): if self.sasjob_status == "running": result = callrestapi(self.cancel_job_uri, self.cancel_job_method, acceptType="text/plain", contentType="text/plain") return result.text
parser.add_argument("-f","--filename", help="Full path to file. (No extension)",default="/tmp/customgroups") parser.add_argument("-d","--debug", action='store_true', help="Debug") args= parser.parse_args() filename=args.filename debug=args.debug # create the requests file of the custom groups # get all groups that are custom reqtype='get' reqval='/identities/groups/?filter=eq(providerId,"local")&limit=10000' groupslist_result_json=callrestapi(reqval,reqtype) groups = groupslist_result_json['items'] #if debug: print(json.dumps(groups,indent=2)) """ This is the json format { "version": 1, "name": "Modelers", "description": "Modelers", "items": [ "/identities/groups/SalesModelers", "/identities/groups/HRModelers" ] } """ basename = os.path.basename(filename)
help="Output Style", choices=['csv', 'json', 'simple', 'simplejson'], default='simplejson') args = parser.parse_args() group = args.group debug = args.debug output_style = args.output if group == 'all': # get all groups that are not custom reqtype = 'get' #reqval='/identities/groups' reqval = '/identities/groups/?filter=ne(providerId,"local")&limit=10000' groupslist_result_json = callrestapi(reqval, reqtype) groups = groupslist_result_json['items'] for group in groups: groupid = group['id'] reqval = '/identities/groups/' + groupid + '/identifier' posixinfo_result_json = callrestapi(reqval, reqtype) # get gid group["gid"] = posixinfo_result_json["gid"] cols = ['id', 'gid', 'name'] printresult(groupslist_result_json, output_style, cols) else:
parser = argparse.ArgumentParser() parser.add_argument("--noheader", action='store_true', help="Do not print the header row") parser.add_argument("-d","--debug", action='store_true', help="Debug") args = parser.parse_args() noheader=args.noheader debug=args.debug # Print header row unless noheader argument was specified if not noheader: print('server,caslib,table') endpoint='/casManagement/servers' method='get' #make the rest call serverlist_result_json=callrestapi(endpoint,method) if debug: print(serverlist_result_json) print('serverlist_result_json is a '+type(serverlist_result_json).__name__+' object') #serverlist_result_json is a dict object servers = serverlist_result_json['items'] for server in servers: servername=server['name'] #print(servername) # List the caslibs in this server endpoint='/casManagement/servers/'+servername+'/caslibs?excludeItemLinks=true' method='get' caslibs_result_json=callrestapi(endpoint,method)
) else: areyousure = "Y" else: areyousure = "Y" # prompt is Y if user selected Y, its a new directory, or user selected quiet mode if areyousure.upper() == 'Y': path = basedir # List the caslibs in this server endpoint = '/casManagement/servers/' + server + '/caslibs?excludeItemLinks=true&limit=10000' + completefilter if debug: print(endpoint) method = 'get' caslibs_result_json = callrestapi(endpoint, method) caslibs = caslibs_result_json['items'] if len(caslibs): if not os.path.exists(path): os.makedirs(path) else: filelist = glob.glob(path + "/*.json") for file in filelist: os.remove(file) # loop the caslibs and output a json file for caslib in caslibs: caslib['server'] = server
ts_before=args.before # Create list for filter conditions filtercond=[] if appname!=None: filtercond.append("eq(application,'"+appname+"')") if username!=None: filtercond.append("eq(user,'"+username+"')") if entry_type!=None: filtercond.append("eq(type,'"+entry_type+"')") if entry_action!=None: filtercond.append("eq(action,'"+entry_action+"')") if entry_state!=None: filtercond.append("eq(state,'"+entry_state+"')") if ts_after!=None: filtercond.append("ge(timeStamp,'"+ts_after+"')") if ts_before!=None: filtercond.append("le(timeStamp,'"+ts_before+"')") # Construct filter delimiter = ',' completefilter = 'and('+delimiter.join(filtercond)+')' # Set request reqtype = 'get' reqval = "/audit/entries?filter="+completefilter+"&limit="+output_limit+"&sortBy="+sort_order # Construct & print endpoint URL baseurl=getbaseurl() endpoint=baseurl+reqval # print("REST endpoint: " +endpoint) # Make REST API call, and process & print results files_result_json=callrestapi(reqval,reqtype) cols=['id','timeStamp','type','action','state','user','remoteAddress','application','description','uri'] printresult(files_result_json,output_style,cols)
folderinfo = getfolderid(folderpath) results = (folderinfo[3]) printresult(results, 'JSON') id = results["id"] package_name = str(uuid.uuid1()) json_name = folderpath.replace("/", "_") if filename != "XNOFILENAMEX": json_name = filename command = clicommand + ' transfer export -u /folders/folders/' + id + ' --name "' + package_name + '"' print(command) subprocess.call(command, shell=True) reqtype = 'get' reqval = '/transfer/packages?filter=eq(name,"' + package_name + '")' package_info = callrestapi(reqval, reqtype) package_id = package_info['items'][0]['id'] completefile = os.path.join(path, json_name + '.json') command = clicommand + ' transfer download --file ' + completefile + ' --id ' + package_id print(command) subprocess.call(command, shell=True) print("NOTE: Viya folder " + folderpath + " exported to json file " + completefile) else: print("NOTE: Operation cancelled")
import argparse from sharedfunctions import callrestapi, printresult # setup command-line arguements parser = argparse.ArgumentParser() parser.add_argument("-u","--objecturi", help="Enter the objecturi.",required='True') parser.add_argument("-p","--principal", help="Enter the identity name or authenticatedUsers, everyone or guest",required='True') parser.add_argument("-o","--output", help="Output Style", choices=['csv','json','simple','simplejson'],default='json') args = parser.parse_args() objuri=args.objecturi ident=args.principal output_style=args.output if ident.lower()=='authenticatedusers': ident='authenticatedUsers' if ident=='guest' or ident=='everyone' or ident=='authenticatedUsers': reqval= "/authorization/rules?filter=and(eq(principalType,'"+ident+"'),eq(objectUri,'"+objuri+"'))" else: reqval= "/authorization/rules?filter=and(eq(principal,'"+ident+"'),eq(objectUri,'"+objuri+"'))" reqtype='get' result=callrestapi(reqval,reqtype) # print rest call results printresult(result,output_style)
# encode the password if pwval: cred = base64.b64encode(pwval.encode("utf-8")).decode("utf-8") # build the rest call reqval = "/credentials/domains/" + domain_name reqtype = "put" # build the json parameters data = {} data['id'] = domain_name data['description'] = desc data['type'] = type # create the domain callrestapi(reqval, reqtype, data=data) # for each group passed in add their credentials to the domain for group_id in grouplist: print("Adding " + group_id + " to domain " + domain_name) reqval = "/credentials/domains/" + domain_name + "/groups/" + group_id reqtype = "put" data = {} data['domainId'] = domain_name data['domainType'] = type data['identityId'] = group_id data['identityType'] = 'group' data['properties'] = {"userId": userid} if pwval:
parser = argparse.ArgumentParser() #parser.add_argument("-t","--principaltype", help="Enter the type of principal to test: user or group.",required='True',choices=['user','group']) parser.add_argument("-q", "--quiet", action='store_true') parser.add_argument("-d", "--debug", action='store_true') args = parser.parse_args() #principaltype=args.principaltype quiet = args.quiet debug = args.debug # STEP 1 of 4: Get the jobDefinition of the existing DEFAULT_BACKUP_SCHEDULE endpoint = '/jobDefinitions/definitions?limit=20&filter=in(name,"' + defaultBackupScheduleName + '")' method = 'get' accept = 'application/json' jobDefinition_json = callrestapi(endpoint, method, accept) if debug: print('jobDefinition_json:') print(jobDefinition_json) jobDefinitions = jobDefinition_json['items'] id_found = False jobDefinitionId = '' for jobDefinition in jobDefinitions: if jobDefinition['name']: if (jobDefinition['name'] == defaultBackupScheduleName): jobDefinitionId = jobDefinition['id'] print('Id: ' + jobDefinitionId) id_found = True if not id_found:
if version > 2: areyousure = input( "Are you sure you want to delete the folder and its contents? (Y)" ) else: areyousure = raw_input( "Are you sure you want to delete the folder and its contents? (Y)" ) if areyousure.upper() == 'Y': #delete folder content, recursive call returns all children reqval = uri + "/members?recursive=true&limit=1000000" reqtype = 'get' allchildren = callrestapi(reqval, reqtype) # get all child items if 'items' in allchildren: itemlist = allchildren['items'] folderlist = [] contentlist = [] #delete child items and if its a folder delete the folder and its content for children in itemlist: #print(json.dumps(children,indent=2)) contenttype = children['contentType']
parser.add_argument("-f", "--file", help="A csv file containing groups and userids.", required=True) args = parser.parse_args() domain_name = args.domain file = args.file # check that domain exists reqval = "/credentials/domains/" + domain_name reqtype = "get" #if domain does not exist call restapi will exit and no additional code is run domainexist = callrestapi(reqval, reqtype) type = domainexist['type'] # read the csv file to create json check = file_accessible(file, 'r') # file can be read if check: with open(file, 'rt') as f: filecontents = csv.reader(f) for row in filecontents: #print(row)
default="cas-shared-default") parser.add_argument("-o", "--output", help="Output Style", choices=['csv', 'json', 'simple', 'simplejson'], default='csv') args = parser.parse_args() casserver = args.server output_style = args.output # set the request type reqtype = 'get' # set the endpoint to call reqval = '/dataSources/providers/cas/sources/' + casserver + '/children?&limit=100000' #make the rest call using the callrestapi function. You can have one or many calls caslib_result_json = callrestapi(reqval, reqtype) # example of overriding the columns for csv output cols = ['name', 'type', 'path', 'scope', 'attributes', 'description'] # print result accepts # the json returned # the output style # optionally the columns for csv outtput, if you don't pass in columns you get defaults # You can just print results r post process the results as you need to printresult(caslib_result_json, output_style, cols)
# Print header row unless noheader argument was specified if not noheader: if show_email: print( 'groupid,groupname,grouptype,groupproviderid,memberid,membername,membertype,memberproviderid,email' ) else: print( 'groupid,groupname,grouptype,groupproviderid,memberid,membername,membertype,memberproviderid' ) endpoint = '/identities/groups?limit=10000' method = 'get' #make the rest call groupslist_result_json = callrestapi(endpoint, method) if debug: print(groupslist_result_json) print('groupslist_result_json is a ' + type(groupslist_result_json).__name__ + ' object' ) #groupslist_result_json is a dict object groups = groupslist_result_json['items'] for group in groups: groupid = group['id'] groupname = group['name'] grouptype = group['type'] groupproviderid = group['providerId']
# setup command-line arguements parser = argparse.ArgumentParser( description="Create custom groups and establish membership") parser.add_argument("-f", "--file", help="Full path to csv file containing groups ", required='True') args = parser.parse_args() file = args.file reqtype = "post" check = file_accessible(file, 'r') allgroups = callrestapi("/identities/groups", "get") # create a list of all groups groupslist = [] if 'items' in allgroups: total_items = allgroups['count'] returned_items = len(allgroups['items']) for i in range(0, returned_items): groupslist.append(allgroups['items'][i]['id']) # file can be read
# Import Python modules from __future__ import print_function import argparse import pprint pp = pprint.PrettyPrinter(indent=4) from sharedfunctions import callrestapi, printresult parser = argparse.ArgumentParser( description="Return a set of configuration properties") parser.add_argument("-c", "--configuration", help="Enter the configuration definition.", required='True') parser.add_argument("-o", "--output", help="Output Style", choices=['csv', 'json', 'simple', 'simplejson'], default='json') args = parser.parse_args() configurationdef = args.configuration output_style = args.output reqval = "/configuration/configurations?definitionName=" + configurationdef configvalues = callrestapi(reqval, 'get') printresult(configvalues, output_style)
# process items not in folders if puri!=None: filtercond.append("contains(parentUri,'"+puri+"')") completefilter = 'and('+delimiter.join(filtercond)+')' reqval="/files/files?filter="+completefilter+"&sortBy="+sortby+":descending&limit=10000" # process items in folders elif pfolder!=None: folderid=getfolderid(pfolder)[0] # add the start and end and comma delimit the filter completefilter = 'and('+delimiter.join(filtercond)+')' reqval="/folders/folders/"+folderid+"/members?filter="+completefilter+"&sortBy="+sortby+":descending&limit=10000" files_in_folder=callrestapi(reqval,reqtype) #now get the file objects using the ids returned iddict=getidsanduris(files_in_folder) # get the uris of the files uris=iddict['uris'] #get id, need to do this because only the uri of the folder is returned idlist=[] for item in uris: vallist=item.rsplit('/') idlist.append(vallist[-1])
parser.add_argument( "-n", "--name", help="Enter the name of the publishing destination to be deleted.", required=True) parser.add_argument("-d", "--debug", action='store_true', help="Debug") args = parser.parse_args() publish_name = args.name debug = args.debug # Does a publishing destination of the specified name actually exist? # This call exits with a reasonably clear error message if the publishing destination does not exist, # so I decided that no other error handling is required for the case where the folder does not exist. reqval = "/modelPublish/destinations/" + publish_name reqtype = "get" test_exists_result_json = callrestapi(reqval, reqtype) #print(test_exists_result_json) #print('test_exists_result_json is a '+type(test_exists_result_json).__name__+' object') #test_exists_result_json is a dict object if test_exists_result_json['name'] == publish_name: folder_exists = True if debug: print('Publishing destination ' + publish_name + ' found.') # Build the rest call # Aiming for something equivalent to ./callrestapi.py -e /modelPublish/destinations/newcasdest2 -m delete reqval = "/modelPublish/destinations/" + publish_name reqtype = "delete" # Delete the publishing destination callrestapi(reqval, reqtype) print('Publishing destination ' + publish_name + ' deleted.')
help="Do not print the header row") parser.add_argument("-d", "--debug", action='store_true', help="Debug") args = parser.parse_args() noheader = args.noheader debug = args.debug # Print header row unless noheader argument was specified if not noheader: print('server,caslib,' + ','.join(map(str, identity_cols)) + ',' + ','.join(map(str, permissions))) endpoint = '/casManagement/servers' method = 'get' #make the rest call serverlist_result_json = callrestapi(endpoint, method) if debug: print(serverlist_result_json) print('serverlist_result_json is a ' + type(serverlist_result_json).__name__ + ' object') #serverlist_result_json is a dict object servers = serverlist_result_json['items'] for server in servers: servername = server['name'] # List the caslibs in this server endpoint = '/casManagement/servers/' + servername + '/caslibs?excludeItemLinks=true&limit=10000' method = 'get'
from sharedfunctions import printresult, callrestapi # setup command-line arguements parser = argparse.ArgumentParser(description="Display POSIX attributes for User") parser.add_argument("-u","--user", help="Enter the user id",required='True') parser.add_argument("-d","--debug", action='store_true', help="Debug") parser.add_argument("-o","--output", help="Output Style", choices=['csv','json','simple','simplejson'],default='json') args = parser.parse_args() user=args.user debug=args.debug output_style=args.output # set the request type reqtype='get' # set the endpoint to call reqval='/identities/users/'+user+"/identifier" if debug: print(reqval) #make the rest call using the callrestapi function. You can have one or many calls user_info_result_json=callrestapi(reqval,reqtype) # seems to be returning non standard results add id to make it standard # print result expects there to an id so use uid user_info_result_json['id']=user_info_result_json["uid"] user_info_result_json['username']=user printresult(user_info_result_json,output_style)
else: if version > 2: areyousure = input("Are you sure you want to move content from " + source + " to " + target + "? (Y)") else: areyousure = raw_input( "Are you sure you want to move content from " + source + " to " + target + "? (Y)") if areyousure.upper() == 'Y': # get all the content in folder reqtype = 'get' reqval = '/folders/folders/' + id + "/members" members = callrestapi(reqval, reqtype) # create a list of items items = members["items"] for item in items: # delete from folder reqtype = "delete" reqval = '/folders/folders/' + id + "/members/" + item["id"] rc = callrestapi(reqval, reqtype) #build dictionary of item thisitem = {
# there is always a number of days, the default is 1825 filtercond.append(datefilter) if modby != None: filtercond.append("eq(modifiedBy," + modby + ")") if nameval != None: filtercond.append('contains($primary,name,"' + nameval + '")') # add the start and end and comma delimit the filter delimiter = ',' completefilter = 'and(' + delimiter.join(filtercond) + ')' # retrieve all reports in the system reqtype = 'get' reqval = '/reports/reports?filter=' + completefilter + '&limit=10000' resultdata = callrestapi(reqval, reqtype) # loop root reports if 'items' in resultdata: total_items = resultdata['count'] itemlist = resultdata['items'] returned_items = len(itemlist) if total_items == 0: print("Note: No items returned.") else: # get the path for each report and add it to the result set # this is not very efficient. I will try to improve it for i in range(0, returned_items):
parser.add_argument("-m","--method", help="Enter the REST method.",default="get",required='True',choices=['get','put','post','delete']) parser.add_argument("-i","--inputfile",help="Enter the full path to an input json file",default=None) parser.add_argument("-a","--accepttype",help="Enter REST Content Type you want returned e.g application/vnd.sas.identity.basic+json",default="application/json") parser.add_argument("-c","--contenttype",help="Enter REST Content Type for POST e.g application/vnd.sas.identity.basic+json",default="application/json") parser.add_argument("-o","--output", help="Output Style", choices=['csv','json','simple'],default='json') parser.add_argument("-t","--text", help="Display Simple Text Results.", action='store_true') args = parser.parse_args() reqval=args.endpoint reqtype=args.method reqfile=args.inputfile reqcontent=args.contenttype reqaccept=args.accepttype simpletext=args.text output_style=args.output # keep for backward compatibility if simpletext: output_style='simple' # use the callrestapi function to make a call to the endpoint # call passing json or not if reqfile != None: inputdata=getinputjson(reqfile) result=callrestapi(reqval,reqtype,reqaccept,reqcontent,data=inputdata) else: result=callrestapi(reqval,reqtype,reqaccept,reqcontent) #print the result printresult(result,output_style)
# prompt is Y if user selected Y, its a new directory, or user selected quiet mode if areyousure.upper() =='Y': path=basedir # create directory if it doesn't exist if not os.path.exists(path): os.makedirs(path) else: filelist=glob.glob(path+"/*.json") for file in filelist: os.remove(file) # retrieve root folders reqtype='get' reqval='/folders/rootFolders' resultdata=callrestapi(reqval,reqtype) # loop root folders if 'items' in resultdata: total_items=resultdata['count'] returned_items=len(resultdata['items']) if total_items == 0: print("Note: No items returned.") else: # export each folder and download the package file to the directory for i in range(0,returned_items): id=resultdata['items'][i]["id"] package_name=str(uuid.uuid1())
newfolder = row[0] description = row[1] if newfolder[0] != '/': newfolder = "/" + newfolder folder = os.path.basename(os.path.normpath(newfolder)) parent_folder = os.path.dirname(newfolder) data = {} data['name'] = folder data['description'] = description print("Creating folder " + newfolder) if parent_folder == "/": reqval = '/folders/folders' else: # parent folder create a child parentinfo = getfolderid(parent_folder) if parentinfo != None: parenturi = parentinfo[1] reqval = '/folders/folders?parentFolderUri=' + parenturi else: print("Parent folder not found") myresult = callrestapi(reqval, reqtype, data=data, stoponerror=0) else: print("ERROR: cannot read " + file)
if args.type == "cas": table = args.table data['destinationTable'] = table elif args.type == "hadoop": hdfsdir = args.hdfsdir data['hdfsDirectory'] = hdfsdir elif args.type == 'teradata': dbcaslib = args.dbcaslib table = args.table data['databaseCasLibrary'] = dbcaslib data['destinationTable'] = table # build the rest call reqval = "/modelPublish/destinations/" reqtype = "post" # create the domain callrestapi( reqval, reqtype, acceptType='application/vnd.sas.models.publishing.destination+json', contentType='application/vnd.sas.models.publishing.destination+json', data=data) print("NOTE: destination created with the following parameters") print(data)
convey = False #Use the /authorization/decision endpoint to ask for an explanation of the rules that are relevant to principals on this URI #See Authorization API documentation in swagger at http://swagger.na.sas.com/apis/authorization/v4/apidoc.html#op:createExplanation endpoint = '/authorization/decision' if name and principaltype: if (principaltype.lower() == 'user'): endpoint = endpoint + '?additionalUser='******'?additionalGroup=' + name method = 'post' accept = 'application/vnd.sas.authorization.explanations+json' content = 'application/vnd.sas.selection+json' inputdata = {"resources": [explainuri]} decisions_result_json = callrestapi(endpoint, method, accept, content, inputdata) #print(decisions_result_json) #print('decisions_result_json is a '+type(decisions_result_json).__name__+' object') #decisions_result_json is a dict object e = decisions_result_json['explanations'][explainuri] #print('e is a '+type(e).__name__+' object') #e is a list object # Print header row if header argument was specified if header: if printpath: if convey: print('path,principal,' + ','.join(map(str, permissions)) + ',' + ','.join(map('{0}(convey)'.format, permissions))) else: print('path,principal,' + ','.join(map(str, permissions)))
with open(reqfile) as json_file: data = json.load(json_file) print(json.dumps(data, indent=2)) if 'name' in data: name = data['name'] # check to see if the json template exists # Execute actual code to upload the json template reqtype = "get" reqval = "/templates/templates/?filter=eq(name, '" + name + "')" reqaccept = "application/vnd.sas.collection+json" reccontent = "application/json" resultdata = callrestapi(reqval, reqtype, reqaccept, reccontent, data, stoponerror=0) if 'items' in resultdata: returned_items = len(resultdata['items']) for i in range(0, returned_items): id = resultdata['items'][i]['id'] print("Template already exists - " + name + " [" + id + "]") else: id = None #upload the json template # Execute actual code to upload the json template if id:
if version > 2: areyousure = input( "Are you sure you want to delete the folder and its contents? (Y)" ) else: areyousure = raw_input( "Are you sure you want to delete the folder and its contents? (Y)" ) if areyousure.upper() == 'Y': #delete folder content, recursive call returns all children reqval = uri + "/members?recursive=true" reqtype = 'get' allchildren = callrestapi(reqval, reqtype) # get all child items if 'items' in allchildren: itemlist = allchildren['items'] for children in itemlist: #if it is a report if children['contentType'] == 'report': linklist = children['links'] for linkval in linklist:
#Exit if the objecURI is not a folder if not objecturi.startswith("/folders/folders/"): raise Exception( 'ObjectURI must be a folder, and should begin with /folders/folders/.') #First, use the /folders/{folderId}/members endpoint to ask for a list of objects which are in the folder passed in by objecturi #See Folders API documentation in swagger at http://swagger.na.sas.com/apis/folders/v1/apidoc.html#op:getAncestors endpoint = objecturi + '/members' if recursive: endpoint = endpoint + '?recursive=true&limit=10000' else: endpoint = endpoint + '?limit=10000' method = 'get' #make the rest call members_result_json = callrestapi(endpoint, method) if debug: print(members_result_json) #print('members_result_json is a '+type(members_result_json).__name__+' object') #members_result_json is a dict object members = members_result_json['items'] for member in members: outstr = '' path = getpath(member['uri']) outstr = outstr + path + ',' + member['id'] + ',' + member[ 'name'] + ',' + member['type'] if 'description' in member: outstr = outstr + ',' + member['description'] else: