From 18440365680860dcb2ecb7274c53e900f45785ed Mon Sep 17 00:00:00 2001 From: Ruben Pollan Date: Wed, 20 Feb 2019 20:30:36 +0100 Subject: [PATCH] Clean up examples * Let's use the pattern 'ok, res = sdclient.operation()' * Add python3 support. * Clean up some pep8 errors. --- examples/add_policy.py | 18 +- examples/create_alert.py | 51 ++--- examples/create_dashboard.py | 30 +-- examples/create_default_policies.py | 16 +- examples/create_sysdig_capture.py | 24 +-- examples/dashboard.py | 92 ++++----- examples/delete_alert.py | 26 +-- examples/delete_all_policies.py | 20 +- examples/delete_dashboard.py | 26 +-- examples/delete_event.py | 31 ++-- examples/delete_policy.py | 22 ++- examples/get_data_advanced.py | 27 +-- examples/get_data_datasource.py | 74 ++++---- examples/get_data_simple.py | 50 +++-- examples/get_policy.py | 16 +- examples/get_secure_policy_events.py | 29 +-- examples/get_secure_system_falco_rules.py | 10 +- examples/get_secure_user_falco_rules.py | 10 +- examples/list_alert_notifications.py | 43 +++-- examples/list_alerts.py | 18 +- examples/list_dashboards.py | 16 +- examples/list_events.py | 42 +++-- examples/list_hosts.py | 57 +++--- examples/list_metrics.py | 16 +- examples/list_policies.py | 34 ++-- examples/list_sysdig_captures.py | 14 +- examples/list_users.py | 18 +- examples/notification_channels.py | 26 +-- examples/post_event.py | 22 +-- examples/post_event_simple.py | 16 +- examples/print_data_retention_info.py | 14 +- examples/print_explore_grouping.py | 8 +- examples/print_user_info.py | 28 +-- examples/resolve_alert_notifications.py | 22 +-- examples/set_secure_system_falco_rules.py | 12 +- examples/set_secure_user_falco_rules.py | 12 +- examples/update_alert.py | 34 ++-- examples/update_policy.py | 16 +- examples/user_team_mgmt.py | 62 +++---- examples/user_team_mgmt_extended.py | 215 +++++++++++----------- 40 files changed, 674 insertions(+), 643 deletions(-) diff --git a/examples/add_policy.py b/examples/add_policy.py index 73c8df3a..43ca7741 100755 --- a/examples/add_policy.py +++ b/examples/add_policy.py @@ -9,12 +9,14 @@ sys.path.insert(0, os.path.join(os.path.dirname(os.path.realpath(sys.argv[0])), '..')) from sdcclient import SdSecureClient + def usage(): - print 'usage: %s ' % sys.argv[0] - print 'Reads policy json from standard input' - print 'You can find your token at https://secure.sysdig.com/#/settings/user' + print('usage: %s ' % sys.argv[0]) + print('Reads policy json from standard input') + print('You can find your token at https://secure.sysdig.com/#/settings/user') sys.exit(1) + # # Parse arguments # @@ -30,15 +32,13 @@ def usage(): # sdclient = SdSecureClient(sdc_token, 'https://secure.sysdig.com') -res = sdclient.add_policy(policy_json) +ok, res = sdclient.add_policy(policy_json) # # Return the result # -if res[0]: - print json.dumps(res[1], indent=2) +if ok: + print(json.dumps(res, indent=2)) else: - print res[1] + print(res) sys.exit(1) - - diff --git a/examples/create_alert.py b/examples/create_alert.py index d344c83a..077934a4 100755 --- a/examples/create_alert.py +++ b/examples/create_alert.py @@ -12,17 +12,19 @@ sys.path.insert(0, os.path.join(os.path.dirname(os.path.realpath(sys.argv[0])), '..')) from sdcclient import SdcClient + # # Parse arguments # def usage(): - print 'usage: %s [-a|--alert ] ' % sys.argv[0] - print '-a|--alert: Set name of alert to create' - print 'You can find your token at https://app.sysdigcloud.com/#/settings/user' + print('usage: %s [-a|--alert ] ' % sys.argv[0]) + print('-a|--alert: Set name of alert to create') + print('You can find your token at https://app.sysdigcloud.com/#/settings/user') sys.exit(1) + try: - opts, args = getopt.getopt(sys.argv[1:],"a:",["alert="]) + opts, args = getopt.getopt(sys.argv[1:], "a:", ["alert="]) except getopt.GetoptError: usage() @@ -44,35 +46,36 @@ def usage(): # # Find notification channels (you need IDs to create an alert). # -notify_channels = [ {'type': 'SLACK', 'channel': '#python-sdc-test-alert'}, - {'type': 'EMAIL', 'emailRecipients': ['python-sdc-testing@draios.com', 'test@sysdig.com']}, - {'type': 'SNS', 'snsTopicARNs': ['arn:aws:sns:us-east-1:273107874544:alarms-stg']} - ] +notify_channels = [{'type': 'SLACK', 'channel': '#python-sdc-test-alert'}, + {'type': 'EMAIL', 'emailRecipients': ['python-sdc-testing@draios.com', 'test@sysdig.com']}, + {'type': 'SNS', 'snsTopicARNs': ['arn:aws:sns:us-east-1:273107874544:alarms-stg']} + ] -res = sdclient.get_notification_ids(notify_channels) -if not res[0]: - print "Could not get IDs and hence not creating the alert: " + res[1] +ok, res = sdclient.get_notification_ids(notify_channels) +if not ok: + print("Could not get IDs and hence not creating the alert: " + res) sys.exit(-1) -notification_channel_ids = res[1] +notification_channel_ids = res # # Create the alert. # -res = sdclient.create_alert(alert_name, # Alert name. - 'this alert was automatically created using the python Sysdig Cloud library', # Alert description. - 6, # Syslog-encoded severity. 6 means 'info'. - 60, # The alert will fire if the condition is met for at least 60 seconds. - 'avg(cpu.used.percent) > 80', # The condition. - ['host.mac', 'proc.name'], # Segmentation. We want to check this metric for every process on every machine. - 'ANY', # in case there is more than one tomcat process, this alert will fire when a single one of them crosses the 80% threshold. - 'proc.name = "tomcat"', # Filter. We want to receive a notification only if the name of the process meeting the condition is 'tomcat'. - notification_channel_ids, - False) # This alert will be disabled when it's created. +ok, res = sdclient.create_alert( + alert_name, # Alert name. + 'this alert was automatically created using the python Sysdig Cloud library', # Alert description. + 6, # Syslog-encoded severity. 6 means 'info'. + 60, # The alert will fire if the condition is met for at least 60 seconds. + 'avg(cpu.used.percent) > 80', # The condition. + ['host.mac', 'proc.name'], # Segmentation. We want to check this metric for every process on every machine. + 'ANY', # in case there is more than one tomcat process, this alert will fire when a single one of them crosses the 80% threshold. + 'proc.name = "tomcat"', # Filter. We want to receive a notification only if the name of the process meeting the condition is 'tomcat'. + notification_channel_ids, + False) # This alert will be disabled when it's created. # # Validate a print the results. # -print res[1] -if not res[0]: +print(res) +if not ok: sys.exit(1) diff --git a/examples/create_dashboard.py b/examples/create_dashboard.py index 26b09526..6ba642f0 100755 --- a/examples/create_dashboard.py +++ b/examples/create_dashboard.py @@ -12,17 +12,19 @@ sys.path.insert(0, os.path.join(os.path.dirname(os.path.realpath(sys.argv[0])), '..')) from sdcclient import SdcClient + # # Parse arguments # def usage(): - print 'usage: %s [-d|--dashboard ] ' % sys.argv[0] - print '-d|--dashboard: Set name of dashboard to create' - print 'You can find your token at https://app.sysdigcloud.com/#/settings/user' + print('usage: %s [-d|--dashboard ] ' % sys.argv[0]) + print('-d|--dashboard: Set name of dashboard to create') + print('You can find your token at https://app.sysdigcloud.com/#/settings/user') sys.exit(1) + try: - opts, args = getopt.getopt(sys.argv[1:],"d:",["dashboard="]) + opts, args = getopt.getopt(sys.argv[1:], "d:", ["dashboard="]) except getopt.GetoptError: usage() @@ -55,15 +57,15 @@ def usage(): # agent tags by using "agent.tag.*" metadata dashboardFilter = "kubernetes.namespace.name = prod and proc.name = cassandra" -print 'Creating dashboard from view' -res = sdclient.create_dashboard_from_view(dashboardName, viewName, dashboardFilter) +print('Creating dashboard from view') +ok, res = sdclient.create_dashboard_from_view(dashboardName, viewName, dashboardFilter) # # Check the result # -if res[0]: - print 'Dashboard created successfully' +if ok: + print('Dashboard created successfully') else: - print res[1] + print(res) sys.exit(1) # @@ -76,14 +78,14 @@ def usage(): # Filter to apply to the new dashboard. Same as above. dashboardFilter = "kubernetes.namespace.name = dev and proc.name = cassandra" -print 'Creating dashboard from dashboard' -res = sdclient.create_dashboard_from_dashboard(dashboardCopy, dashboardName, dashboardFilter) +print('Creating dashboard from dashboard') +ok, res = sdclient.create_dashboard_from_dashboard(dashboardCopy, dashboardName, dashboardFilter) # # Check the result # -if res[0]: - print 'Dashboard copied successfully' +if ok: + print('Dashboard copied successfully') else: - print res[1] + print(res) sys.exit(1) diff --git a/examples/create_default_policies.py b/examples/create_default_policies.py index 8643765d..57b2b556 100755 --- a/examples/create_default_policies.py +++ b/examples/create_default_policies.py @@ -12,11 +12,13 @@ sys.path.insert(0, os.path.join(os.path.dirname(os.path.realpath(sys.argv[0])), '..')) from sdcclient import SdSecureClient + def usage(): - print 'usage: %s ' % sys.argv[0] - print 'You can find your token at https://secure.sysdig.com/#/settings/user' + print('usage: %s ' % sys.argv[0]) + print('You can find your token at https://secure.sysdig.com/#/settings/user') sys.exit(1) + # # Parse arguments # @@ -30,15 +32,13 @@ def usage(): # sdclient = SdSecureClient(sdc_token, 'https://secure.sysdig.com') -res = sdclient.create_default_policies() +ok, res = sdclient.create_default_policies() # # Return the result # -if res[0]: - print json.dumps(res[1], indent=2) +if ok: + print(json.dumps(res, indent=2)) else: - print res[1] + print(res) sys.exit(1) - - diff --git a/examples/create_sysdig_capture.py b/examples/create_sysdig_capture.py index d082e66f..7cd9bcf6 100755 --- a/examples/create_sysdig_capture.py +++ b/examples/create_sysdig_capture.py @@ -13,8 +13,8 @@ # Parse arguments # if len(sys.argv) not in (5, 6): - print 'usage: %s hostname capture_name duration [filter]' % sys.argv[0] - print 'You can find your token at https://app.sysdigcloud.com/#/settings/user' + print('usage: %s hostname capture_name duration [filter]' % sys.argv[0]) + print('You can find your token at https://app.sysdigcloud.com/#/settings/user') sys.exit(1) sdc_token = sys.argv[1] @@ -31,32 +31,32 @@ # sdclient = SdcClient(sdc_token) -res = sdclient.create_sysdig_capture(hostname, capture_name, int(duration), capture_filter) +ok, res = sdclient.create_sysdig_capture(hostname, capture_name, int(duration), capture_filter) # # Show the list of metrics # -if res[0]: - capture = res[1]['dump'] +if ok: + capture = res['dump'] else: - print res[1] + print(res) sys.exit(1) while True: - res = sdclient.poll_sysdig_capture(capture) - if res[0]: - capture = res[1]['dump'] + ok, res = sdclient.poll_sysdig_capture(capture) + if ok: + capture = res['dump'] else: - print res[1] + print(res) sys.exit(1) - print 'Capture is in state ' + capture['status'] + print('Capture is in state ' + capture['status']) if capture['status'] in ('requested', 'capturing', 'uploading'): pass elif capture['status'] in ('error', 'uploadingError'): sys.exit(1) elif capture['status'] in ('done', 'uploaded'): - print 'Download at: ' + sdclient.url + capture['downloadURL'] + print('Download at: ' + sdclient.url + capture['downloadURL']) sys.exit(0) time.sleep(1) diff --git a/examples/dashboard.py b/examples/dashboard.py index aacddc62..79c5eb08 100755 --- a/examples/dashboard.py +++ b/examples/dashboard.py @@ -10,17 +10,19 @@ sys.path.insert(0, os.path.join(os.path.dirname(os.path.realpath(sys.argv[0])), '..')) from sdcclient import SdcClient + # # Parse arguments # def usage(): - print 'usage: %s [-d|--dashboard ] ' % sys.argv[0] - print '-d|--dashboard: Set name of dashboard to create' - print 'You can find your token at https://app.sysdigcloud.com/#/settings/user' + print('usage: %s [-d|--dashboard ] ' % sys.argv[0]) + print('-d|--dashboard: Set name of dashboard to create') + print('You can find your token at https://app.sysdigcloud.com/#/settings/user') sys.exit(1) + try: - opts, args = getopt.getopt(sys.argv[1:],"d:",["dashboard="]) + opts, args = getopt.getopt(sys.argv[1:], "d:", ["dashboard="]) except getopt.GetoptError: usage() @@ -44,28 +46,28 @@ def usage(): # Create an empty dashboard # dashboard_configuration = None -res = sdclient.create_dashboard(dashboard_name) +ok, res = sdclient.create_dashboard(dashboard_name) # Check the result -if res[0]: - print 'Dashboard %d created successfully' % res[1]['dashboard']['id'] - dashboard_configuration = res[1]['dashboard'] +if ok: + print('Dashboard %d created successfully' % res['dashboard']['id']) + dashboard_configuration = res['dashboard'] else: - print res[1] + print(res) sys.exit(1) # # Find a dashboard by name # -res = sdclient.find_dashboard_by(dashboard_name) +ok, res = sdclient.find_dashboard_by(dashboard_name) # Check the result -if res[0] and len(res[1]) > 0: - print 'Dashboard found' - dashboard_configuration = res[1][0]['dashboard'] +if ok and len(res) > 0: + print('Dashboard found') + dashboard_configuration = res[0]['dashboard'] else: - print res[1] + print(res) sys.exit(1) @@ -75,18 +77,18 @@ def usage(): panel_name = 'CPU Over Time' panel_type = 'timeSeries' metrics = [ - { 'id': 'kubernetes.pod.name' }, - { 'id': 'cpu.used.percent', 'aggregations': { 'time': 'avg', 'group': 'avg' } } + {'id': 'kubernetes.pod.name'}, + {'id': 'cpu.used.percent', 'aggregations': {'time': 'avg', 'group': 'avg'}} ] scope = 'kubernetes.namespace.name = "dev" and kubernetes.replicationController.name = "cassandra"' -res = sdclient.add_dashboard_panel(dashboard_configuration, panel_name, panel_type, metrics, scope=scope) +ok, res = sdclient.add_dashboard_panel(dashboard_configuration, panel_name, panel_type, metrics, scope=scope) # Check the result -if res[0]: - print 'Panel added successfully' - dashboard_configuration = res[1]['dashboard'] +if ok: + print('Panel added successfully') + dashboard_configuration = res['dashboard'] else: - print res[1] + print(res) sys.exit(1) @@ -96,19 +98,19 @@ def usage(): panel_name = 'CPU by host' panel_type = 'top' metrics = [ - { 'id': 'host.hostName' }, - { 'id': 'cpu.used.percent', 'aggregations': { 'time': 'avg', 'group': 'avg' } } + {'id': 'host.hostName'}, + {'id': 'cpu.used.percent', 'aggregations': {'time': 'avg', 'group': 'avg'}} ] -sort_by = { 'metric': 'cpu.used.percent', 'mode': 'desc' } +sort_by = {'metric': 'cpu.used.percent', 'mode': 'desc'} limit = 10 -res = sdclient.add_dashboard_panel(dashboard_configuration, panel_name, panel_type, metrics, sort_by=sort_by, limit=limit) +ok, res = sdclient.add_dashboard_panel(dashboard_configuration, panel_name, panel_type, metrics, sort_by=sort_by, limit=limit) # Check the result -if res[0]: - print 'Panel added successfully' - dashboard_configuration = res[1]['dashboard'] +if ok: + print('Panel added successfully') + dashboard_configuration = res['dashboard'] else: - print res[1] + print(res) sys.exit(1) @@ -118,42 +120,42 @@ def usage(): panel_name = 'CPU' panel_type = 'number' metrics = [ - { 'id': 'cpu.used.percent', 'aggregations': { 'time': 'avg', 'group': 'avg' } } + {'id': 'cpu.used.percent', 'aggregations': {'time': 'avg', 'group': 'avg'}} ] -layout = { 'col': 6, 'row': 1, 'size_x': 2, 'size_y': 3 } -res = sdclient.add_dashboard_panel(dashboard_configuration, panel_name, panel_type, metrics, layout=layout) +layout = {'col': 6, 'row': 1, 'size_x': 2, 'size_y': 3} +ok, res = sdclient.add_dashboard_panel(dashboard_configuration, panel_name, panel_type, metrics, layout=layout) # Check the result -if res[0]: - print 'Panel added successfully' - dashboard_configuration = res[1]['dashboard'] +if ok: + print('Panel added successfully') + dashboard_configuration = res['dashboard'] else: - print res[1] + print(res) sys.exit(1) # # Remove a panel # -res = sdclient.remove_dashboard_panel(dashboard_configuration, 'CPU') +ok, res = sdclient.remove_dashboard_panel(dashboard_configuration, 'CPU') # Check the result -if res[0]: - print 'Panel removed successfully' - dashboard_configuration = res[1]['dashboard'] +if ok: + print('Panel removed successfully') + dashboard_configuration = res['dashboard'] else: - print res[1] + print(res) sys.exit(1) # # Delete the dashboard # -res = sdclient.delete_dashboard(dashboard_configuration) +ok, res = sdclient.delete_dashboard(dashboard_configuration) # Check the result -if res[0]: - print 'Dashboard deleted successfully' +if ok: + print('Dashboard deleted successfully') else: - print res[1] + print(res) sys.exit(1) diff --git a/examples/delete_alert.py b/examples/delete_alert.py index cf1de7c5..40c948e3 100755 --- a/examples/delete_alert.py +++ b/examples/delete_alert.py @@ -9,17 +9,19 @@ sys.path.insert(0, os.path.join(os.path.dirname(os.path.realpath(sys.argv[0])), '..')) from sdcclient import SdcClient + # # Parse arguments # def usage(): - print 'usage: %s [-a|--alert ] ' % sys.argv[0] - print '-a|--alert: Set name of alert to delete' - print 'You can find your token at https://app.sysdigcloud.com/#/settings/user' + print('usage: %s [-a|--alert ] ' % sys.argv[0]) + print('-a|--alert: Set name of alert to delete') + print('You can find your token at https://app.sysdigcloud.com/#/settings/user') sys.exit(1) + try: - opts, args = getopt.getopt(sys.argv[1:],"a:",["alert="]) + opts, args = getopt.getopt(sys.argv[1:], "a:", ["alert="]) except getopt.GetoptError: usage() @@ -38,15 +40,15 @@ def usage(): # sdclient = SdcClient(sdc_token) -res = sdclient.get_alerts() -if not res[0]: - print res[1] +ok, res = sdclient.get_alerts() +if not ok: + print(res) sys.exit(1) -for alert in res[1]['alerts']: +for alert in res['alerts']: if alert['name'] == alert_name: - print "Deleting alert" - res = sdclient.delete_alert(alert) - if not res[0]: - print res[1] + print("Deleting alert") + ok, res = sdclient.delete_alert(alert) + if not ok: + print(res) sys.exit(1) diff --git a/examples/delete_all_policies.py b/examples/delete_all_policies.py index 05ed1f90..dfda73b2 100755 --- a/examples/delete_all_policies.py +++ b/examples/delete_all_policies.py @@ -9,11 +9,13 @@ sys.path.insert(0, os.path.join(os.path.dirname(os.path.realpath(sys.argv[0])), '..')) from sdcclient import SdSecureClient + def usage(): - print 'usage: %s ' % sys.argv[0] - print 'You can find your token at https://secure.sysdig.com/#/settings/user' + print('usage: %s ' % sys.argv[0]) + print('You can find your token at https://secure.sysdig.com/#/settings/user') sys.exit(1) + # # Parse arguments # @@ -28,18 +30,18 @@ def usage(): sdclient = SdSecureClient(sdc_token, 'https://secure.sysdig.com') # Get a list of policyIds -res = sdclient.list_policies() +ok, res = sdclient.list_policies() policies = [] -if not res[0]: - print res[1] +if not ok: + print(res) sys.exit(1) else: policies = res[1]['policies'] for policy in policies: - print "deleting policy: " + str(policy['id']) - res = sdclient.delete_policy_id(policy['id']) - if not res[0]: - print res[1] + print("deleting policy: " + str(policy['id'])) + ok, res = sdclient.delete_policy_id(policy['id']) + if not ok: + print(res) sys.exit(1) diff --git a/examples/delete_dashboard.py b/examples/delete_dashboard.py index 05417eef..6347f280 100755 --- a/examples/delete_dashboard.py +++ b/examples/delete_dashboard.py @@ -9,17 +9,19 @@ sys.path.insert(0, os.path.join(os.path.dirname(os.path.realpath(sys.argv[0])), '..')) from sdcclient import SdcClient + # # Parse arguments # def usage(): - print 'usage: %s [-p|--pattern ] ' % sys.argv[0] - print '-p|--pattern: Delete all dashboards containing the provided pattern' - print 'You can find your token at https://app.sysdigcloud.com/#/settings/user' + print('usage: %s [-p|--pattern ] ' % sys.argv[0]) + print('-p|--pattern: Delete all dashboards containing the provided pattern') + print('You can find your token at https://app.sysdigcloud.com/#/settings/user') sys.exit(1) + try: - opts, args = getopt.getopt(sys.argv[1:],"p:",["pattern="]) + opts, args = getopt.getopt(sys.argv[1:], "p:", ["pattern="]) except getopt.GetoptError: usage() @@ -41,18 +43,18 @@ def usage(): # # List the dashboards # -res = sdclient.get_dashboards() -if not res[0]: - print res[1] +ok, res = sdclient.get_dashboards() +if not ok: + print(res) sys.exit(1) # # Delete all the dashboards containing pattern # -for dashboard in res[1]['dashboards']: +for dashboard in res['dashboards']: if pattern in dashboard['name']: - print "Deleting " + dashboard['name'] - res = sdclient.delete_dashboard(dashboard) - if not res[0]: - print res[1] + print("Deleting " + dashboard['name']) + ok, res = sdclient.delete_dashboard(dashboard) + if not ok: + print(res) sys.exit(1) diff --git a/examples/delete_event.py b/examples/delete_event.py index d889e212..d6135dc1 100755 --- a/examples/delete_event.py +++ b/examples/delete_event.py @@ -10,17 +10,19 @@ sys.path.insert(0, os.path.join(os.path.dirname(os.path.realpath(sys.argv[0])), '..')) from sdcclient import SdcClient + # # Parse arguments # def usage(): - print 'usage: %s [-e|--event ] ' % sys.argv[0] - print '-e|--event: Name of event to delete' - print 'You can find your token at https://app.sysdigcloud.com/#/settings/user' + print('usage: %s [-e|--event ] ' % sys.argv[0]) + print('-e|--event: Name of event to delete') + print('You can find your token at https://app.sysdigcloud.com/#/settings/user') sys.exit(1) + try: - opts, args = getopt.getopt(sys.argv[1:],"e:",["event="]) + opts, args = getopt.getopt(sys.argv[1:], "e:", ["event="]) except getopt.GetoptError: usage() @@ -42,20 +44,19 @@ def usage(): # # Get the events that match a name # -res = sdclient.get_events(name=event_name) +ok, res = sdclient.get_events(name=event_name) -if not res[0]: - print res[1] - sys.exit(1) +if not ok: + print(res) + sys.exit(1) # # Delete the first event among the returned ones # -for event in res[1]['events']: - print "Deleting event " + event['name'] - - res = sdclient.delete_event(event) +for event in res['events']: + print("Deleting event " + event['name']) - if not res[0]: - print res[1] - sys.exit(1) + ok, res = sdclient.delete_event(event) + if not ok: + print(res) + sys.exit(1) diff --git a/examples/delete_policy.py b/examples/delete_policy.py index f577e307..a9a716e7 100755 --- a/examples/delete_policy.py +++ b/examples/delete_policy.py @@ -10,18 +10,20 @@ sys.path.insert(0, os.path.join(os.path.dirname(os.path.realpath(sys.argv[0])), '..')) from sdcclient import SdSecureClient + def usage(): - print 'usage: %s [-i|--id ] [-n|--name ] ' % sys.argv[0] - print '-i|--id: the id of the policy to delete' - print '-n|--name: the name of the policy to delete' - print 'You can find your token at https://secure.sysdig.com/#/settings/user' + print('usage: %s [-i|--id ] [-n|--name ] ' % sys.argv[0]) + print('-i|--id: the id of the policy to delete') + print('-n|--name: the name of the policy to delete') + print('You can find your token at https://secure.sysdig.com/#/settings/user') sys.exit(1) + # # Parse arguments # try: - opts, args = getopt.getopt(sys.argv[1:],"i:n:",["id=","name="]) + opts, args = getopt.getopt(sys.argv[1:], "i:n:", ["id=", "name="]) except getopt.GetoptError: usage() @@ -47,15 +49,15 @@ def usage(): sdclient = SdSecureClient(sdc_token, 'https://secure.sysdig.com') if len(id) > 0: - res = sdclient.delete_policy_id(id) + ok, res = sdclient.delete_policy_id(id) else: - res = sdclient.delete_policy_name(name) + ok, res = sdclient.delete_policy_name(name) # # Return the result # -if res[0]: - print json.dumps(res[1], indent=2) +if ok: + print(json.dumps(res, indent=2)) else: - print res[1] + print(res) sys.exit(1) diff --git a/examples/get_data_advanced.py b/examples/get_data_advanced.py index 5cd21561..bdedec6f 100755 --- a/examples/get_data_advanced.py +++ b/examples/get_data_advanced.py @@ -13,12 +13,13 @@ sys.path.insert(0, os.path.join(os.path.dirname(os.path.realpath(sys.argv[0])), '..')) from sdcclient import SdcClient + # # Parse arguments # if len(sys.argv) != 3: - print 'usage: %s ' % sys.argv[0] - print 'You can find your token at https://app.sysdigcloud.com/#/settings/user' + print('usage: %s ' % sys.argv[0]) + print('You can find your token at https://app.sysdigcloud.com/#/settings/user') sys.exit(1) sdc_token = sys.argv[1] @@ -44,7 +45,7 @@ "time": "avg", "group": "avg" } - } + } ] # @@ -56,22 +57,22 @@ # Paging (from and to included; by default you get from=0 to=9) # Here we'll get the top 5. # -paging = { "from": 0, "to": 4 } +paging = {"from": 0, "to": 4} # # Fire the query. # -res = sdclient.get_data(metrics=metrics, # List of metrics to query - start_ts=-600, # Start of query span is 600 seconds ago - end_ts=0, # End the query span now - sampling_s=60, # 1 data point per minute - filter=filter, # The filter specifying the target host - paging=paging, # Paging to limit to just the 5 most busy - datasource_type='container') # The source for our metrics is the container +ok, res = sdclient.get_data(metrics=metrics, # List of metrics to query + start_ts=-600, # Start of query span is 600 seconds ago + end_ts=0, # End the query span now + sampling_s=60, # 1 data point per minute + filter=filter, # The filter specifying the target host + paging=paging, # Paging to limit to just the 5 most busy + datasource_type='container') # The source for our metrics is the container # # Show the result! # -print json.dumps(res[1], sort_keys=True, indent=4) -if not res[0]: +print(json.dumps(res, sort_keys=True, indent=4)) +if not ok: sys.exit(1) diff --git a/examples/get_data_datasource.py b/examples/get_data_datasource.py index 74146b1c..0e976b08 100755 --- a/examples/get_data_datasource.py +++ b/examples/get_data_datasource.py @@ -13,8 +13,8 @@ # Parse arguments # if len(sys.argv) != 2: - print 'usage: %s ' % sys.argv[0] - print 'You can find your token at https://app.sysdigcloud.com/#/settings/user' + print('usage: %s ' % sys.argv[0]) + print('You can find your token at https://app.sysdigcloud.com/#/settings/user') sys.exit(1) sdc_token = sys.argv[1] @@ -30,7 +30,7 @@ "time": "avg", "group": "avg" } - }] + }] # # First example: CPU by host name @@ -38,18 +38,18 @@ # req = [{"id": "host.hostName"}] req.extend(cpu_metric) -res = sdclient.get_data(req, # metrics list - -600, # start_ts = 600 seconds ago - 0) # end_ts = now +ok, res = sdclient.get_data(req, # metrics list + -600, # start_ts = 600 seconds ago + 0) # end_ts = now -if res[0]: - data = res[1] +if ok: + data = res else: - print res[1] + print(res) sys.exit(1) -print "\n\nCPU by host:" -print data +print("\n\nCPU by host:") +print(data) # # Second example: CPU by container name @@ -57,51 +57,51 @@ # req = [{"id": "container.name"}] req.extend(cpu_metric) -res = sdclient.get_data(req, # metrics list - -600, # start_ts = 600 seconds ago - 0) # end_ts = now +ok, res = sdclient.get_data(req, # metrics list + -600, # start_ts = 600 seconds ago + 0) # end_ts = now -if res[0]: - data = res[1] +if ok: + data = res else: - print res[1] + print(res) sys.exit(1) -print "\n\nCPU by container:" -print data +print("\n\nCPU by container:") +print(data) # # Third example: CPU average across all hosts # datasource_type is set to host since no grouping keys or filters are specified (default would be host anyway) # -res = sdclient.get_data(cpu_metric, # metrics list - -600, # start_ts = 600 seconds ago - 0, # end_ts = now - datasource_type='host') # ask data from hosts +ok, res = sdclient.get_data(cpu_metric, # metrics list + -600, # start_ts = 600 seconds ago + 0, # end_ts = now + datasource_type='host') # ask data from hosts -if res[0]: - data = res[1] +if ok: + data = res else: - print res[1] + print(res) sys.exit(1) -print "\n\nAverage CPU across all the hosts in the infrastructure:" -print data +print("\n\nAverage CPU across all the hosts in the infrastructure:") +print(data) # # Third example: CPU average across all containers # datasource_type is set to container since no grouping keys or filters are specified (ovverrides the host default) # -res = sdclient.get_data(cpu_metric, # metrics list - -600, # start_ts = 600 seconds ago - 0, # end_ts = now - datasource_type='container') # ask data from containers +ok, res = sdclient.get_data(cpu_metric, # metrics list + -600, # start_ts = 600 seconds ago + 0, # end_ts = now + datasource_type='container') # ask data from containers -if res[0]: - data = res[1] +if ok: + data = res else: - print res[1] + print(res) sys.exit(1) -print "\n\nAverage CPU across all the containers in the infrastructure:" -print data +print("\n\nAverage CPU across all the containers in the infrastructure:") +print(data) diff --git a/examples/get_data_simple.py b/examples/get_data_simple.py index e75230f8..719b2b62 100755 --- a/examples/get_data_simple.py +++ b/examples/get_data_simple.py @@ -16,8 +16,8 @@ # Parse arguments # if len(sys.argv) != 2: - print 'usage: %s ' % sys.argv[0] - print 'You can find your token at https://app.sysdigcloud.com/#/settings/user' + print('usage: %s ' % sys.argv[0]) + print('You can find your token at https://app.sysdigcloud.com/#/settings/user') sys.exit(1) sdc_token = sys.argv[1] @@ -28,41 +28,41 @@ # List of metrics to export. Imagine a SQL data table, with key columns and value columns # You just need to specify the ID for keys, and ID with aggregation for values. # -metrics = [ - # { "id": "container.id" }, - # { "id": "agent.tag.env", "aggregations": { "time": "concat", "group": "concat" } }, - { "id": "cpu.used.percent", "aggregations": { "time": "timeAvg", "group": "avg" } } - ] +metrics = [ + # {"id": "container.id"}, + # {"id": "agent.tag.env", "aggregations": {"time": "concat", "group": "concat"}}, + {"id": "cpu.used.percent", "aggregations": {"time": "timeAvg", "group": "avg"}} +] # # Data filter or None if you want to see "everything" # -filter = None +filter = None # # Time window: # - for "from A to B": start is equal to A, end is equal to B (expressed in seconds) # - for "last X seconds": start is equal to -X, end is equal to 0 # -start = -600 -end = 0 +start = -600 +end = 0 # # Sampling time: # - for time series: sampling is equal to the "width" of each data point (expressed in seconds) # - for aggregated data (similar to bar charts, pie charts, tables, etc.): sampling is equal to 0 # -sampling = 60 +sampling = 60 # # Load data # -res = sdclient.get_data(metrics, start, end, sampling, filter = filter) +ok, res = sdclient.get_data(metrics, start, end, sampling, filter=filter) # # Show the result # -if res[0]: +if ok: # # Read response. The JSON looks like this: # @@ -78,26 +78,24 @@ # ] # } # - response = res[1] - colLen = 25 # # Print summary (what, when) # - start = response['start'] - end = response['end'] - data = response['data'] + start = res['start'] + end = res['end'] + data = res['data'] - print 'Data for %s from %d to %d' % (filter if filter else 'everything', start, end) - print '' + print('Data for %s from %d to %d' % (filter if filter else 'everything', start, end)) + print('') # # Print table headers # - dataToPrint = ' '.join( [ str(x['id']).ljust(colLen) if len(str(x['id'])) < colLen else str(x['id'])[:(colLen - 3)].ljust(colLen - 3) + '...' for x in metrics ] ) - print '%s %s' % ('timestamp'.ljust(colLen), dataToPrint) if sampling > 0 else dataToPrint - print '' + dataToPrint = ' '.join([str(x['id']).ljust(colLen) if len(str(x['id'])) < colLen else str(x['id'])[:(colLen - 3)].ljust(colLen - 3) + '...' for x in metrics]) + print('%s %s' % ('timestamp'.ljust(colLen), dataToPrint) if sampling > 0 else dataToPrint) + print('') # # Print table body @@ -106,10 +104,10 @@ timestamp = d['t'] if sampling > 0 else start values = d['d'] - dataToPrint = ' '.join( [ str(x).ljust(colLen) if len(str(x)) < colLen else str(x)[:(colLen - 3)].ljust(colLen - 3) + '...' for x in values ] ) + dataToPrint = ' '.join([str(x).ljust(colLen) if len(str(x)) < colLen else str(x)[:(colLen - 3)].ljust(colLen - 3) + '...' for x in values]) - print '%s %s' % ( ('' % (timestamp)).ljust(colLen), dataToPrint ) if sampling > 0 else dataToPrint + print('%s %s' % (('' % (timestamp)).ljust(colLen), dataToPrint) if sampling > 0 else dataToPrint) else: - print res[1] + print(res) sys.exit(1) diff --git a/examples/get_policy.py b/examples/get_policy.py index 6cce7465..ebdedc86 100755 --- a/examples/get_policy.py +++ b/examples/get_policy.py @@ -9,11 +9,13 @@ sys.path.insert(0, os.path.join(os.path.dirname(os.path.realpath(sys.argv[0])), '..')) from sdcclient import SdSecureClient + def usage(): - print 'usage: %s ' % sys.argv[0] - print 'You can find your token at https://secure.sysdig.com/#/settings/user' + print('usage: %s ' % sys.argv[0]) + print('You can find your token at https://secure.sysdig.com/#/settings/user') sys.exit(1) + # # Parse arguments # @@ -28,15 +30,13 @@ def usage(): # sdclient = SdSecureClient(sdc_token, 'https://secure.sysdig.com') -res = sdclient.get_policy(name) +ok, res = sdclient.get_policy(name) # # Return the result # -if res[0]: - print json.dumps(res[1], indent=2) +if ok: + print(json.dumps(res, indent=2)) else: - print res[1] + print(res) sys.exit(1) - - diff --git a/examples/get_secure_policy_events.py b/examples/get_secure_policy_events.py index 02c714f3..947fdeec 100755 --- a/examples/get_secure_policy_events.py +++ b/examples/get_secure_policy_events.py @@ -20,15 +20,17 @@ sys.path.insert(0, os.path.join(os.path.dirname(os.path.realpath(sys.argv[0])), '..')) from sdcclient import SdSecureClient + def usage(): - print 'usage: %s [-s|--summarize] [-l|--limit ] [| ]' % sys.argv[0] - print '-s|--summarize: group policy events by sanitized output and print by frequency' - print '-l|--limit: with -s, only print the first outputs' - print 'You can find your token at https://secure.sysdig.com/#/settings/user' + print('usage: %s [-s|--summarize] [-l|--limit ] [| ]' % sys.argv[0]) + print('-s|--summarize: group policy events by sanitized output and print by frequency') + print('-l|--limit: with -s, only print the first outputs') + print('You can find your token at https://secure.sysdig.com/#/settings/user') sys.exit(1) + try: - opts, args = getopt.getopt(sys.argv[1:],"sl:",["summarize","limit="]) + opts, args = getopt.getopt(sys.argv[1:], "sl:", ["summarize", "limit="]) except getopt.GetoptError: usage() @@ -65,9 +67,9 @@ def usage(): sdclient = SdSecureClient(sdc_token, 'https://secure.sysdig.com') if duration is not None: - res = sdclient.get_policy_events_duration(duration) + ok, res = sdclient.get_policy_events_duration(duration) else: - res = sdclient.get_policy_events_range(from_sec, to_sec) + ok, res = sdclient.get_policy_events_range(from_sec, to_sec) all_outputs = dict() @@ -76,23 +78,23 @@ def usage(): # # Return the result # - if not res[0]: - print res[1] + if not ok: + print(res) sys.exit(1) - if len(res[1]['data']['policyEvents']) == 0: + if len(res['data']['policyEvents']) == 0: break - sys.stderr.write("offset={}\n".format(res[1]['ctx']['offset'])) + sys.stderr.write("offset={}\n".format(res['ctx']['offset'])) - for event in res[1]['data']['policyEvents']: + for event in res['data']['policyEvents']: if summarize: sanitize_output = re.sub(r'\S+\s\(id=\S+\)', '', event['output']) all_outputs[sanitize_output] = all_outputs.get(sanitize_output, 0) + 1 else: sys.stdout.write(json.dumps(event) + "\n") - res = sdclient.get_more_policy_events(res[1]['ctx']) + ok, res = sdclient.get_more_policy_events(res['ctx']) if summarize: sorted = sorted(all_outputs.items(), key=operator.itemgetter(1), reverse=True) @@ -102,4 +104,3 @@ def usage(): sys.stdout.write("{} {}\n".format(val[1], val[0])) if limit != 0 and count > limit: break - diff --git a/examples/get_secure_system_falco_rules.py b/examples/get_secure_system_falco_rules.py index 839da37f..8ec0d545 100755 --- a/examples/get_secure_system_falco_rules.py +++ b/examples/get_secure_system_falco_rules.py @@ -12,8 +12,8 @@ # Parse arguments # if len(sys.argv) != 2: - print 'usage: %s ' % sys.argv[0] - print 'You can find your token at https://secure.sysdig.com/#/settings/user' + print('usage: %s ' % sys.argv[0]) + print('You can find your token at https://secure.sysdig.com/#/settings/user') sys.exit(1) sdc_token = sys.argv[1] @@ -26,13 +26,13 @@ # # Get the configuration # -res = sdclient.get_system_falco_rules() +ok, res = sdclient.get_system_falco_rules() # # Return the result # -if res[0]: +if ok: sys.stdout.write(res[1]["systemRulesFile"]["content"]) else: - print res[1] + print(res) sys.exit(1) diff --git a/examples/get_secure_user_falco_rules.py b/examples/get_secure_user_falco_rules.py index 7fdbf0c9..30d014ec 100755 --- a/examples/get_secure_user_falco_rules.py +++ b/examples/get_secure_user_falco_rules.py @@ -12,8 +12,8 @@ # Parse arguments # if len(sys.argv) != 2: - print 'usage: %s ' % sys.argv[0] - print 'You can find your token at https://secure.sysdig.com/#/settings/user' + print('usage: %s ' % sys.argv[0]) + print('You can find your token at https://secure.sysdig.com/#/settings/user') sys.exit(1) sdc_token = sys.argv[1] @@ -26,13 +26,13 @@ # # Get the configuration # -res = sdclient.get_user_falco_rules() +ok, res = sdclient.get_user_falco_rules() # # Return the result # -if res[0]: +if ok: sys.stdout.write(res[1]["userRulesFile"]["content"]) else: - print res[1] + print(res) sys.exit(1) diff --git a/examples/list_alert_notifications.py b/examples/list_alert_notifications.py index 8ddada25..1cf85027 100755 --- a/examples/list_alert_notifications.py +++ b/examples/list_alert_notifications.py @@ -9,6 +9,7 @@ sys.path.insert(0, os.path.join(os.path.dirname(os.path.realpath(sys.argv[0])), '..')) from sdcclient import SdcClient + def print_notifications(notifications): for notification in notifications: values = [] @@ -16,15 +17,16 @@ def print_notifications(notifications): for value in entity['metricValues']: values.append(str(value['value'])) - print "#%s, State: %s, Severity: %s, Scope: %s, Condition: %s, Value: %s, Resolved: %s" % \ - (notification['id'], notification['state'], notification['severity'], notification['filter'], notification['condition'], ','.join(values), notification['resolved']) + print("#%(id)s, State: %(state)s, Severity: %(severity)s, Scope: %(filter)s, Condition: %(condition)s, Value: %(values)s, Resolved: %(resolved)s" % + notification.update({'values': ','.join(values)})) + # # Parse arguments # if len(sys.argv) != 2: - print 'usage: %s ' % sys.argv[0] - print 'You can find your token at https://app.sysdigcloud.com/#/settings/user' + print('usage: %s ' % sys.argv[0]) + print('You can find your token at https://app.sysdigcloud.com/#/settings/user') sys.exit(1) sdc_token = sys.argv[1] @@ -37,35 +39,44 @@ def print_notifications(notifications): # # Get the notifications in the last day # -res = sdclient.get_notifications(from_ts=int(time.time()-86400), to_ts=int(time.time())) +ok, res = sdclient.get_notifications( + from_ts=int(time.time() - 86400), + to_ts=int(time.time())) -print_notifications(res[1]['notifications']) -if not res[0]: +print_notifications(res['notifications']) +if not ok: sys.exit(1) # # Get the notifications in the last day and active state # -res = sdclient.get_notifications(from_ts=int(time.time()-86400), to_ts=int(time.time()), state='ACTIVE') +ok, res = sdclient.get_notifications( + from_ts=int(time.time() - 86400), + to_ts=int(time.time()), state='ACTIVE') -print_notifications(res[1]['notifications']) -if not res[0]: +print_notifications(res['notifications']) +if not ok: sys.exit(1) # # Get the notifications in the last day and active state # -res = sdclient.get_notifications(from_ts=int(time.time()-86400), to_ts=int(time.time()), state='OK') +ok, res = sdclient.get_notifications( + from_ts=int(time.time() - 86400), + to_ts=int(time.time()), state='OK') -print_notifications(res[1]['notifications']) -if not res[0]: +print_notifications(res['notifications']) +if not ok: sys.exit(1) # # Get the notifications in the last day and resolved state # -res = sdclient.get_notifications(from_ts=int(time.time()-86400), to_ts=int(time.time()), resolved=True) +ok, res = sdclient.get_notifications( + from_ts=int(time.time() - 86400), + to_ts=int(time.time()), + resolved=True) -print_notifications(res[1]['notifications']) -if not res[0]: +print_notifications(res['notifications']) +if not ok: sys.exit(1) diff --git a/examples/list_alerts.py b/examples/list_alerts.py index 6d7bb881..a0f79a80 100755 --- a/examples/list_alerts.py +++ b/examples/list_alerts.py @@ -15,8 +15,8 @@ # json_dumpfilename = None if len(sys.argv) < 2 or len(sys.argv) > 3: - print 'usage: %s [json-dumpfile]' % sys.argv[0] - print 'You can find your token at https://app.sysdigcloud.com/#/settings/user' + print('usage: %s [json-dumpfile]' % sys.argv[0]) + print('You can find your token at https://app.sysdigcloud.com/#/settings/user') sys.exit(1) elif len(sys.argv) == 3: json_dumpfilename = sys.argv[2] @@ -31,20 +31,18 @@ # # Fire the request. # -res = sdclient.get_alerts() +ok, res = sdclient.get_alerts() # # Show the list of alerts # -if res[0]: - data = res[1] -else: - print res[1] +if not ok: + print(res) sys.exit(1) -for alert in data['alerts']: - print 'enabled: %s, name: %s' % (str(alert['enabled']), alert['name']) +for alert in res['alerts']: + print('enabled: %s, name: %s' % (str(alert['enabled']), alert['name'])) if json_dumpfilename: with open(json_dumpfilename, "w") as f: - json.dump(data, f, sort_keys=True, indent=4) + json.dump(res, f, sort_keys=True, indent=4) diff --git a/examples/list_dashboards.py b/examples/list_dashboards.py index ac3be654..c9c3a65b 100755 --- a/examples/list_dashboards.py +++ b/examples/list_dashboards.py @@ -12,8 +12,8 @@ # Parse arguments # if len(sys.argv) != 2: - print 'usage: %s ' % sys.argv[0] - print 'You can find your token at https://app.sysdigcloud.com/#/settings/user' + print('usage: %s ' % sys.argv[0]) + print('You can find your token at https://app.sysdigcloud.com/#/settings/user') sys.exit(1) sdc_token = sys.argv[1] @@ -26,16 +26,14 @@ # # Fire the request. # -res = sdclient.get_dashboards() +ok, res = sdclient.get_dashboards() # # Show the list of dashboards # -if res[0]: - data = res[1] -else: - print res[1] +if not ok: + print(res) sys.exit(1) -for db in data['dashboards']: - print "Name: %s, # Charts: %d" % (db['name'], len(db['items'] if 'items' in db else [])) +for db in res['dashboards']: + print("Name: %s, # Charts: %d" % (db['name'], len(db['items'] if 'items' in db else []))) diff --git a/examples/list_events.py b/examples/list_events.py index 2a82d033..8fd26bbe 100755 --- a/examples/list_events.py +++ b/examples/list_events.py @@ -8,17 +8,19 @@ sys.path.insert(0, os.path.join(os.path.dirname(os.path.realpath(sys.argv[0])), '..')) from sdcclient import SdcClient + def print_events(data): for event in data['events']: - severity = event['severity'] if event.get('severity') else 'not set' - print 'time: %d, name: %s, description: %s, severity: %s' % (event['timestamp'], event['name'], event['description'], severity) + event['sev'] = event['severity'] if event.get('severity') else 'not set' + print('time: %(timestamp)d, name: %(name)s, description: %(description)s, severity: %(sev)s' % event) + # # Parse arguments # if len(sys.argv) != 2: - print 'usage: %s ' % sys.argv[0] - print 'You can find your token at https://app.sysdigcloud.com/#/settings/user' + print('usage: %s ' % sys.argv[0]) + print('You can find your token at https://app.sysdigcloud.com/#/settings/user') sys.exit(1) sdc_token = sys.argv[1] @@ -31,43 +33,43 @@ def print_events(data): # # Get the entire list of events # -res = sdclient.get_events() +ok, res = sdclient.get_events() -if res[0]: - print_events(res[1]) +if ok: + print_events(res) else: - print res[1] + print(res) sys.exit(1) # # Get the events that match a period in time # -res = sdclient.get_events(from_ts=1460365211, to_ts=1460465211) +ok, res = sdclient.get_events(from_ts=1460365211, to_ts=1460465211) -if res[0]: - print_events(res[1]) +if ok: + print_events(res) else: - print res[1] + print(res) sys.exit(1) # # Get the events that match a name # -res = sdclient.get_events(name='test event') +ok, res = sdclient.get_events(name='test event') -if res[0]: - print_events(res[1]) +if ok: + print_events(res) else: - print res[1] + print(res) sys.exit(1) # # Get the events that match a tag/value pair # -res = sdclient.get_events(tags="tag1 = 'value1'") +ok, res = sdclient.get_events(tags="tag1 = 'value1'") -if res[0]: - print_events(res[1]) +if ok: + print_events(res) else: - print res[1] + print(res) sys.exit(1) diff --git a/examples/list_hosts.py b/examples/list_hosts.py index 85917c62..3350fb3f 100755 --- a/examples/list_hosts.py +++ b/examples/list_hosts.py @@ -18,18 +18,21 @@ sys.path.insert(0, os.path.join(os.path.dirname(os.path.realpath(sys.argv[0])), '..')) from sdcclient import SdcClient + # # Parse arguments # def usage(): - print 'usage: %s [-j|--json] [-d|--duration ] [-c|--count ] ' % sys.argv[0] - print '-d|--duration: List hosts seen in the last seconds (default: 3600, ie. last hour)' - print '-c|--count: Number of hosts to print (default: 100)' - print '-j|--json: Print output as json' - print 'You can find your token at https://app.sysdigcloud.com/#/settings/user' + print('usage: %s [-j|--json] [-d|--duration ] [-c|--count ] ' % sys.argv[0]) + print('-d|--duration: List hosts seen in the last seconds (default: 3600, ie. last hour)') + print('-c|--count: Number of hosts to print (default: 100)') + print('-j|--json: Print output as json') + print('You can find your token at https://app.sysdigcloud.com/#/settings/user') sys.exit(1) + + try: - opts, args = getopt.getopt(sys.argv[1:],"jd:c:",["json", "duration=", "count="]) + opts, args = getopt.getopt(sys.argv[1:], "jd:c:", ["json", "duration=", "count="]) except getopt.GetoptError: usage() @@ -55,37 +58,37 @@ def usage(): # - container.count: This is the metric # metrics = [ - { "id": "host.hostName" }, - { "id": "container.count", "aggregations": { "time": "avg", "group": "avg" } } + {"id": "host.hostName"}, + {"id": "container.count", "aggregations": {"time": "avg", "group": "avg"}} ] -res = sdclient.get_data( +ok, res = sdclient.get_data( metrics, # list of metrics -duration, # start time: either a unix timestamp, or a difference from "now" 0, # end time: either a unix timestamp, or a difference from "now" (0 means you need "last X seconds") duration, # sampling time, ie. data granularity; # if equal to the time window span then the result will contain a single sample - paging = { + paging={ "from": 0, "to": count - 1 }) -if res[0]: - # data fetched successfully - if print_json: - print json.dumps(res[1]) - else: - data = res[1]['data'] - output = [] - for i in range(0, len(data)): - sample = data[i] - metrics = sample['d'] - hostName = metrics[0] - count = metrics[1] - output.append('%s\t%d' % (hostName, count)) - - print '\n'.join(output) -else: +if not ok: # data fetch failed - print res[1] + print(res) sys.exit(1) + +# data fetched successfully +if print_json: + print(json.dumps(res)) +else: + data = res['data'] + output = [] + for i in range(0, len(data)): + sample = data[i] + metrics = sample['d'] + hostName = metrics[0] + count = metrics[1] + output.append('%s\t%d' % (hostName, count)) + + print '\n'.join(output) diff --git a/examples/list_metrics.py b/examples/list_metrics.py index c27ddd44..ff5231fa 100755 --- a/examples/list_metrics.py +++ b/examples/list_metrics.py @@ -12,8 +12,8 @@ # Parse arguments # if len(sys.argv) != 2: - print 'usage: %s ' % sys.argv[0] - print 'You can find your token at https://app.sysdigcloud.com/#/settings/user' + print('usage: %s ' % sys.argv[0]) + print('You can find your token at https://app.sysdigcloud.com/#/settings/user') sys.exit(1) sdc_token = sys.argv[1] @@ -26,16 +26,14 @@ # # Fire the request. # -res = sdclient.get_metrics() +ok, res = sdclient.get_metrics() # # Show the list of metrics # -if res[0]: - data = res[1] -else: - print res[1] +if not ok: + print(res) sys.exit(1) -for metric_id, metric in data.iteritems(): - print "Metric name: " + metric_id + ", type: " + metric['type'] +for metric_id, metric in res.iteritems(): + print("Metric name: " + metric_id + ", type: " + metric['type']) diff --git a/examples/list_policies.py b/examples/list_policies.py index bed6874f..ffb51b69 100755 --- a/examples/list_policies.py +++ b/examples/list_policies.py @@ -10,14 +10,16 @@ sys.path.insert(0, os.path.join(os.path.dirname(os.path.realpath(sys.argv[0])), '..')) from sdcclient import SdSecureClient + def usage(): - print 'usage: %s [-o|--order-only] ' % sys.argv[0] - print '-o|--order-only: Only display the list of policy ids in evaluation order. Suitable for use by set_policy_order.py' - print 'You can find your token at https://secure.sysdig.com/#/settings/user' + print('usage: %s [-o|--order-only] ' % sys.argv[0]) + print('-o|--order-only: Only display the list of policy ids in evaluation order. Suitable for use by set_policy_order.py') + print('You can find your token at https://secure.sysdig.com/#/settings/user') sys.exit(1) + try: - opts, args = getopt.getopt(sys.argv[1:],"o",["order-only"]) + opts, args = getopt.getopt(sys.argv[1:], "o", ["order-only"]) except getopt.GetoptError: usage() @@ -39,28 +41,26 @@ def usage(): # sdclient = SdSecureClient(sdc_token, 'https://secure.sysdig.com') -res = sdclient.get_policy_priorities() +ok, res = sdclient.get_policy_priorities() -if not res[0]: - print res[1] +if not ok: + print(res) sys.exit(1) # Strip the surrounding json to only keep the list of policy ids -res[1] = res[1]['priorities']['policyIds'] +res = res['priorities']['policyIds'] if not order_only: - priorities = res[1] - res = sdclient.list_policies() - if res[0]: - res[1]['policies'].sort(key=lambda p: priorities.index(p['id'])) + priorities = res + ok, res = sdclient.list_policies() + if ok: + res['policies'].sort(key=lambda p: priorities.index(p['id'])) # # Return the result # -if res[0]: - print json.dumps(res[1], indent=2) +if ok: + print(json.dumps(res, indent=2)) else: - print res[1] + print(res) sys.exit(1) - - diff --git a/examples/list_sysdig_captures.py b/examples/list_sysdig_captures.py index 209036e9..63b2e238 100755 --- a/examples/list_sysdig_captures.py +++ b/examples/list_sysdig_captures.py @@ -12,8 +12,8 @@ # Parse arguments # if len(sys.argv) != 2: - print 'usage: %s ' % sys.argv[0] - print 'You can find your token at https://app.sysdigcloud.com/#/settings/user' + print('usage: %s ' % sys.argv[0]) + print('You can find your token at https://app.sysdigcloud.com/#/settings/user') sys.exit(1) sdc_token = sys.argv[1] @@ -26,17 +26,17 @@ # # Fire the request. # -res = sdclient.get_sysdig_captures() +ok, res = sdclient.get_sysdig_captures() # # Show the list of metrics # -if res[0]: +if ok: captures = res[1]['dumps'] else: - print res[1] + print(res) sys.exit(1) for capture in captures: - print "Folder %s, Name %s, Host: %s, Size: %d, Status: %s" % \ - (capture['folder'], capture['name'], capture['agent']['hostName'], capture['size'], capture['status']) + print("Folder %s, Name %s, Host: %s, Size: %d, Status: %s" % + (capture['folder'], capture['name'], capture['agent']['hostName'], capture['size'], capture['status'])) diff --git a/examples/list_users.py b/examples/list_users.py index b0c72628..934beeaf 100755 --- a/examples/list_users.py +++ b/examples/list_users.py @@ -13,9 +13,9 @@ # Parse arguments # if len(sys.argv) != 2: - print 'usage: %s ' % sys.argv[0] - print 'You can find your token at https://app.sysdigcloud.com/#/settings/user' - print 'For this script to work, the user for the token must have Admin rights' + print('usage: %s ' % sys.argv[0]) + print('You can find your token at https://app.sysdigcloud.com/#/settings/user') + print('For this script to work, the user for the token must have Admin rights') sys.exit(1) sdc_token = sys.argv[1] @@ -28,11 +28,11 @@ # # Get the configuration # -res = sdclient.get_users() -if res[0]: - print 'Users\n=====' - for user in res[1]: - print user['username'] +ok, res = sdclient.get_users() +if ok: + print('Users\n=====') + for user in res: + print(user['username']) else: - print res[1] + print(res) sys.exit(1) diff --git a/examples/notification_channels.py b/examples/notification_channels.py index 10d0b76e..15e599cb 100755 --- a/examples/notification_channels.py +++ b/examples/notification_channels.py @@ -9,17 +9,19 @@ sys.path.insert(0, os.path.join(os.path.dirname(os.path.realpath(sys.argv[0])), '..')) from sdcclient import SdcClient + # # Parse arguments # def usage(): - print 'usage: %s [-c|--channel ] ' % sys.argv[0] - print '-c|--channel: Set name of channel to create' - print 'You can find your token at https://app.sysdigcloud.com/#/settings/user' + print('usage: %s [-c|--channel ] ' % sys.argv[0]) + print('-c|--channel: Set name of channel to create') + print('You can find your token at https://app.sysdigcloud.com/#/settings/user') sys.exit(1) + try: - opts, args = getopt.getopt(sys.argv[1:],"c:",["channel="]) + opts, args = getopt.getopt(sys.argv[1:], "c:", ["channel="]) except getopt.GetoptError: usage() @@ -42,21 +44,21 @@ def usage(): # # Create an email notification channel # -res = sdclient.create_email_notification_channel(channel_name, ['gianluca.borello@sysdig.com', 'foo@sysdig.com', 'bar@sysdig.com']) -if not res[0]: - print res[1] +ok, res = sdclient.create_email_notification_channel(channel_name, ['gianluca.borello@sysdig.com', 'foo@sysdig.com', 'bar@sysdig.com']) +if not ok: + print(res) sys.exit(1) # # The notification channel will contain the id, that can be used when creating alerts # -channel = res[1]['notificationChannel'] -print channel +channel = res['notificationChannel'] +print(channel) # # Notification channels can also be programmatically deleted # -res = sdclient.delete_notification_channel(channel) -if not res[0]: - print res[1] +ok, res = sdclient.delete_notification_channel(channel) +if not ok: + print(res) sys.exit(1) diff --git a/examples/post_event.py b/examples/post_event.py index cc3472fd..534fb9bd 100755 --- a/examples/post_event.py +++ b/examples/post_event.py @@ -16,18 +16,18 @@ # Usage: post_event.py [-h] [-d DESCRIPTION] [-s SEVERITY] [-c SCOPE] [-t TAGS] sysdig_token name # parser = argparse.ArgumentParser() -parser.add_argument('-d','--description') -parser.add_argument('-s','--severity', help='syslog style from 0 (high) to 7 (low)') -parser.add_argument('-c','--scope', help='metadata, in Sysdig Cloud format, of nodes to associate with the event, eg: \'host.hostName = "ip-10-1-1-1" and container.name = "foo"\'') -parser.add_argument('-t','--tags', help='dictionary of arbitrary key-value pairs, eg: \'{"app":"my_app", "file":"text.py"}\'') +parser.add_argument('-d', '--description') +parser.add_argument('-s', '--severity', help='syslog style from 0 (high) to 7 (low)') +parser.add_argument('-c', '--scope', help='metadata, in Sysdig Cloud format, of nodes to associate with the event, eg: \'host.hostName = "ip-10-1-1-1" and container.name = "foo"\'') +parser.add_argument('-t', '--tags', help='dictionary of arbitrary key-value pairs, eg: \'{"app":"my_app", "file":"text.py"}\'') parser.add_argument('sysdig_token', help='You can find your token at https://app.sysdigcloud.com/#/settings/user') parser.add_argument('name') args = parser.parse_args() -tags=None +tags = None if args.tags: - tags=json.loads(args.tags) - + tags = json.loads(args.tags) + # # Instantiate the SDC client # @@ -36,13 +36,13 @@ # # Post the event using post_event(self, name, description=None, severity=None, event_filter=None, tags=None) # -res = sdclient.post_event(args.name, args.description, args.severity, args.scope, tags) +ok, res = sdclient.post_event(args.name, args.description, args.severity, args.scope, tags) # # Return the result # -if res[0]: - print 'Event Posted Successfully' +if ok: + print('Event Posted Successfully') else: - print res[1] + print(res) sys.exit(1) diff --git a/examples/post_event_simple.py b/examples/post_event_simple.py index 88a85dcd..fe2761bb 100755 --- a/examples/post_event_simple.py +++ b/examples/post_event_simple.py @@ -12,16 +12,16 @@ # Parse arguments # if len(sys.argv) < 4: - print 'usage: %s name description [severity]' % sys.argv[0] - print 'You can find your token at https://app.sysdigcloud.com/#/settings/user' + print('usage: %s name description [severity]' % sys.argv[0]) + print('You can find your token at https://app.sysdigcloud.com/#/settings/user') sys.exit(1) sdc_token = sys.argv[1] name = sys.argv[2] description = sys.argv[3] -scope='host.hostName = "foo" and container.name = "bar"' -tags={"tag1" : "value1"} +scope = 'host.hostName = "foo" and container.name = "bar"' +tags = {"tag1": "value1"} severity = 6 if len(sys.argv) < 4: @@ -35,13 +35,13 @@ # # Post the event # -res = sdclient.post_event(name, description, severity, scope, tags) +ok, res = sdclient.post_event(name, description, severity, scope, tags) # # Return the result # -if res[0]: - print 'Event Posted Successfully' +if ok: + print('Event Posted Successfully') else: - print res[1] + print(res) sys.exit(1) diff --git a/examples/print_data_retention_info.py b/examples/print_data_retention_info.py index 6d2ac430..bc31a9db 100755 --- a/examples/print_data_retention_info.py +++ b/examples/print_data_retention_info.py @@ -12,8 +12,8 @@ # Parse arguments # if len(sys.argv) != 2: - print 'usage: %s ' % sys.argv[0] - print 'You can find your token at https://app.sysdigcloud.com/#/settings/user' + print('usage: %s ' % sys.argv[0]) + print('You can find your token at https://app.sysdigcloud.com/#/settings/user') sys.exit(1) sdc_token = sys.argv[1] @@ -26,15 +26,13 @@ # # Fire the request. # -res = sdclient.get_data_retention_info() +ok, res = sdclient.get_data_retention_info() # # Show the list of retention intervals # -if res[0]: - data = res[1] -else: - print res[1] +if not ok: + print(res) sys.exit(1) -print data['agents'] \ No newline at end of file +print res['agents'] diff --git a/examples/print_explore_grouping.py b/examples/print_explore_grouping.py index bd28e07c..19900615 100755 --- a/examples/print_explore_grouping.py +++ b/examples/print_explore_grouping.py @@ -12,8 +12,8 @@ # Parse arguments # if len(sys.argv) != 2: - print 'usage: %s ' % sys.argv[0] - print 'You can find your token at https://app.sysdigcloud.com/#/settings/user' + print('usage: %s ' % sys.argv[0]) + print('You can find your token at https://app.sysdigcloud.com/#/settings/user') sys.exit(1) sdc_token = sys.argv[1] @@ -26,9 +26,9 @@ # # Fire the request # -res = sdclient.get_explore_grouping_hierarchy() +_, res = sdclient.get_explore_grouping_hierarchy() # # Show the result # -print res[1] \ No newline at end of file +print(res) diff --git a/examples/print_user_info.py b/examples/print_user_info.py index c704a6d1..600d52b8 100755 --- a/examples/print_user_info.py +++ b/examples/print_user_info.py @@ -1,6 +1,6 @@ #!/usr/bin/env python # -# Print email, current and maximum number of agents for the Sysdig Cloud user +# Print email, current and maximum number of agents for the Sysdig Cloud user # identified by the given token. # @@ -13,8 +13,8 @@ # Parse arguments # if len(sys.argv) != 2: - print 'usage: %s ' % sys.argv[0] - print 'You can find your token at https://app.sysdigcloud.com/#/settings/user' + print('usage: %s ' % sys.argv[0]) + print('You can find your token at https://app.sysdigcloud.com/#/settings/user') sys.exit(1) sdc_token = sys.argv[1] @@ -27,25 +27,25 @@ # # Get the required info # -res = sdclient.get_user_info() +ok, res = sdclient.get_user_info() -if res[0]: - uinfo = res[1] +if ok: + uinfo = res else: - print res[1] + print(res) sys.exit(1) -res = sdclient.get_n_connected_agents() +ok, res = sdclient.get_n_connected_agents() # # Print the results # -if res[0]: - nagents = res[1] +if ok: + nagents = res else: - print res[1] + print(res) sys.exit(1) -print 'User Email: ' + uinfo['user']['username'] -print 'Current Agents: %d' % nagents -print 'Max Agents: %s' % uinfo['user']['customerSettings']['plan']['maxAgents'] +print('User Email: ' + uinfo['user']['username']) +print('Current Agents: %d' % nagents) +print('Max Agents: %s' % uinfo['user']['customerSettings']['plan']['maxAgents']) diff --git a/examples/resolve_alert_notifications.py b/examples/resolve_alert_notifications.py index 5562bf4f..2ee4722d 100755 --- a/examples/resolve_alert_notifications.py +++ b/examples/resolve_alert_notifications.py @@ -13,8 +13,8 @@ # Parse arguments # if len(sys.argv) != 3: - print 'usage: %s ' % sys.argv[0] - print 'You can find your token at https://app.sysdigcloud.com/#/settings/user' + print('usage: %s ' % sys.argv[0]) + print('You can find your token at https://app.sysdigcloud.com/#/settings/user') sys.exit(1) sdc_token = sys.argv[1] @@ -28,21 +28,21 @@ # # Get the unresolved notifications in the last day # -res = sdclient.get_notifications(from_ts=int(time.time() - int(num_days_to_resolve) * 86400), - to_ts=int(time.time()), resolved=False) +ok, res = sdclient.get_notifications(from_ts=int(time.time() - int(num_days_to_resolve) * 86400), + to_ts=int(time.time()), resolved=False) -if not res[0]: - print res[1] +if not ok: + print(res) sys.exit(1) # # Resolve them # -notifications = res[1]['notifications'] +notifications = res['notifications'] -print "Resolving " + str(len(notifications)) + " notifications" +print("Resolving " + str(len(notifications)) + " notifications") for notification in notifications: - res = sdclient.update_notification_resolution(notification, True) - if not res[0]: - print res[1] + ok, res = sdclient.update_notification_resolution(notification, True) + if not ok: + print(res) sys.exit(1) diff --git a/examples/set_secure_system_falco_rules.py b/examples/set_secure_system_falco_rules.py index 423c0ba4..ca96b77b 100755 --- a/examples/set_secure_system_falco_rules.py +++ b/examples/set_secure_system_falco_rules.py @@ -15,8 +15,8 @@ # Parse arguments # if len(sys.argv) != 3: - print 'usage: %s ' % sys.argv[0] - print 'You can find your token at https://app.sysdigcloud.com/#/settings/user' + print('usage: %s ' % sys.argv[0]) + print('You can find your token at https://app.sysdigcloud.com/#/settings/user') sys.exit(1) sdc_token = sys.argv[1] @@ -34,13 +34,13 @@ # # Push the configuration # -res = sdclient.set_system_falco_rules(yaml_conf) +ok, res = sdclient.set_system_falco_rules(yaml_conf) # # Check if everything went well # -if res[0]: - print 'system falco rules set successfully' +if ok: + print('system falco rules set successfully') else: - print res[1] + print(res) sys.exit(1) diff --git a/examples/set_secure_user_falco_rules.py b/examples/set_secure_user_falco_rules.py index 23590238..a3e968e2 100755 --- a/examples/set_secure_user_falco_rules.py +++ b/examples/set_secure_user_falco_rules.py @@ -15,8 +15,8 @@ # Parse arguments # if len(sys.argv) != 3: - print 'usage: %s ' % sys.argv[0] - print 'You can find your token at https://app.sysdigcloud.com/#/settings/user' + print('usage: %s ' % sys.argv[0]) + print('You can find your token at https://app.sysdigcloud.com/#/settings/user') sys.exit(1) sdc_token = sys.argv[1] @@ -34,13 +34,13 @@ # # Push the configuration # -res = sdclient.set_user_falco_rules(yaml_conf) +ok, res = sdclient.set_user_falco_rules(yaml_conf) # # Check if everything went well # -if res[0]: - print 'user falco rules set successfully' +if ok: + print('user falco rules set successfully') else: - print res[1] + print(res) sys.exit(1) diff --git a/examples/update_alert.py b/examples/update_alert.py index d179b53b..becd5f7b 100755 --- a/examples/update_alert.py +++ b/examples/update_alert.py @@ -12,17 +12,19 @@ sys.path.insert(0, os.path.join(os.path.dirname(os.path.realpath(sys.argv[0])), '..')) from sdcclient import SdcClient + # # Parse arguments # def usage(): - print 'usage: %s [-a|--alert ] ' % sys.argv[0] - print '-a|--alert: Set name of alert to update' - print 'You can find your token at https://app.sysdigcloud.com/#/settings/user' + print('usage: %s [-a|--alert ] ' % sys.argv[0]) + print('-a|--alert: Set name of alert to update') + print('You can find your token at https://app.sysdigcloud.com/#/settings/user') sys.exit(1) + try: - opts, args = getopt.getopt(sys.argv[1:],"a:",["alert="]) + opts, args = getopt.getopt(sys.argv[1:], "a:", ["alert="]) except getopt.GetoptError: usage() @@ -41,33 +43,33 @@ def usage(): # sdclient = SdcClient(sdc_token) -res = sdclient.get_alerts() -if not res[0]: - print res[1] +ok, res = sdclient.get_alerts() +if not ok: + print(res) sys.exit(1) alert_found = False -for alert in res[1]['alerts']: +for alert in res['alerts']: if alert['name'] == alert_name: alert_found = True - print 'Updating alert. Configuration before changing timespan, description, and notification channels:' - print json.dumps(alert, sort_keys=True, indent=4) + print('Updating alert. Configuration before changing timespan, description, and notification channels:') + print(json.dumps(alert, sort_keys=True, indent=4)) if 'notificationChannelIds' in alert: alert['notificationChannelIds'] = alert['notificationChannelIds'][0:-1] update_txt = ' (changed by update_alert)' if alert['description'][-len(update_txt):] != update_txt: alert['description'] = alert['description'] + update_txt alert['timespan'] = alert['timespan'] * 2 # Note: Expressed in seconds * 1000000 - res_update = sdclient.update_alert(alert) + ok, res_update = sdclient.update_alert(alert) - if not res_update[0]: - print res_update[1] + if not ok: + print(res_update) sys.exit(1) # Validate and print the results - print '\nAlert after modification:' - print json.dumps(res_update[1], sort_keys=True, indent=4) + print('\nAlert after modification:') + print(json.dumps(res_update, sort_keys=True, indent=4)) if not alert_found: - print 'Alert to be updated not found' + print('Alert to be updated not found') sys.exit(1) diff --git a/examples/update_policy.py b/examples/update_policy.py index 67904af3..12759f37 100755 --- a/examples/update_policy.py +++ b/examples/update_policy.py @@ -9,12 +9,14 @@ sys.path.insert(0, os.path.join(os.path.dirname(os.path.realpath(sys.argv[0])), '..')) from sdcclient import SdSecureClient + def usage(): - print 'usage: %s ' % sys.argv[0] - print 'Reads json representing updated policy from standard input' - print 'You can find your token at https://secure.sysdig.com/#/settings/user' + print('usage: %s ' % sys.argv[0]) + print('Reads json representing updated policy from standard input') + print('You can find your token at https://secure.sysdig.com/#/settings/user') sys.exit(1) + # # Parse arguments # @@ -29,15 +31,15 @@ def usage(): # sdclient = SdSecureClient(sdc_token, 'https://secure.sysdig.com') -res = sdclient.update_policy(policy_json) +ok, res = sdclient.update_policy(policy_json) # # Return the result # -if res[0]: - print json.dumps(res[1], indent=2) +if ok: + print(json.dumps(res, indent=2)) else: - print res[1] + print(res) sys.exit(1) diff --git a/examples/user_team_mgmt.py b/examples/user_team_mgmt.py index 5411e25d..0bb971b9 100755 --- a/examples/user_team_mgmt.py +++ b/examples/user_team_mgmt.py @@ -12,8 +12,8 @@ # Parse arguments # if len(sys.argv) != 4: - print 'usage: %s team-name user-name' % sys.argv[0] - print 'You can find your token at https://app.sysdigcloud.com/#/settings/user' + print('usage: %s team-name user-name' % sys.argv[0]) + print('You can find your token at https://app.sysdigcloud.com/#/settings/user') sys.exit(1) sdc_token = sys.argv[1] @@ -26,16 +26,16 @@ team_name = sys.argv[2] user_name = sys.argv[3] -print 'Trying to invite a user:', user_name +print('Trying to invite a user:', user_name) res = sdclient.create_user_invite(user_name) if res[0] == False: if res[1] == 'user ' + user_name + ' already exists': - print 'User creation failed because', user_name ,'already exists. Continuing.' + print('User creation failed because', user_name ,'already exists. Continuing.') else: - print 'User creation failed:', res[1], '. Exiting.' + print('User creation failed:', res[1], '. Exiting.') sys.exit(1) else: - print 'User creation succeeded' + print('User creation succeeded') # Possible failures on Team creation might include having reached the # max limit on Teams for this customer account or if the Team by that @@ -43,48 +43,48 @@ # would have deleted the Team by the same name, and we need to be able # to configure Teams for this test to pass, we'll treat both types of # error as a genuine fail of the test. -print 'Now trying to create a team with name:', team_name -res = sdclient.create_team(team_name) -if res[0] == False: - print 'Team creation failed:', res[1], '. Exiting.' +print('Now trying to create a team with name:', team_name) +ok, res = sdclient.create_team(team_name) +if not ok: + print('Team creation failed:', res, '. Exiting.') sys.exit(1) else: - print 'Team creation succeeded.', res[1] + print('Team creation succeeded.', res) -print 'Now trying to find team with name:', team_name -res = sdclient.get_team(team_name) -if res[0] == False: - print 'Could not get team info:', res[1], '. Exiting.' +print('Now trying to find team with name:', team_name) +ok, res = sdclient.get_team(team_name) +if not ok: + print('Could not get team info:', res, '. Exiting.') sys.exit(1) else: - print 'Team fetch succeeded' + print('Team fetch succeeded') -print 'Now trying to edit team:', team_name +print('Now trying to edit team:', team_name) memberships = { 'admin@draios.com': 'ROLE_TEAM_MANAGER', 'john-doe@sysdig.com': 'ROLE_TEAM_READ' } -res = sdclient.edit_team(team_name, description='Nextgen2', memberships=memberships) -if res[0] == False: - print 'Could not edit team:', res[1], '. Exiting.' +ok, res = sdclient.edit_team(team_name, description='Nextgen2', memberships=memberships) +if not ok: + print('Could not edit team:', res, '. Exiting.') sys.exit(1) else: - print 'Edited team to change description and add users' + print('Edited team to change description and add users') -print 'Now trying to edit user:', user_name -res = sdclient.edit_user(user_name, firstName='Just', lastName='Edited3', systemRole='ROLE_CUSTOMER') -if res[0] == False: - print 'Could not edit user:', res[1], '. Exiting.' +print('Now trying to edit user:', user_name) +ok, res = sdclient.edit_user(user_name, firstName='Just', lastName='Edited3', systemRole='ROLE_CUSTOMER') +if not ok: + print('Could not edit user:', res, '. Exiting.') sys.exit(1) else: - print 'Edit user succeeded' + print('Edit user succeeded') -print 'Now trying to delete the team:', team_name -res = sdclient.delete_team(team_name) -if res[0] == False: - print 'Could not delete team:', res[1], '. Exiting.' +print('Now trying to delete the team:', team_name) +ok, res = sdclient.delete_team(team_name) +if not ok: + print('Could not delete team:', res, '. Exiting.') sys.exit(1) else: - print 'Delete team succeeded' + print('Delete team succeeded') sys.exit(0) diff --git a/examples/user_team_mgmt_extended.py b/examples/user_team_mgmt_extended.py index da2c7785..f4078698 100755 --- a/examples/user_team_mgmt_extended.py +++ b/examples/user_team_mgmt_extended.py @@ -7,12 +7,13 @@ import sys sys.path.insert(0, os.path.join(os.path.dirname(os.path.realpath(sys.argv[0])), '..')) from sdcclient import SdcClient + # # Parse arguments # if len(sys.argv) != 4: - print 'usage: %s team-prefix user-name' % sys.argv[0] - print 'You can find your token at https://app.sysdigcloud.com/#/settings/user' + print('usage: %s team-prefix user-name' % sys.argv[0]) + print('You can find your token at https://app.sysdigcloud.com/#/settings/user') sys.exit(1) sdc_token = sys.argv[1] @@ -35,31 +36,31 @@ # admin = user_email_prefix + '+team_mgmt-admin' + '@' + user_email_domain -userA = user_email_prefix + '+team_mgmt-a' + '@' + user_email_domain -userB = user_email_prefix + '+team_mgmt-b' + '@' + user_email_domain +userA = user_email_prefix + '+team_mgmt-a' + '@' + user_email_domain +userB = user_email_prefix + '+team_mgmt-b' + '@' + user_email_domain -print 'Creating test users...' +print('Creating test users...') -res = sdclient.create_user_invite(admin, first_name='TestUser', last_name='Admin', system_role='ROLE_CUSTOMER') -if res[0] is False: - print '-- User creation failed:', res[1], '. Exiting.' +ok, res = sdclient.create_user_invite(admin, first_name='TestUser', last_name='Admin', system_role='ROLE_CUSTOMER') +if not ok: + print('-- User creation failed:', res, '. Exiting.') sys.exit(1) else: - print '-- User \'', admin, '\' created successfully.' + print('-- User \'', admin, '\' created successfully.') -res = sdclient.create_user_invite(userA, first_name='TestUser', last_name='Alpha') -if res[0] is False: - print '-- User creation failed:', res[1], '. Exiting.' +ok, res = sdclient.create_user_invite(userA, first_name='TestUser', last_name='Alpha') +if not ok: + print('-- User creation failed:', res, '. Exiting.') sys.exit(1) else: - print '-- User \'', userA, '\' created successfully.' + print('-- User \'', userA, '\' created successfully.') -res = sdclient.create_user_invite(userB, first_name='TestUser', last_name='Beta') -if res[0] is False: - print '-- User creation failed:', res[1], '. Exiting.' +ok, res = sdclient.create_user_invite(userB, first_name='TestUser', last_name='Beta') +if not ok: + print('-- User creation failed:', res[1], '. Exiting.') sys.exit(1) else: - print '-- User \'', userB, '\' created successfully.' + print('-- User \'', userB, '\' created successfully.') # # Create test teams @@ -75,21 +76,21 @@ teamA = team_prefix + 'A' teamB = team_prefix + 'B' -print 'Creating test teams...' +print('Creating test teams...') -res = sdclient.create_team(teamA) -if res[0] is False: - print '-- Team creation failed:', res[1], '. Exiting.' +ok, res = sdclient.create_team(teamA) +if not ok: + print('-- Team creation failed:', res, '. Exiting.') sys.exit(1) else: - print '-- Team \'', teamA, '\' created successfully.' + print('-- Team \'', teamA, '\' created successfully.') -res = sdclient.create_team(teamB) -if res[0] is False: - print '-- Team creation failed:', res[1], '. Exiting.' +ok, res = sdclient.create_team(teamB) +if not ok: + print('-- Team creation failed:', res, '. Exiting.') sys.exit(1) else: - print '-- Team \'', teamB, '\' created successfully.' + print('-- Team \'', teamB, '\' created successfully.') # # Membership manipulation @@ -97,153 +98,153 @@ # Admins are part of all teams and their membership cannot be edited. # -print 'Membership manipulation...' +print('Membership manipulation...') -res = sdclient.list_memberships(teamA) -if res[0] is False: - print '-- Unable to fetch team memberships:', res[1], '. Exiting.' +ok, res = sdclient.list_memberships(teamA) +if not ok: + print('-- Unable to fetch team memberships:', res, '. Exiting.') sys.exit(1) -elif admin not in res[1].keys(): - print '-- Admin should be part of all teams!', 'Exiting.' +elif admin not in res.keys(): + print('-- Admin should be part of all teams!', 'Exiting.') sys.exit(1) -elif userA in res[1].keys() or userB in res[1].keys(): - print '-- Users ', userA, ' and ', userB, ' should not be part of team ', teamA, '!', 'Exiting.' +elif userA in res.keys() or userB in res.keys(): + print('-- Users ', userA, ' and ', userB, ' should not be part of team ', teamA, '!', 'Exiting.') sys.exit(1) -res = sdclient.list_memberships(teamB) -if res[0] is False: - print '-- Unable to fetch team memberships:', res[1], '. Exiting.' +ok, res = sdclient.list_memberships(teamB) +if not ok: + print('-- Unable to fetch team memberships:', res, '. Exiting.') sys.exit(1) -elif admin not in res[1].keys(): - print '-- Admin should be part of all teams!', 'Exiting.' +elif admin not in res.keys(): + print('-- Admin should be part of all teams!', 'Exiting.') sys.exit(1) -elif userA in res[1].keys() or userB in res[1].keys(): - print '-- Users ', userA, ' and ', userB, ' should not be part of team ', teamB, '!', 'Exiting.' +elif userA in res.keys() or userB in res.keys(): + print('-- Users ', userA, ' and ', userB, ' should not be part of team ', teamB, '!', 'Exiting.') sys.exit(1) # # Create team memberships # -print '-- Create team memberships' +print('-- Create team memberships') # Manipulate with teamA -res = sdclient.save_memberships(teamA, {userA: 'ROLE_TEAM_EDIT'}) -if res[0] is False: - print '-- Unable to add ', userA, ' to ', teamA, ' due to: ', res[1], '. Exiting.' +ok, res = sdclient.save_memberships(teamA, {userA: 'ROLE_TEAM_EDIT'}) +if not ok: + print('-- Unable to add ', userA, ' to ', teamA, ' due to: ', res, '. Exiting.') sys.exit(1) -res = sdclient.list_memberships(teamA) -if res[0] is False: - print '-- Unable to fetch team memberships:', res[1], '. Exiting.' +ok, res = sdclient.list_memberships(teamA) +if not ok: + print('-- Unable to fetch team memberships:', res, '. Exiting.') sys.exit(1) -elif userA not in res[1].keys() or admin not in res[1].keys(): - print '-- Users ', userA, ' and ', admin, ' should be part of team ', teamA, '!', 'Exiting.' +elif userA not in res.keys() or admin not in res.keys(): + print('-- Users ', userA, ' and ', admin, ' should be part of team ', teamA, '!', 'Exiting.') sys.exit(1) # Manipulate with teamB -res = sdclient.save_memberships(teamB, {userA: 'ROLE_TEAM_MANAGER', userB: 'ROLE_TEAM_READ'}) -if res[0] is False: - print '-- Unable to add ', userA, ' and ', userB, ' to ', teamB, ' due to: ', res[1], '. Exiting.' +ok, res = sdclient.save_memberships(teamB, {userA: 'ROLE_TEAM_MANAGER', userB: 'ROLE_TEAM_READ'}) +if not ok: + print('-- Unable to add ', userA, ' and ', userB, ' to ', teamB, ' due to: ', res, '. Exiting.') sys.exit(1) -res = sdclient.list_memberships(teamB) -if res[0] is False: - print '-- Unable to fetch team memberships:', res[1], '. Exiting.' +ok, res = sdclient.list_memberships(teamB) +if not ok: + print('-- Unable to fetch team memberships:', res, '. Exiting.') sys.exit(1) -elif userA not in res[1].keys() or userB not in res[1].keys() or admin not in res[1].keys(): - print '-- Users ', userA, ', ', userB, ' and ', admin, ' should be part of team ', teamB, '!', 'Exiting.' +elif userA not in res.keys() or userB not in res.keys() or admin not in res.keys(): + print('-- Users ', userA, ', ', userB, ' and ', admin, ' should be part of team ', teamB, '!', 'Exiting.') sys.exit(1) # Update team memberships -print '-- Update team memberships' +print('-- Update team memberships') # Add new or update existing memberships -res = sdclient.save_memberships(teamA, {userA: 'ROLE_TEAM_READ', userB: 'ROLE_TEAM_EDIT'}) -if res[0] is False: - print '-- Unable to modify membership for ', userA, ' and to add ', userB, ' to ', teamA, ' due to: ', res[1], '. Exiting.' +ok, res = sdclient.save_memberships(teamA, {userA: 'ROLE_TEAM_READ', userB: 'ROLE_TEAM_EDIT'}) +if not ok: + print('-- Unable to modify membership for ', userA, ' and to add ', userB, ' to ', teamA, ' due to: ', res, '. Exiting.') sys.exit(1) -res = sdclient.list_memberships(teamA) -if res[0] is False: - print '-- Unable to fetch team memberships:', res[1], '. Exiting.' +ok, res = sdclient.list_memberships(teamA) +if not ok: + print('-- Unable to fetch team memberships:', res, '. Exiting.') sys.exit(1) -elif userA not in res[1].keys() or userB not in res[1].keys() or admin not in res[1].keys(): - print '-- Users ', userA, ', ', userB, ' and ', admin, ' should be part of team ', teamA, '!', 'Exiting.' +elif userA not in res.keys() or userB not in res.keys() or admin not in res.keys(): + print('-- Users ', userA, ', ', userB, ' and ', admin, ' should be part of team ', teamA, '!', 'Exiting.') sys.exit(1) -elif res[1][userA] != 'ROLE_TEAM_READ' or res[1][userB] != 'ROLE_TEAM_EDIT': - print '-- Users ', userA, ' and ', userB, ' should have appropriate roles assigned for team ', teamA, '!', 'Exiting.' +elif res[userA] != 'ROLE_TEAM_READ' or res[userB] != 'ROLE_TEAM_EDIT': + print('-- Users ', userA, ' and ', userB, ' should have appropriate roles assigned for team ', teamA, '!', 'Exiting.') sys.exit(1) # Remove team memberships -print '-- Remove team memberships' +print('-- Remove team memberships') -res = sdclient.remove_memberships(teamA, [userB]) -if res[0] is False: - print '-- Unable to remove membership for ', userB, ' from team', teamA, ' due to: ', res[1], '. Exiting.' +ok, res = sdclient.remove_memberships(teamA, [userB]) +if not ok: + print('-- Unable to remove membership for ', userB, ' from team', teamA, ' due to: ', res, '. Exiting.') sys.exit(1) -res = sdclient.list_memberships(teamA) -if res[0] is False: - print '-- Unable to fetch team memberships:', res[1], '. Exiting.' +ok, res = sdclient.list_memberships(teamA) +if not ok: + print('-- Unable to fetch team memberships:', res, '. Exiting.') sys.exit(1) -elif userB in res[1].keys(): - print '-- User ', userB, ' should not be part of team ', teamA, '!', 'Exiting.' +elif userB in res.keys(): + print('-- User ', userB, ' should not be part of team ', teamA, '!', 'Exiting.') sys.exit(1) # Admin user cannot be removed from any team -res = sdclient.remove_memberships(teamB, [admin, userA]) -if res[0] is False: - print '-- Unable to remove membership for ', userB, ' from team', teamA, ' due to: ', res[1], '. Exiting.' +ok, res = sdclient.remove_memberships(teamB, [admin, userA]) +if not ok: + print('-- Unable to remove membership for ', userB, ' from team', teamA, ' due to: ', res, '. Exiting.') sys.exit(1) -res = sdclient.list_memberships(teamB) -if res[0] is False: - print '-- Unable to fetch team memberships:', res[1], '. Exiting.' +ok, res = sdclient.list_memberships(teamB) +if not ok: + print('-- Unable to fetch team memberships:', res, '. Exiting.') sys.exit(1) -elif userA in res[1].keys(): - print '-- User ', userA, ' should not be part of team ', teamB, '!', 'Exiting.' +elif userA in res.keys(): + print('-- User ', userA, ' should not be part of team ', teamB, '!', 'Exiting.') sys.exit(1) -elif admin not in res[1].keys(): - print '-- User ', admin, ' should be always part of all teams!', 'Exiting.' +elif admin not in res.keys(): + print('-- User ', admin, ' should be always part of all teams!', 'Exiting.') sys.exit(1) # # Clean-up # -print 'Cleaning up...' +print('Cleaning up...') -print '-- Deleting test teams.' +print('-- Deleting test teams.') -res = sdclient.delete_team(teamA) -if res[0] is False: - print '-- Team \'', teamA, '\' deletion failed: ', res[1] +ok, res = sdclient.delete_team(teamA) +if not ok: + print('-- Team \'', teamA, '\' deletion failed: ', res) -res = sdclient.delete_team(teamB) -if res[0] is False: - print '-- Team \'', teamB, '\' deletion failed: ', res[1] +ok, res = sdclient.delete_team(teamB) +if not ok: + print('-- Team \'', teamB, '\' deletion failed: ', res) -print '-- Deleting test users.' +print('-- Deleting test users.') -res = sdclient.delete_user(admin) -if res[0] is False: - print '-- User \'', admin, '\' deletion failed: ', res[1] +ok, res = sdclient.delete_user(admin) +if not ok: + print('-- User \'', admin, '\' deletion failed: ', res) -res = sdclient.delete_user(userA) -if res[0] is False: - print '-- User \'', userA, '\' deletion failed: ', res[1] +ok, res = sdclient.delete_user(userA) +if not ok: + print('-- User \'', userA, '\' deletion failed: ', res) -res = sdclient.delete_user(userB) -if res[0] is False: - print '-- User \'', userB, '\' deletion failed: ', res[1] +ok, res = sdclient.delete_user(userB) +if not ok: + print('-- User \'', userB, '\' deletion failed: ', res) -print 'All done successfully!!!' +print('All done successfully!!!') sys.exit(0)