当前位置: 首页>>代码示例>>Python>>正文


Python SampleUtilities类代码示例

本文整理汇总了Python中SampleUtilities的典型用法代码示例。如果您正苦于以下问题:Python SampleUtilities类的具体用法?Python SampleUtilities怎么用?Python SampleUtilities使用的例子?那么恭喜您, 这里精选的类代码示例或许可以为您提供帮助。


在下文中一共展示了SampleUtilities类的15个代码示例,这些例子默认根据受欢迎程度排序。您可以为喜欢或者感觉有用的代码点赞,您的评价将有助于系统推荐出更棒的Python代码示例。

示例1: main

def main():
    # Create our client.
    client = RestApiClient(version="3.0")

    # Using the /asset_model/assets endpoint with a GET request.
    SampleUtilities.pretty_print_request(client, "asset_model/assets", "GET")
    response = client.call_api("asset_model/assets", "GET")

    # Verify that the call to the API was successful.
    if response.code != 200:
        print("Failed to retrieve asset list.")
        SampleUtilities.pretty_print_response(response)
        sys.exit(1)

    # Display the number of assets retrieved.
    response_body = json.loads(response.read().decode("utf-8"))
    number_of_assets_retrieved = len(response_body)

    # Display number of assets, and the IDs of the assets retrieved.
    print(str(number_of_assets_retrieved) + " assets were retrieved.")
    if number_of_assets_retrieved > 0:
        print("Asset IDs: ", end="")
        for asset in response_body:
            print(str(asset["id"]) + " ", end="")
        print()
开发者ID:jonaslsl,项目名称:api-samples,代码行数:25,代码来源:01_GetAssets.py

示例2: main

def main():

    # Create our client and set up some sample data.
    client = RestApiClient()
    setup_data(client)
    
    # Some endpoints accept path parameters.
    # These parameters are inserted into the path portion of the URL at specific
    # locations. In this example we are retrieving the contents of a reference
    # set named 'rest_api_samples_testset'.
    SampleUtilities.pretty_print_request(client, 'referencedata/sets/rest_api_samples_testset', 'GET')
    response = client.call_api('referencedata/sets/rest_api_samples_testset', 'GET')
    SampleUtilities.pretty_print_response(response)
    
    
    # Query parameters and path parameters can be combined in a single request.
    # Here we are adding a value to the reference set we just looked at.
    SampleUtilities.pretty_print_request(client, 'referencedata/sets/rest_api_samples_testset?value=rest_api_sample_value', 'POST')
    response = client.call_api('referencedata/sets/rest_api_samples_testset?value=rest_api_sample_value', 'POST')
    
    # Along with GET requests, POST and DELETE requests often return information
    # that can be used to confirm the results of the request.
    SampleUtilities.pretty_print_response(response)
    
    # Now we can look at the contents of the reference set again to see the
    # value we added.
    response = client.call_api('referencedata/sets/rest_api_samples_testset', 'GET')
    SampleUtilities.pretty_print_response(response)
开发者ID:MatticusCaesar,项目名称:api-samples,代码行数:28,代码来源:03_PathParameters.py

示例3: setup_data

def setup_data(client):
    SampleUtilities.data_setup(client, 'reference_data/sets?name=rest_api_samples_suspect_ips&element_type=IP', 'POST')
    SampleUtilities.data_setup(client, 'reference_data/sets/rest_api_samples_suspect_ips?value=8.7.6.5', 'POST')
    SampleUtilities.data_setup(client, 'reference_data/sets/rest_api_samples_suspect_ips?value=10.7.6.5', 'POST')
    SampleUtilities.data_setup(client, 'reference_data/sets/rest_api_samples_suspect_ips?value=13.7.6.5', 'POST')

    SampleUtilities.data_setup(client, 'reference_data/sets?name=rest_api_samples_blocked_ips&element_type=IP', 'POST')
开发者ID:RuanMuller,项目名称:api-samples,代码行数:7,代码来源:01_Sets.py

示例4: main

def main():
    # Create our client.
    client = RestApiClient()

    # Using the /asset_model/assets endpoint with a GET request. 
    SampleUtilities.pretty_print_request(client, 'asset_model/assets', 'GET')
    response = client.call_api('asset_model/assets', 'GET')

    # Verify that the call to the API was successful.
    if (response.code != 200):
        print('Failed to retrieve asset list.')
        SampleUtilities.pretty_print_response(response)
        sys.exit(1)

    # Display the number of assets retrieved.
    response_body = json.loads(response.read().decode('utf-8'))
    number_of_assets_retrieved = len(response_body)
		
    # Display number of assets, and the IDs of the assets retrieved.
    print(str(number_of_assets_retrieved) + ' assets were retrieved.')
    if (number_of_assets_retrieved > 0):
        print("Asset IDs: ", end="")
        for asset in response_body:
            print(str(asset['id']) + ' ', end="")
        print()		
开发者ID:phieber,项目名称:api-samples,代码行数:25,代码来源:01_GetAssets.py

示例5: main

def main():
    # Create our client and set up some sample data.
    client = RestApiClient()
    setup_data(client)
    
    # Here we have a look at the data in this map of sets.
    response = client.call_api('referencedata/mapOfSets/rest_api_samples_login_events', 'GET')
    SampleUtilities.pretty_print_response(response)
    
    # Retrieve the map of sets and load it into a JSON object.
    response = client.call_api('referencedata/mapOfSets/rest_api_samples_login_events', 'GET')
    response_body = json.loads(response.read().decode('utf-8'))
    
    # Capture the data portion of the map of sets.
    data = response_body['data']
    
    # Also get the current time so that the CIO's dashboard can plot the results
    # over time.
    current_time = time.strftime('%Y-%m-%d %H:%M:%S')
    
    # We now empty the reference map of sets so that new data can start to
    # accumulate. We empty it now so that we don't miss new events if we have a
    # lot of data to process. Note that by using the purgeOnly parameter we are
    # only emptying the collection, not deleting it.
    print("Purging the collection so that new data can be collected.")
    response = client.call_api('referencedata/mapOfSets/rest_api_samples_login_events?purgeOnly=true', 'DELETE')
    SampleUtilities.pretty_print_response(response)
    
    # Go through the data, find the information we are interested in, and send
    # it to the CIO's dashboard.
    for key in data.keys():
        number_of_elements = len(data[key])
        send_data_to_dashboard(current_time, key, number_of_elements)
开发者ID:MatticusCaesar,项目名称:api-samples,代码行数:33,代码来源:03_MapOfSets.py

示例6: main

def main():
    # Create our client.
    client = RestApiClient()

    # Using the /asset_model/properties endpoint with a GET request. 
    SampleUtilities.pretty_print_request(client, 'asset_model/properties', 'GET')
    response = client.call_api('asset_model/properties', 'GET')

    # Verify that the call to the API was successful.
    if (response.code != 200):
        print('Failed to retrieve propertiy list.')
        SampleUtilities.pretty_print_response(response)
        sys.exit(1)

    # Display the number of properties retrieved.
    response_body = json.loads(response.read().decode('utf-8'))
    number_of_properties_retrieved = len(response_body)
		
    # Display number of properties, and the names of the properties retrieved.
    print(str(number_of_properties_retrieved) + ' properties were retrieved.')
    if (number_of_properties_retrieved > 0):
        print("Property Names: ", end="")
        for property in response_body:
            print(str(property['name']) + ', ', end="")
        print()		
开发者ID:phieber,项目名称:api-samples,代码行数:25,代码来源:02_GetProperties.py

示例7: main

def main():
    # For the purpose of this sample, the reading in of credentials, the setup
    # of HTTP request headers, and the construction and sending of a request
    # object has been abstracted to the 'RestApiClient' class.
    # For more information on how these operations are done see the sample
    # '01_Authentication.py'.
    client = RestApiClient()

    # Many API endpoints accept parameters.
    # One type of parameter is a query parameter.
    # If an endpoint accepts query parameters they are passed after a '?' as
    # part of the URL. Each parameter has a name and a value separated by a '='.
    # Several parameters can be passed separated by '&' characters.
    SampleUtilities.pretty_print_request(client, 'reference_data/sets?name=rest_api_samples_testset&element_type=ALN', 'POST')

    response = client.call_api('reference_data/sets?name=rest_api_samples_testset&element_type=ALN', 'POST')

    # The response code for successfully creating a set is 201.
    if (response.code == 201):
        SampleUtilities.pretty_print_response(response)
    # The error code that occurs when attempting to create a set that already
    # exists is 409.
    elif (response.code == 409):
        print("Reference set already exists")
        response = client.call_api('reference_data/sets/rest_api_samples_testset', 'GET')
        SampleUtilities.pretty_print_response(response)
    elif (response.code >= 500):
        print("An internal server error occurred. You should check your system.")
        SampleUtilities.pretty_print_response(response)
    else:
        print("Some other error has occurred:")
        SampleUtilities.pretty_print_response(response)
开发者ID:phieber,项目名称:api-samples,代码行数:32,代码来源:02_QueryParameters.py

示例8: main

def main():
    # Create our client.
    client = RestApiClient()
    
    # While using the REST API an error may occur. Information about
    # the error is returned to you in the HTTP response that you receive.
    # The HTTP code in the response can tell you a little bit about the error.
    # A code in the 400 range indicates that there was a problem with the
    # request.
    # A code in the 500 range indicates that there was a problem with the
    # server.
    # In addition to the response code, the response body contains information
    # about the error that occurred.
    
    # In this example we are trying to access the contents of a reference data
    # set that does not exist.
    try:
        SampleUtilities.pretty_print_request(client, 'referencedata/sets/rest_api_samples_does_not_exist', 'GET')
        response = client.call_api('referencedata/sets/rest_api_samples_does_not_exist', 'GET')
    except urllib.error.HTTPError as e:
        response = e
    
    SampleUtilities.pretty_print_response(response)
    
    # In this example we are passing a query parameter using the wrong name.
    try:
        SampleUtilities.pretty_print_request(client, 'referencedata/sets?wrong_name=fake', 'POST')
        response = client.call_api('referencedata/sets?wrong_name=fake', 'POST')
    except urllib.error.HTTPError as e:
        response = e
        
    SampleUtilities.pretty_print_response(response)
开发者ID:MatticusCaesar,项目名称:api-samples,代码行数:32,代码来源:05_Errors.py

示例9: main

def main():
    # Create our client and set up some sample data.
    client = RestApiClient()
    setup_data(client)
    current_time = int(time.time() *1000)

    # First lets have a look at the data in the system.
    response = client.call_api('referencedata/tables/rest_api_samples_server_access', 'GET')
    SampleUtilities.pretty_print_response(response)

    response = client.call_api('referencedata/tables/rest_api_samples_server_access', 'GET')
    response_body = json.loads(response.read().decode('utf-8'))
    data = response_body['data']

    # Note that tables are stored sparsely, that is to say if a particular
    # cell is empty it does not exist in the table. However, our external
    # reporting tool can put appropriate defaults for these cells into the
    # report.
    print_custom_report(data)
    
    # Now our external system calculates which users should have their secure
    # access revoked.
    threshold = get_old_data_threshold(data)
    
    # check to see which users should have their secure access expired.
    for user in data:
        if ('Last_Secure_Login' in data[user]):
            if (data[user]['Last_Secure_Login']['lastSeen'] < threshold):
                print ("User '" + user + "' has not logged in to the secure server recently. Revoking their access.")
                outer_key = user
                if ('Authorization_Server_IP_Secure' in data[user]):
                    inner_key = 'Authorization_Server_IP_Secure'
                    value = data[user]['Authorization_Server_IP_Secure']['value']
                    response = client.call_api('referencedata/tables/rest_api_samples_server_access/' + outer_key + '/' + inner_key + '?value=' + value, 'DELETE')
                if ('Authorization_Server_PORT_Secure' in data[user]):
                    inner_key = 'Authorization_Server_PORT_Secure'
                    value = data[user]['Authorization_Server_PORT_Secure']['value']
                    response = client.call_api('referencedata/tables/rest_api_samples_server_access/' + outer_key + '/' + inner_key + '?value=' + value, 'DELETE')
    
    
    # now lets have a look at the data after we updated the table.
    response = client.call_api('referencedata/tables/rest_api_samples_server_access', 'GET')
    SampleUtilities.pretty_print_response(response)

    response = client.call_api('referencedata/tables/rest_api_samples_server_access', 'GET')
    response_body = json.loads(response.read().decode('utf-8'))
    data = response_body['data']
    
    print_custom_report(data)
开发者ID:MatticusCaesar,项目名称:api-samples,代码行数:49,代码来源:04_Tables.py

示例10: main

def main():
    # Create our client and set up some sample data.
    client = RestApiClient(version="3.0")
    setup_data(client)

    # Using the '/sets/{name} endpoint with a GET request we can retrieve the
    # contents of our set of suspect addresses.
    SampleUtilities.pretty_print_request(client, "reference_data/sets/rest_api_samples_suspect_ips", "GET")
    response = client.call_api("reference_data/sets/rest_api_samples_suspect_ips", "GET")

    # Based on our business rules, this set should always exist. If it does not
    # exist it could be an indication that our security has been breached and
    # that an attack is in progress. We should raise an alarm.
    if response.code == 404:
        print("Something is wrong, a system administrator should investigate.")
        sys.exit(1)

    # Extract the reference set from the response body.
    response_body = json.loads(response.read().decode("utf-8"))
    data = response_body["data"]

    for element in data:

        # For each suspect ip address, pass it to our legacy system to
        # validate. If it is a real threat, move it to the blocked list so that
        # the configured rules can generate offenses if it is active on our
        # network.
        ip_address = element["value"]
        if legacy_system_logic(ip_address):
            SampleUtilities.pretty_print_request(
                client, "reference_data/sets/rest_api_samples_blocked_ips?value=" + ip_address, "POST"
            )
            response = client.call_api("reference_data/sets/rest_api_samples_blocked_ips?value=" + ip_address, "POST")

            SampleUtilities.pretty_print_request(
                client, "reference_data/sets/rest_api_samples_suspect_ips/" + ip_address, "DELETE"
            )
            response = client.call_api("reference_data/sets/rest_api_samples_suspect_ips/" + ip_address, "DELETE")

    # The result of this processing is that there are some ip addresses now in
    # the blocked list.
    response = client.call_api("reference_data/sets/rest_api_samples_suspect_ips", "GET")
    SampleUtilities.pretty_print_response(response)

    # The ip addresses that were not blocked are sill in the suspect list for
    # us to watch.
    response = client.call_api("reference_data/sets/rest_api_samples_blocked_ips", "GET")
    SampleUtilities.pretty_print_response(response)
开发者ID:jonaslsl,项目名称:api-samples,代码行数:48,代码来源:01_Sets.py

示例11: call_api

    def call_api(self, endpoint, method, headers=None, params=[], data=None,
                 print_request=False):

        path = self.parse_path(endpoint, params)

        # If the caller specified customer headers merge them with the default
        # headers.
        actual_headers = self.headers.copy()
        if headers is not None:
            for header_key in headers:
                actual_headers[header_key] = headers[header_key]

        # Send the request and receive the response
        request = Request(
            'https://' + self.server_ip + self.base_uri + path,
            headers=actual_headers)
        request.get_method = lambda: method

        # Print the request if print_request is True.
        if print_request:
            SampleUtilities.pretty_print_request(self, path, method,
                                                 headers=actual_headers)

        try:
            response = urlopen(request, data)

            response_info = response.info()
            if 'Deprecated' in response_info:

                # This version of the API is Deprecated. Print a warning to
                # stderr.
                print("WARNING: " + response_info['Deprecated'],
                      file=sys.stderr)

            # returns response object for opening url.
            return response
        except HTTPError as e:
            # an object which contains information similar to a request object
            return e
        except URLError as e:
            if (isinstance(e.reason, ssl.SSLError) and
                    e.reason.reason == "CERTIFICATE_VERIFY_FAILED"):
                print("Certificate verification failed.")
                sys.exit(3)
            else:
                raise e
开发者ID:Harrysk,项目名称:api-samples,代码行数:46,代码来源:RestApiClient.py

示例12: main

def main():
    # Create our client.
    client = RestApiClient(version='3.0')

    # Using the /asset_model/properties endpoint with a GET request.
    SampleUtilities.pretty_print_request(client, 'asset_model/saved_searches',
                                         'GET')
    response = client.call_api('asset_model/saved_searches', 'GET')

    # Verify that the call to the API was successful.
    if (response.code != 200):
        print('Failed to retrieve saved searches list.')
        SampleUtilities.pretty_print_response(response)
        sys.exit(1)

    # Find the number of saved searches retrieved.
    response_body = json.loads(response.read().decode('utf-8'))
    number_of_searches_retrieved = len(response_body)

    # Display number of searches, and the names of the searches retrieved.
    print(str(number_of_searches_retrieved) + ' searches were retrieved.\n')
    if (number_of_searches_retrieved > 0):
        print("Searching Assets...\n\n")
        for search in response_body:
            # Retrieve the saved search unique identifier.
            saved_search_id = str(search['id'])
            saved_search_name = str(search['name'])

            print('Running saved search : ' + saved_search_name)

            # Using the /asset_model/saved_searches/{saved_search_id}/results
            # endpoint with a GET request.
            search_endpoint_url = ('asset_model/saved_searches/' +
                                   saved_search_id + '/results')
            SampleUtilities.pretty_print_request(client, search_endpoint_url,
                                                 'GET')
            search_response = client.call_api(search_endpoint_url, 'GET')

            if(response.code != 200):
                print("Failed to search assets.")
                SampleUtilities.pretty_print_response(response)
                sys.exit(1)

            # Find the number of assets found
            search_response_body = json.loads(search_response.read().
                                              decode('utf-8'))
            number_of_assets_found = len(search_response_body)

            # Display the number of assets retrieved.
            print(str(number_of_assets_found) + ' assets were retrieved.\n')
        print()
开发者ID:amico1234,项目名称:api-samples,代码行数:51,代码来源:04_SearchAssets.py

示例13: setup_data

def setup_data(client):
    SampleUtilities.data_setup(
        client,
        'reference_data/maps?name=rest_api_samples_current_admin_shift&' +
        'element_type=ALN', 'POST')
    SampleUtilities.data_setup(
        client,
        'reference_data/maps/rest_api_samples_current_admin_shift?' +
        'key=7.34.87.23&value=sven', 'POST')
    SampleUtilities.data_setup(
        client,
        'reference_data/maps/rest_api_samples_current_admin_shift?' +
        'key=7.34.85.10&value=sven', 'POST')
    SampleUtilities.data_setup(
        client,
        'reference_data/maps/rest_api_samples_current_admin_shift?' +
        'key=7.34.123.8&value=jill', 'POST')
    SampleUtilities.data_setup(
        client,
        'reference_data/maps/rest_api_samples_current_admin_shift?' +
        'key=7.34.10.5&value=alice', 'POST')
开发者ID:amico1234,项目名称:api-samples,代码行数:21,代码来源:02_Maps.py

示例14: main

def main():
    
    # Create our client and set up some sample data.
    client = RestApiClient()
    setup_data(client)
    
    # Some endpoints accept body parameters. An example of this is the
    # /referencedata/sets/bulkLoad endpoint.
    # Body parameters may appear with path parameters, as in this case, but will
    # never appear with query parameters.
    
    # You must make sure that you set the content type correctly to a type
    # accepted by the endpoint.
    headers = client.get_headers().copy()
    headers['Content-type'] = 'application/json'
    
    body = b'["abc", "def", "123"]'
    
    # Send the request.
    SampleUtilities.pretty_print_request(client, 'referencedata/sets/bulkLoad/rest_api_samples_testset', 'POST', headers=headers)
    response = client.call_api('referencedata/sets/bulkLoad/rest_api_samples_testset', 'POST', headers=headers, data=body)
    SampleUtilities.pretty_print_response(response)
    
    # The response from the previous command only shows information about the
    # set, not the contents of the set. We can view the contents of the set with
    # this command:
    response = client.call_api('referencedata/sets/rest_api_samples_testset', 'GET')
    SampleUtilities.pretty_print_response(response)
开发者ID:MatticusCaesar,项目名称:api-samples,代码行数:28,代码来源:04_BodyParameters.py

示例15: main

def main():
	# First we have to create our client
	client = RestApiClient()

	# This example gives a demonstration of how to create a new closing reason for your
	# offenses.

	# First, check what closing reasons are already available to avoid creating duplicates
	# Send in the GET request
	SampleUtilities.pretty_print_request(client, 'siem/offense_closing_reasons', 'GET')
	response = client.call_api('siem/offense_closing_reasons', 'GET')
	# and output the response
	SampleUtilities.pretty_print_response(response)

	if (response.code != 200):
		print('Call Failed')
		sys.exit(1)

	# Double check that the user wants to create a new closing reason
	while True:
		confirmation = input('Are you sure you want to create a new closing reason? (YES/no) ')

		if (confirmation == 'YES'):
			break
		elif (confirmation == 'no'):
			print('Not creating a new closing reason')
			exit(0)
		else:
			print(confirmation + 'is not a valid answer.')

	# Have the user input the text. quote it to retain special characters like spaces.
	text = urllib.parse.quote(input('Please enter the text you want to put in the closing reason.\n'))

	# Put through the request to add a closing reason with the text the user entered as the reason
	SampleUtilities.pretty_print_request(client, 'siem/offense_closing_reasons?reason=' + text, 'POST')
	response = client.call_api('siem/offense_closing_reasons?reason=' + text, 'POST')
	
	SampleUtilities.pretty_print_response(response)

	if (response.code != 201):
		print('Call Failed')
		sys.exit(1)

	print('Closing reason added')
开发者ID:devilcoder,项目名称:api-samples,代码行数:44,代码来源:05_ClosingReasons.py


注:本文中的SampleUtilities类示例由纯净天空整理自Github/MSDocs等开源代码及文档管理平台,相关代码片段筛选自各路编程大神贡献的开源项目,源码版权归原作者所有,传播和使用请参考对应项目的License;未经允许,请勿转载。