Sysdig Secure

class sdcclient.SdSecureClient(token='', sdc_url='https://secure.sysdig.com', ssl_verify=True, custom_headers=None)[source]
add_compliance_task(name, module_name='docker-bench-security', schedule='06:00:00Z/PT12H', scope=None, enabled=True)[source]
Description

Add a new compliance task.

Arguments
  • name: The name of the task e.g. ‘Check Docker Compliance’.

  • module_name: The name of the module that implements this task. Separate from task name in case you want to use the same module to run separate tasks with different scopes or schedules. [ ‘docker-bench-security’, ‘kube-bench’ ]

  • schedule: The frequency at which this task should run. Expressed as an ISO 8601 Duration

  • scope: The agent will only run the task on hosts matching this scope or on hosts where containers match this scope.

  • enabled: Whether this task should actually run as defined by its schedule.

Success Return Value

A JSON representation of the compliance task.

add_falco_list(name, items, append=False)[source]
Description

Create a new list

Arguments
  • name: A name for this object. Should exactly be the value of the “list” property of the yaml object.

  • items: the array of items as represented in the yaml List.

Success Return Value

A JSON object representing the falco list.

add_falco_macro(name, condition, append=False)[source]
Description

Create a new macro

Arguments
  • name: A name for this object. Should exactly be the value of the “macro” property of the yaml object.

  • condition: the full condition text exactly as represented in the yaml file.

Success Return Value

A JSON object representing the falco macro.

add_policy(name, description, rule_names=[], actions=[], scope=None, severity=0, enabled=True, notification_channels=[], type='falco')

Adds a new policy.

Parameters
  • name (str) – A short name for the policy

  • description (str) – Description of policy

  • rule_names (list) – Array of rule names. (They must be names instead of ids, as the rules list view is by name, to account for multiple rules having the same name).

  • actions (list) – It can be a policy_action_stop(), policy_action_pause(), policy_action_capture() or policy_action_kill() action

  • scope (str) – Where the policy is being applied- Container, Host etc.. (example: “container.image.repository = sysdig/agent”)

  • severity (int) – True if the policy should be considered

  • enabled (bool) – How severe is this policy when violated. Range from 0 to 7 included.

  • notification_channels (list) – ids of the notification channels to subscribe to the policy

  • type (str) – Type of the Policy. It can be one of: falco, list_matching, k8s_audit.

Returns: A touple (bool, res/err) where the first element indicates if the API call was successful and the second the error or the result.

Examples

>>> from sdcclient.secure import PolicyClientV2, policy_action_stop
>>> client = PolicyClientV2(sdc_url="https://secure.sysdig.com", token=SECURE_TOKEN)
>>> ok, res = client.add_policy(name="Terminal shell in container",
                                description="A shell was spawned by a program in a container with an attached terminal.",
                                rule_names=["Terminal shell in container"],
                                actions=[policy_action_stop()],
                                type="falco")
add_policy_json(policy_json)

Add a new policy using the provided json.

Parameters

policy_json – a description of the new policy

Returns: A touple (bool, res/err) where the first element indicates if the API call was successful and the second the error or the result.

Examples

>>> import sys
>>> from sdcclient.secure import PolicyClientV2
>>> client = PolicyClientV2(sdc_url="https://secure.sysdig.com", token=SECURE_TOKEN)
>>> policy_json = sys.stdin.read()
>>> ok, res = client.add_policy_json(policy_json)
add_rule(name, details={}, description='', tags=[])[source]
Description

Create a new rule

Arguments
  • name: A name for this object. Should exactly be the value of the “rule” property of the yaml object.

  • details: The rule description as a python dictionary.

  • description: A description of this rule. No newlines/formatting.

  • tags: The set of tags.

Success Return Value

A JSON object representing the rule.

clear_agents_config()
create_access_key()
Description

Create a new access key for Sysdig Monitor/Secure

Reslut

The access keys object

create_default_policies()

Create new policies based on the currently available set of rules. For now, this only covers Falco rules, but we might extend the endpoint later. The backend should use the defaultPolicies property of a previously provided FalcoRulesFiles model as guidance on the set of policies to create. The backend should only create new policies (not delete or modify), and should only create new policies if there is not an existing policy with the same name.

Returns: A touple (bool, res/err) where the first element indicates if the API call was successful and the second the error or the result.

Examples

>>> from sdcclient.secure import PolicyClientV2
>>> client = PolicyClientV2(sdc_url="https://secure.sysdig.com", token=SECURE_TOKEN)
>>> ok, res = client.create_default_policies()
create_email_notification_channel(channel_name, email_recipients)
create_notification_channel(channel)
create_sysdig_capture(hostname, capture_name, duration, capture_filter='', folder='/')
Description

Create a new sysdig capture. The capture will be immediately started.

Arguments
  • hostname: the hostname of the instrumented host where the capture will be taken.

  • capture_name: the name of the capture.

  • duration: the duration of the capture, in seconds.

  • capture_filter: a sysdig filter expression.

  • folder: directory in the S3 bucket where the capture will be saved.

Success Return Value

A dictionary showing the details of the new capture.

Example

examples/create_sysdig_capture.py

create_team(name, memberships=None, filter='', description='', show='host', theme='#7BB0B2', perm_capture=False, perm_custom_events=False, perm_aws_data=False, perm_rapid_response=False)
Description

Creates a new team

Arguments
  • name: the name of the team to create.

  • memberships: dictionary of (user-name, team-role) pairs that should describe new memberships of the team.

  • filter: the scope that this team is able to access within Sysdig Monitor.

  • description: describes the team that will be created.

  • show: possible values are host, container.

  • theme: the color theme that Sysdig Monitor will use when displaying the team.

  • perm_capture: if True, this team will be allowed to take sysdig captures.

  • perm_custom_events: if True, this team will be allowed to view all custom events from every user and agent.

  • perm_aws_data: if True, this team will have access to all AWS metrics and tags, regardless of the team’s scope.

  • perm_rapid_response: if True, this team will have access rapid response feature.

Success Return Value

The newly created team.

Example

examples/user_team_mgmt.py

create_user(user_email, first_name=None, last_name=None, password=None)

Provisions a new user to use Sysdig without sending an email notification. If password is not set through this request a random one is generated for the user which requires them to reset password on first login.

Parameters
  • user_email (str) – Email of the user to provision.

  • first_name (str) – First name of the user to provision. Can be null.

  • last_name (str) – Last name of the user to provision. Can be null.

  • password (str) – Default password for the user to provision. If this is not set, a random one is generated.

Returns

The provisioned user information.

create_user_invite(user_email, first_name=None, last_name=None, system_role=None)
Description

Invites a new user to use Sysdig Monitor. This should result in an email notification to the specified address.

Arguments
  • user_email: the email address of the user that will be invited to use Sysdig Monitor

  • first_name: the first name of the user being invited

  • last_name: the last name of the user being invited

  • system_role: system-wide privilege level for this user regardless of team. specify ‘ROLE_CUSTOMER’ to create an Admin. if not specified, default is a non-Admin (‘ROLE_USER’).

Success Return Value

The newly created user.

Examples
delete_all_policies()

Delete all existing policies.

Returns: A touple (bool, res/err) where the first element indicates if the API call was successful and the second the error or the result.

Examples

>>> from sdcclient.secure import PolicyClientV2
>>> client = PolicyClientV2(sdc_url="https://secure.sysdig.com", token=SECURE_TOKEN)
>>> ok, res = client.delete_all_policies()
delete_compliance_task(id)[source]
Description

Delete the compliance task with the given id

Arguments
  • id: the id of the compliance task to delete

delete_falco_list(id)[source]
Description

Delete the list with given id.

Arguments
  • id: The list id

Success Return Value

A JSON object representing the list.

delete_falco_macro(id)[source]
Description

Delete the macro with given id.

Arguments
  • id: The macro id

Success Return Value

A JSON object representing the macro.

delete_notification_channel(channel)
delete_policy_id(id)

Delete the policy with the given name.

Parameters

id (int) – The id of the policy to delete

Returns: A touple (bool, res/err) where the first element indicates if the API call was successful and the second the error or the JSON object representing the now-deleted policy.

Examples

>>> from sdcclient.secure import PolicyClientV2
>>> client = PolicyClientV2(sdc_url="https://secure.sysdig.com", token=SECURE_TOKEN)
>>> ok, res = client.delete_policy_id(id=123456)
delete_policy_name(name)

Delete the policy with the given name.

Parameters

name (str) – The name of the policy to delete

Returns: A touple (bool, res/err) where the first element indicates if the API call was successful and the second the error or the JSON object representing the now-deleted policy.

Examples

>>> from sdcclient.secure import PolicyClientV2
>>> client = PolicyClientV2(sdc_url="https://secure.sysdig.com", token=SECURE_TOKEN)
>>> ok, res = client.delete_policy_name(name="Terminal shell in container")
delete_rule(id)[source]
Description

Delete the rule with given id.

Arguments
  • id: The rule id

Success Return Value

A JSON object representing the rule.

delete_sysdig_capture(capture_id)

Removes an existing Sysdig Capture from Monitor

Parameters

capture_id – ID of the capture to remove

Returns: A touple of (bool, error) where the first value is false if there’s an error and the second value is the error.

delete_team(name)
Description

Deletes a team from Sysdig Monitor.

Arguments
  • name: the name of the team that will be deleted from Sysdig Monitor

Example

examples/user_team_mgmt.py

delete_user(user_email)
Description

Deletes a user from Sysdig Monitor.

Arguments
  • user_email: the email address of the user that will be deleted from Sysdig Monitor

Example

examples/user_team_mgmt.py

disable_access_key(access_key)
Description

Disable an existing access key

Arguments
  • access_key: the access key to be disabled

Reslut

The access keys object

download_sysdig_capture(capture_id)
Description

Download a sysdig capture by id.

Arguments
  • capture_id: the capture id to download.

Success Return Value

The bytes of the scap

edit_team(name, memberships=None, filter=None, description=None, show=None, theme=None, perm_capture=None, perm_custom_events=None, perm_aws_data=None, perm_rapid_response=False)
Description

Edits an existing team. All arguments are optional. Team settings for any arguments unspecified will remain at their current settings.

Arguments
  • name: the name of the team to edit.

  • memberships: dictionary of (user-name, team-role) pairs that should describe new memberships of the team.

  • filter: the scope that this team is able to access within Sysdig Monitor.

  • description: describes the team that will be created.

  • show: possible values are host, container.

  • theme: the color theme that Sysdig Monitor will use when displaying the team.

  • perm_capture: if True, this team will be allowed to take sysdig captures.

  • perm_custom_events: if True, this team will be allowed to view all custom events from every user and agent.

  • perm_aws_data: if True, this team will have access to all AWS metrics and tags, regardless of the team’s scope.

  • perm_rapid_response: if True, this team will have access rapid response feature.

Success Return Value

The edited team.

Example

examples/user_team_mgmt.py

edit_user(user_email, firstName=None, lastName=None, systemRole=None)
enable_access_key(access_key)
Description

Enable an existing access key

Arguments
  • access_key: the access key to be enabled

Reslut

The access keys object

get_agents_config()
get_command_audit(id, metrics=[])[source]
Description

Get a command audit.

DEPRECATED: Use sdcclient.secure.ActivityAuditClientV1 instead. This is maintained for old on-prem versions, but will be removed over time.

Arguments
  • id: the id of the command audit to get.

Success Return Value

A JSON representation of the command audit.

get_compliance_results(id)[source]
Description

Retrieve the details for a specific compliance task run result.

Arguments
  • id: the id of the compliance task run to get.

Success Return Value

A JSON representation of the compliance task run result.

get_compliance_results_csv(id)[source]
Description

Retrieve the details for a specific compliance task run result in csv.

Arguments
  • id: the id of the compliance task run to get.

Success Return Value

A CSV representation of the compliance task run result.

get_compliance_task(id)[source]
Description

Get a compliance task.

Arguments
  • id: the id of the compliance task to get.

Success Return Value

A JSON representation of the compliance task.

get_connected_agents()
Description

Return the agents currently connected to Sysdig Monitor for the current user.

Success Return Value

A list of the agents with all their attributes.

get_data(metrics, start_ts, end_ts=0, sampling_s=0, filter='', datasource_type='host', paging=None)
Description

Export metric data (both time-series and table-based).

Arguments
  • metrics: a list of dictionaries, specifying the metrics and grouping keys that the query will return. A metric is any of the entries that can be found in the Metrics section of the Explore page in Sysdig Monitor. Metric entries require an aggregations section specifying how to aggregate the metric across time and containers/hosts. A grouping key is any of the entries that can be found in the Show or Segment By sections of the Explore page in Sysdig Monitor. These entries are used to apply single or hierarchical segmentation to the returned data and don’t require the aggregations section. Refer to the Example link below for ready-to-use code snippets.

  • start_ts: the UTC time (in seconds) of the beginning of the data window. A negative value can be optionally used to indicate a relative time in the past from now. For example, -3600 means “one hour ago”.

  • end_ts: the UTC time (in seconds) of the end of the data window, or 0 to indicate “now”. A negative value can also be optionally used to indicate a relative time in the past from now. For example, -3600 means “one hour ago”.

  • sampling_s: the duration of the samples that will be returned. 0 means that the whole data will be returned as a single sample.

  • filter: a boolean expression combining Sysdig Monitor segmentation criteria that defines what the query will be applied to. For example: kubernetes.namespace.name=’production’ and container.image=’nginx’.

  • datasource_type: specify the metric source for the request, can be container or host. Most metrics, for example cpu.used.percent or memory.bytes.used, are reported by both hosts and containers. By default, host metrics are used, but if the request contains a container-specific grouping key in the metric list/filter (e.g. container.name), then the container source is used. In cases where grouping keys are missing or apply to both hosts and containers (e.g. tag.Name), datasource_type can be explicitly set to avoid any ambiguity and allow the user to select precisely what kind of data should be used for the request. examples/get_data_datasource.py contains a few examples that should clarify the use of this argument.

  • paging: if segmentation of the query generates values for several different entities (e.g. containers/hosts), this parameter specifies which to include in the returned result. It’s specified as a dictionary of inclusive values for from and to with the default being { "from": 0, "to": 9 }, which will return values for the “top 10” entities. The meaning of “top” is query-dependent, based on points having been sorted via the specified group aggregation, with the results sorted in ascending order if the group aggregation is min or none, and descending order otherwise.

Success Return Value

A dictionary with the requested data. Data is organized in a list of time samples, each of which includes a UTC timestamp and a list of values, whose content and order reflect what was specified in the metrics argument.

Examples
get_data_retention_info()
Description

Return the list of data retention intervals, with beginning and end UTC time for each of them. Sysdig Monitor performs rollups of the data it stores. This means that data is stored at different time granularities depending on how far back in time it is. This call can be used to know what precision you can expect before you make a call to get_data().

Success Return Value

A dictionary containing the list of available sampling intervals.

Example

examples/print_data_retention_info.py

get_default_falco_rules_files()
Description
Get the set of falco rules files from the backend. The _files programs and endpoints are a

replacement for the system_file endpoints and allow for publishing multiple files instead of a single file as well as publishing multiple variants of a given file that are compatible with different agent versions.

Arguments
  • None

Success Return Value
A dict with the following keys:
  • tag: A string used to uniquely identify this set of rules. It is recommended that this tag change every time the set of rules is updated.

  • files: An array of dicts. Each dict has the following keys:
    • name: the name of the file

    • variants: An array of dicts with the following keys:
      • requiredEngineVersion: the minimum falco engine version that can read this file

      • content: the falco rules content

An example would be:
{‘tag’: ‘v1.5.9’,
‘files’: [
{

‘name’: ‘falco_rules.yaml’, ‘variants’: [

{

‘content’: ‘- required_engine_version: 29

  • list: foo

‘,

‘requiredEngineVersion’: 29

}, {

‘content’: ‘- required_engine_version: 1

  • list: foo

‘,

‘requiredEngineVersion’: 1

}

]

}, {

‘name’: ‘k8s_audit_rules.yaml’, ‘variants’: [

{

‘content’: ‘# some comment

‘,

‘requiredEngineVersion’: 0

}

]

}

]

}

Example

examples/get_default_falco_rules_files.py

get_falco_list_id(id)[source]
Description

Retrieve info about a single falco list

Arguments
  • id: the id of the falco list

Success Return Value

A JSON object representing the falco list.

get_falco_lists_group(name)[source]
Description

Retrieve a group of all falco lists having the given name. This is used to show how a base list is modified by later lists that override/append to the list.

Arguments
  • name: the name of the falco lists group

Success Return Value

A JSON object representing the list of falco lists.

get_falco_macro_id(id)[source]
Description

Retrieve info about a single falco macro

Arguments
  • id: the id of the falco macro

Success Return Value

A JSON object representing the falco macro.

get_falco_macros_group(name)[source]
Description

Retrieve a group of all falco groups having the given name. This is used to show how a base macro is modified by later macrosthat override/append to the macro.

Arguments
  • name: the name of the falco macros group

Success Return Value

A JSON object representing the list of falco macros.

get_image_profile(profileId)[source]
Description

Find the image profile with a (partial) profile ID <profileId> and return its json description.

Arguments
  • name: the name of the image profile to fetch

Success Return Value

A JSON object containing the description of the image profile. If there is no image profile with the given name, returns False. Moreover, it could happen that more than one profile IDs have a collision. It is due to the fact that a partial profile ID can be passed and interpreted; in this case a set of collision profiles is returned, and the full complete ID string is printed. In this case, it returns false.

get_more_policy_events(ctx)
Description

Fetch additional policy events after an initial call to get_policy_events_range() / get_policy_events_duration() or a prior call to get_more_policy_events.

Arguments
Success Return Value
An array containing:
  • A context object that should be passed to later calls to get_more_policy_events()

  • An array of policy events, in JSON format. Each policy event contains the following:
    • id: a unique identifier for this policy event

    • cursor: unique ID that can be used with get_more_policy_events context to retrieve paginated policy events

    • timestamp: when the event occurred (ns since the epoch)

    • source: the source of the policy event. It can be “syscall” or “k8s_audit”

    • description: the description of the event

    • severity: a severity level from 1-7

    • agentId: the agent that reported this event

    • machineId: the MAC of the machine that reported this event

    • content: More information about what triggered the event
      • falsePositive: if the event is considered a false-positive

      • fields: raw information from the rule that fired this event

      • output: Output from the rule that fired this event

      • policyId: the ID of the policy that fired this event

      • ruleName: name of the rule that fired this event

      • ruleTags: tags from the rule that fired this event

    • labels: more information from the scope of this event

When the number of policy events returned is 0, there are no remaining events and you can stop calling get_more_policy_events().

Example

examples/get_secure_policy_events.py

get_n_connected_agents()
Description

Return the number of agents currently connected to Sysdig Monitor for the current user.

Success Return Value

An integer number.

get_notification_channel(id)
get_notification_ids(channels=None)
Description

Get an array of all configured Notification Channel IDs, or a filtered subset of them.

Arguments
  • channels: an optional array of dictionaries to limit the set of Notification Channel IDs returned. If not specified, IDs for all configured Notification Channels are returned. Each dictionary contains a type field that can be one of the available types of Notification Channel (EMAIL, SNS, PAGER_DUTY, SLACK, OPSGENIE, VICTOROPS, WEBHOOK) as well as additional elements specific to each channel type.

Success Return Value

An array of Notification Channel IDs (integers).

Examples
get_policy(name)

Find the policy with name <name> and return its json description.

Parameters

name (str) – The name of the policy to fetch

Returns: A touple (bool, res/err) where the first element indicates if the API call was successful and the second the error or the JSON object containing the policy.

Examples

>>> import json
>>> from sdcclient.secure import PolicyClientV2
>>> client = PolicyClientV2(sdc_url="https://secure.sysdig.com", token=SECURE_TOKEN)
>>> ok, res = client.get_policy(name="Terminal shell in container")
>>> if ok:
>>>     print((json.dumps(res, indent=2)))
get_policy_event(event_id)
Parameters

event_id – The ID of the Runtime Policy event to retrieve more info from.

Returns

A tuple where the first parameter indicates if the request was successful, and the second parameter holds the info from the policy event or the error.

get_policy_events_duration(duration_sec, filter=None)
Description

Fetch all policy events that occurred in the last duration_sec seconds. This method is used in conjunction with get_more_policy_events() to provide paginated access to policy events.

Arguments
  • duration_sec: Fetch all policy events that have occurred in the last duration_sec seconds.

  • filter: this is a SysdigMonitor-like filter (e.g. filter: ‘severity in (“4”,”5”) and freeText in (“Suspicious”)’)

Success Return Value
An array containing:
  • A context object that should be passed to later calls to get_more_policy_events.

  • An array of policy events, in JSON format. See get_more_policy_events() for details on the contents of policy events.

Example

examples/get_secure_policy_events.py

get_policy_events_id_duration(id, duration_sec, sampling=None, aggregations=None, scope_filter=None, event_filter=None)
Description

Fetch all policy events with id that occurred in the last duration_sec seconds. This method is used in conjunction with get_more_policy_events() to provide paginated access to policy events.

Arguments
  • id: the id of the policy events to fetch.

  • duration_sec: Fetch all policy events that have occurred in the last duration_sec seconds.

  • sampling: Sample all policy events using sampling interval.

  • aggregations: When present it specifies how to aggregate events (sampling does not need to be specified, because when it’s present it automatically means events will be aggregated). This field can either be a list of scope metrics or a list of policyEvents fields but (currently) not a mix of the two. When policy events fields are specified, only these can be used= severity, agentId, containerId, policyId, ruleType.

  • scope_filter: this is a SysdigMonitor-like filter (e.g ‘container.image=ubuntu’). When provided, events are filtered by their scope, so only a subset will be returned (e.g. ‘container.image=ubuntu’ will provide only events that have happened on an ubuntu container).

  • event_filter: this is a SysdigMonitor-like filter (e.g. policyEvent.policyId=3). When provided, events are filtered by some of their properties. Currently the supported set of filters is policyEvent.all(which can be used just with matches, policyEvent.policyId, policyEvent.id, policyEvent.severity, policyEvent.ruleTye, policyEvent.ruleSubtype.

Success Return Value
An array containing:
  • A context object that should be passed to later calls to get_more_policy_events.

  • An array of policy events, in JSON format. See get_more_policy_events() for details on the contents of policy events.

Example

examples/get_secure_policy_events.py

get_policy_events_id_range(id, from_sec, to_sec, sampling=None, aggregations=None, scope_filter=None, event_filter=None)
Description

Fetch all policy events with id that occurred in the time range [from_sec:to_sec]. This method is used in conjunction with get_more_policy_events() to provide paginated access to policy events.

Arguments
  • id: the id of the policy events to fetch.

  • from_sec: the start of the timerange for which to get events

  • end_sec: the end of the timerange for which to get events

  • sampling: sample all policy events using sampling interval.

  • scope_filter: this is a SysdigMonitor-like filter (e.g ‘container.image=ubuntu’). When provided, events are filtered by their scope, so only a subset will be returned (e.g. ‘container.image=ubuntu’ will provide only events that have happened on an ubuntu container).

  • event_filter: this is a SysdigMonitor-like filter (e.g. policyEvent.policyId=3). When provided, events are filtered by some of their properties. Currently the supported set of filters is policyEvent.all(which can be used just with matches, policyEvent.policyId, policyEvent.id, policyEvent.severity, policyEvent.ruleTye, policyEvent.ruleSubtype.

  • aggregations: When present it specifies how to aggregate events (sampling does not need to be specified, because when it’s present it automatically means events will be aggregated). This field can either be a list of scope metrics or a list of policyEvents fields but (currently) not a mix of the two. When policy events fields are specified, only these can be used= severity, agentId, containerId, policyId, ruleType.

Success Return Value
An array containing:
  • A context object that should be passed to later calls to get_more_policy_events.

  • An array of policy events, in JSON format. See get_more_policy_events() for details on the contents of policy events.

Example

examples/get_secure_policy_events.py

get_policy_events_range(from_sec, to_sec, filter=None)
Description

Fetch all policy events that occurred in the time range [from_sec:to_sec]. This method is used in conjunction with get_more_policy_events() to provide paginated access to policy events.

Arguments
  • from_sec: the start of the timerange for which to get events

  • end_sec: the end of the timerange for which to get events

  • filter: this is a SysdigMonitor-like filter (e.g. filter: ‘severity in (“4”,”5”) and freeText in (“Suspicious”)’)

Success Return Value
An array containing:
  • A context object that should be passed to later calls to get_more_policy_events.

  • An array of policy events, in JSON format. See get_more_policy_events() for details on the contents of policy events.

Example

examples/get_secure_policy_events.py

get_policy_id(id)

Find the policy with id <id> and return its json description.

Parameters

id (int) – The id of the policy to fetch

Returns: A touple (bool, res/err) where the first element indicates if the API call was successful and the second the error or the JSON object containing the policy.

Examples

>>> import json
>>> from sdcclient.secure import PolicyClientV2
>>> client = PolicyClientV2(sdc_url="https://secure.sysdig.com", token=SECURE_TOKEN)
>>> ok, res = client.get_policy_id(id=123456)
>>> if ok:
>>>     print((json.dumps(res, indent=2)))
get_rule_id(id)[source]
Description

Retrieve info about a single rule

Arguments
  • id: the id of the rule

Success Return Value

A JSON object representing the rule.

get_rules_group(name)[source]
Description

Retrieve a group of all rules having the given name. This is used to show how a base rule is modified by later rules that override/append to the rule.

Arguments
  • name: the name of the rule group

Success Return Value

A JSON object representing the list of rules.

get_sysdig_captures(from_sec=None, to_sec=None, scope_filter=None)
Description

Returns the list of sysdig captures for the user.

Arguments
  • from_sec: the start of the timerange for which to get the captures

  • end_sec: the end of the timerange for which to get the captures

  • scope_filter: this is a SysdigMonitor-like filter (e.g ‘container.image=ubuntu’). When provided, events are filtered by their scope, so only a subset will be returned (e.g. ‘container.image=ubuntu’ will provide only events that have happened on an ubuntu container).

Success Return Value

A dictionary containing the list of captures.

Example

examples/list_sysdig_captures.py

get_system_falco_rules()
Description

Get the system falco rules file in use for this customer. See the Falco wiki for documentation on the falco rules format.

Arguments
  • None

Success Return Value

The contents of the system falco rules file.

Example

examples/get_secure_system_falco_rules.py

get_team(name)
Description

Return the team with the specified team name, if it is present.

Arguments
  • name: the name of the team to return

Success Return Value

The requested team.

Example

examples/user_team_mgmt.py

get_team_ids(teams)
get_teams(team_filter='')
Description

Return the set of teams that match the filter specified. The team_filter should be a substring of the names of the teams to be returned.

Arguments
  • team_filter: the team filter to match when returning the list of teams

Success Return Value

The teams that match the filter.

get_topology_map(grouping_hierarchy, time_window_s, sampling_time_s)
get_user(user_email)
get_user_api_token(username, teamname)
get_user_falco_rules()
Description

Get the user falco rules file in use for this customer. See the Falco wiki for documentation on the falco rules format.

Arguments
  • None

Success Return Value

The contents of the user falco rules file.

Example

examples/get_secure_user_falco_rules.py

get_user_ids(users)
get_user_info()
Description

Get details about the current user.

Success Return Value

A dictionary containing information about the user, for example its email and the maximum number of agents it can install.

Example

examples/print_user_info.py

get_user_token()
Description

Return the API token of the current user.

Success Return Value

A string containing the user token.

get_users()
Description

Return a list containing details about all users in the Sysdig Monitor environment. The API token must have Admin rights for this to succeed.

Success Return Value

A list user objects

lasterr = None
list_access_keys()
Description

List all the access keys enabled and disabled for this instance of Sysdig Monitor/Secure

Reslut

A list of access keys objects

Example

examples/list_access_keys.py

list_commands_audit(from_sec=None, to_sec=None, scope_filter=None, command_filter=None, limit=100, offset=0, metrics=[])[source]
Description

List the commands audit.

DEPRECATED: Use sdcclient.secure.ActivityAuditClientV1 instead. This is maintained for old on-prem versions, but will be removed over time.

Arguments
  • from_sec: the start of the timerange for which to get commands audit.

  • end_sec: the end of the timerange for which to get commands audit.

  • scope_filter: this is a SysdigMonitor-like filter (e.g ‘container.image=ubuntu’). When provided, commands are filtered by their scope, so only a subset will be returned (e.g. ‘container.image=ubuntu’ will provide only commands that have happened on an ubuntu container).

  • command_filter: this is a SysdigMonitor-like filter (e.g. command.comm=”touch”). When provided, commands are filtered by some of their properties. Currently the supported set of filters is command.comm, command.cwd, command.pid, command.ppid, command.uid, command.loginshell.id, command.loginshell.distance

  • limit: Maximum number of commands in the response.

  • metrics: A list of metric values to include in the return.

Success Return Value

A JSON representation of the commands audit.

list_compliance_results(limit=50, direction=None, cursor=None, filter='')[source]
Description

Get the list of all compliance tasks runs.

Arguments
  • limit: Maximum number of alerts in the response.

  • direction: the direction (PREV or NEXT) that determines which results to return in relation to cursor.

  • cursor: An opaque string representing the current position in the list of alerts. It’s provided in the ‘responseMetadata’ of the list_alerts response.

  • filter: an optional case insensitive filter used to match against the completed task name and return matching results.

Success Return Value

A JSON list with the representation of each compliance task run.

list_compliance_tasks()[source]
Description

Get the list of all compliance tasks.

Arguments
  • None

Success Return Value

A JSON list with the representation of each compliance task.

list_falco_lists()[source]
Description

Returns the list of falco lists in the system. These are grouped by name and do not necessarily represent individual falco list objects, as multiple falco lists can have the same name.

Arguments
  • None

Success Return Value

A JSON object representing the list of falco lists.

list_falco_macros()[source]
Description

Returns the list of macros in the system. These are grouped by name and do not necessarily represent individual macro objects, as multiple macros can have the same name.

Arguments
  • None

Success Return Value

A JSON object representing the list of falco macros.

list_image_profiles()[source]
Description

List the current set of image profiles.

Arguments
  • None

Success Return Value

A JSON object containing the details of each profile.

list_memberships(team)
Description

List all memberships for specified team.

Arguments
  • team: the name of the team for which we want to see memberships

Result

Dictionary of (user-name, team-role) pairs that should describe memberships of the team.

Example

examples/user_team_mgmt_extended.py

list_notification_channels()
Description

List all configured Notification Channels

Arguments

none

Success Return Value

A JSON representation of all the notification channels

list_policies()

List the current set of policies.

Returns: A touple (bool, res/err) where the first element indicates if the API call was successful and the second the error or the result.

Examples

>>> from sdcclient.secure import PolicyClientV2
>>> client = PolicyClientV2(sdc_url="https://secure.sysdig.com", token=SECURE_TOKEN)
>>> ok, res = client.list_policies()
list_rules()[source]
Description

Returns the list of rules in the system. These are grouped by name and do not necessarily represent individual rule objects, as multiple rules can have the same name.

Arguments
  • None

Success Return Value

A JSON object representing the list of rules.

load_default_falco_rules_files(save_dir)
Description

Given a file and directory layout as described in save_default_falco_rules_files(), load those files and return a dict representing the contents. This dict is suitable for passing to set_default_falco_rules_files().

Arguments
  • save_dir: a directory path from which to load the files.

Success Return Value
  • A dict matching the format described in get_default_falco_rules_files.

Example

examples/set_default_falco_rules_files.py

property policy_v2

Description True if policy V2 API is available

poll_sysdig_capture(capture)
Description

Fetch the updated state of a sysdig capture. Can be used to poll the status of a capture that has been previously created and started with create_sysdig_capture().

Arguments
  • capture: the capture object as returned by get_sysdig_captures() or create_sysdig_capture().

Success Return Value

A dictionary showing the updated details of the capture. Use the status field to check the progress of a capture.

Example

examples/create_sysdig_capture.py

remove_memberships(team, users)
Description

Remove user memberships from specified team.

Arguments
  • team: the name of the team from which user memberships are removed

  • users: list of usernames which should be removed from team

Example

examples/user_team_mgmt_extended.py

save_default_falco_rules_files(fsobj, save_dir)
Description
Given a dict returned from get_default_falco_rules_files, save those files to a set of files below save_dir.

The first level below save_dir is a directory with the tag name and an optional default_policies.yaml file, which groups rules into recommended default policies. The second level is a directory per file. The third level is a directory per variant. Finally the files are at the lowest level, in a file called “content”.

For example, using the example dict in get_default_falco_rules_files(), the directory layout would look like:
save_dir/

default_policies.yaml v1.5.9/

falco_rules.yaml/
29/

content: a file containing “- required_engine_version: 29

  • list: foo

1/

content: a file containing “- required_engine_version: 1

  • list: foo

k8s_audit_rules.yaml/
0/

content: a file containing “# some comment”

Arguments
  • fsobj: a python dict matching the structure returned by get_default_falco_rules_files()

  • save_dir: a directory path under which to save the files. If the path already exists, it will be removed first.

Success Return Value
  • None

Example

examples/get_default_falco_rules_files.py

save_memberships(team, memberships)
Description

Create new user team memberships or update existing ones.

Arguments
  • team: the name of the team for which we are creating new memberships

  • memberships: dictionary of (user-name, team-role) pairs that should describe new memberships

Example

examples/user_team_mgmt_extended.py

set_agents_config(config)
set_default_falco_rules_files(rules_files)
Description
Update the set of falco rules files to the provided set of files. See the Falco wiki for documentation on the falco rules format.

The _files programs and endpoints are a replacement for the system_file endpoints and allow for publishing multiple files instead of a single file as well as publishing multiple variants of a given file that are compatible with different agent versions.

Arguments
  • rules_files: a dict with the same structure as returned by get_default_falco_rules_files.

Success Return Value

The contents of the default falco rules files that were just updated.

Example

examples/set_default_falco_rules_files.py

set_system_falco_rules(rules_content)
Description

Set the system falco rules file in use for this customer. NOTE: This API endpoint can only be used in on-premise deployments. Generally the system falco rules file is only modified in conjunction with Sysdig support. See the Falco wiki for documentation on the falco rules format.

Arguments
  • A string containing the system falco rules.

Success Return Value

The contents of the system falco rules file that were just updated.

Example

examples/set_secure_system_falco_rules.py

set_user_falco_rules(rules_content)
Description

Set the user falco rules file in use for this customer. See the Falco wiki for documentation on the falco rules format.

Arguments
  • A string containing the user falco rules.

Success Return Value

The contents of the user falco rules file that were just updated.

Example

examples/set_secure_user_falco_rules.py

update_compliance_task(id, name=None, module_name=None, schedule=None, scope=None, enabled=None)[source]
Description

Update an existing compliance task.

Arguments
  • id: the id of the compliance task to be updated.

  • name: The name of the task e.g. ‘Check Docker Compliance’.

  • module_name: The name of the module that implements this task. Separate from task name in case you want to use the same module to run separate tasks with different scopes or schedules. [ ‘docker-bench-security’, ‘kube-bench’ ]

  • schedule: The frequency at which this task should run. Expressed as an ISO 8601 Duration

  • scope: The agent will only run the task on hosts matching this scope or on hosts where containers match this scope.

  • enabled: Whether this task should actually run as defined by its schedule.

Success Return Value

A JSON representation of the compliance task.

update_falco_list(id, items)[source]
Description

Update info associated with a list

Arguments
  • id: The rule id

  • items: the array of items as represented in the yaml List.

Success Return Value

A JSON object representing the list.

update_falco_macro(id, condition)[source]
Description

Update info associated with a macro

Arguments
  • id: The rule id

  • condition: the full condition text exactly as represented in the yaml file.

Success Return Value

A JSON object representing the macro.

update_notification_channel(channel)
update_policy(id, name=None, description=None, rule_names=None, actions=None, scope=None, severity=None, enabled=None, notification_channels=None)

Update policy with the provided values. Only the defined values will be updated.

Parameters
  • id (int) – The id of the policy to update

  • name (str) – A short name for the policy

  • description (str) – Description of policy

  • rule_names (list) – Array of rule names. (They must be names instead of ids, as the rules list view is by name, to account for multiple rules having the same name).

  • actions (list) – It can be a policy_action_stop(), policy_action_pause(), policy_action_capture() or policy_action_kill() action

  • scope (str) – Where the policy is being applied- Container, Host etc.. (example: “container.image.repository = sysdig/agent”)

  • severity (int) – True if the policy should be considered

  • enabled (bool) – How severe is this policy when violated. Range from 0 to 7 included.

  • notification_channels (list) – ids of the notification channels to subscribe to the policy

Returns: A touple (bool, res/err) where the first element indicates if the API call was successful and the second the error or the result.

Examples

>>> from sdcclient.secure import PolicyClientV2, policy_action_stop
>>> client = PolicyClientV2(sdc_url="https://secure.sysdig.com", token=SECURE_TOKEN)
>>> ok, res = client.update_policy(name="Terminal shell in container",
                                   description="A shell was spawned by a program in a container with an attached terminal.",
                                   rule_names=["Terminal shell in container"],
                                   actions=[policy_action_stop()])
update_policy_json(policy_json)

Update an existing policy using the provided json. The ‘id’ field from the policy is used to determine which policy to update.

Parameters

policy_json (str) – A description of the new policy

Returns: A touple (bool, res/err) where the first element indicates if the API call was successful and the second the error or the result.

Examples

>>> import sys
>>> from sdcclient.secure import PolicyClientV2
>>> client = PolicyClientV2(sdc_url="https://secure.sysdig.com", token=SECURE_TOKEN)
>>> policy_json = sys.stdin.read()
>>> ok, res = client.update_policy_json(policy_json)
update_rule(id, details={}, description='', tags=[])[source]
Description

Update info associated with a rule

Arguments
  • id: The rule id

  • details: The rule description as a python dictionary.

  • description: A description of this rule. No newlines/formatting.

  • tags: The set of tags.

Success Return Value

A JSON object representing the rule.

class sdcclient.SdScanningClient(token='', sdc_url='https://secure.sysdig.com', ssl_verify=True, custom_headers=None)[source]
class RepositoryAlertTrigger
static cve_update(alert)
static new_image_analyzed(alert)
static scan_result_change_any(alert)
static scan_result_change_fail(alert)
class RuntimeAlertTrigger
static cve_update(alert)
static scan_result_change_any(alert)
static scan_result_change_fail(alert)
static unscanned_image(alert)
activate_subscription(subscription_type, subscription_key)[source]
Description

Activate a subscription

Arguments
  • subscription_type: Type of subscription. Valid options:
    • ‘tag_update’: Receive notification when new image is pushed

    • ‘policy_eval’: Receive notification when image policy status changes

    • ‘vuln_update’: Receive notification when vulnerabilities are added, removed or modified

    • ‘repo_update’: Receive notification when a repo is updated

  • subscription_key: Fully qualified name of tag to subscribe to. Eg. docker.io/library/alpine:latest

add_alert(name, description=None, scope='', triggers={'failed': True, 'unscanned': True}, enabled=False, notification_channels=[])[source]

Create a new alert Warning: add_alert is deprecated and will be removed soon, use add_runtime_alert or add_repository_alert from ScanningAlertsClientV1 instead.

Parameters
  • name (str) – The name of the alert.

  • description (str) – The descprition of the alert.

  • scope (str) – An AND-composed string of predicates that selects the scope in which the alert will be applied. (like: ‘host.domain = “example.com” and container.image != “alpine:latest”’)

  • tiggers (dict) – A dict {str: bool} indicating wich triggers should be enabled/disabled. (default: {‘failed’: True, ‘unscanned’: True})

  • enabled (bool) – Whether this alert should actually be applied.

  • notification_channels (list) – A list of notification channel ids.

Returns

A JSON object containing the alert description.

Deprecated since version `add_alert`: is deprecated and will be removed soon, use add_runtime_alert or add_repository_alert from ScanningAlertsClientV1 instead.

add_image(image, force=False, dockerfile=None, annotations={}, autosubscribe=True)[source]
Description

Add an image to the scanner

Arguments
  • image: Input image can be in the following formats: registry/repo:tag

  • dockerfile: The contents of the dockerfile as a str.

  • annotations: A dictionary of annotations {str: str}.

  • autosubscribe: Should active the subscription to this image?

Success Return Value

A JSON object representing the image that was added.

add_policy(name, rules, comment='', bundleid=None)[source]
Description

Create a new policy

Arguments
  • name: The name of the policy.

  • rules: A list of Anchore PolicyRule elements (while creating/updating a policy, new rule IDs will be created backend side)

  • comment: A human-readable description.

  • bundleid: Target bundle. If not specified, the currently active bundle will be used.

Success Return Value

A JSON object containing the policy description.

add_registry(registry, registry_user, registry_pass, insecure=False, registry_type='docker_v2', validate=True)[source]
Description

Add image registry

Arguments
  • registry: Full hostname/port of registry. Eg. myrepo.example.com:5000

  • registry_user: Username

  • registry_pass: Password

  • insecure: Allow connection to registry without SSL cert checks (ex: if registry uses a self-signed SSL certificate)

  • registry_type: Specify the registry type. ‘docker_v2’ and ‘awsecr’ are supported (default=’docker_v2’)

  • validate: If set to ‘False’ will not attempt to validate registry/creds on registry add

Success Return Value

A JSON object representing the registry.

add_repo(repo, autosubscribe=True, lookuptag=None)[source]
Description

Add a repository

Arguments
  • repo: Input repository can be in the following formats: registry/repo

  • autosubscribe: If unset, instruct the engine to disable subscriptions for any discovered tags.

  • lookuptag: Specify a tag to use for repo tag scan if ‘latest’ tag does not exist in the repo.

Success Return Value

A JSON object representing the repo.

add_repository_alert(name, registry, repository, tag, description='', triggers=None, notification_channels=None, enabled=True)

Create a new repository alert

Parameters
  • name (str) – The name of the alert.

  • registry (str) – Registry to alert (e.g. docker.io)

  • repository (str) – Repository to alert (e.g. sysdig/agent)

  • tag (str) – Tag to alert (e.g. latest)

  • description (str) – The description of the alert.

  • triggers (list) – A list of RepositoryAlertTrigger indicating which triggers should be enabled. (default: [ScanningAlertsClientV1.RuntimeAlertTrigger.new_image_analyzed])

  • notification_channels (list) – A list of notification channel ids.

  • enabled (bool) – Whether this alert should actually be applied. Defaults to true.

Returns

The created alert.

Examples

>>> client = ScanningAlertsClientV1(sdc_url=os.getenv("SDC_SECURE_URL", "https://secure.sysdig.com"),
>>>                                 token=os.getenv("SDC_SECURE_TOKEN"))
>>> ok, res = client.add_repository_alert(
>>>        name="A name",
>>>        registry="docker.io",
>>>        repository="sysdig/agent",
>>>        tag="latest",
>>>        description="A description",
>>>        triggers=[ScanningAlertsClientV1.RepositoryAlertTrigger.new_image_analyzed,
>>>                  ScanningAlertsClientV1.RepositoryAlertTrigger.scan_result_change_fail,
>>>                  ScanningAlertsClientV1.RepositoryAlertTrigger.cve_update]
>>>)
>>> if not ok:
>>>    print(f"error creating alert: {res}")
>>> alert_id = res["alertId"]
add_runtime_alert(name, description='', scope='', triggers=None, notification_channels=None, enabled=True)

Create a new runtime alert

Parameters
  • name (str) – The name of the alert.

  • description (str) – The description of the alert.

  • scope (str) – An AND-composed string of predicates that selects the scope in which the alert will be applied. (like: ‘host.domain = “example.com” and container.image != “alpine:latest”’)

  • triggers (list) – A list of RuntimeAlertTrigger indicating which triggers should be enabled. (default: [ScanningAlertsClientV1.RuntimeAlertTrigger.unscanned_image])

  • notification_channels (list) – A list of notification channel ids.

  • enabled (bool) – Whether this alert should actually be applied. Defaults to true.

Returns

The created alert.

Examples

>>> client = ScanningAlertsClientV1(sdc_url=os.getenv("SDC_SECURE_URL", "https://secure.sysdig.com"),
>>>                                 token=os.getenv("SDC_SECURE_TOKEN"))
>>> ok, res = client.add_runtime_alert(
>>>     name="A name",
>>>     description="A description",
>>>     scope="",
>>>     triggers=[ScanningAlertsClientV1.RuntimeAlertTrigger.unscanned_image,
>>>               ScanningAlertsClientV1.RuntimeAlertTrigger.scan_result_change_fail,
>>>               ScanningAlertsClientV1.RuntimeAlertTrigger.cve_update]
>>>)
>>> if not ok:
>>>    print(f"error creating alert: {res}")
>>> alert_id = res["alertId"]
add_vulnerability_exception(bundle, cve, note=None, expiration_date=None)[source]
add_vulnerability_exception_bundle(name, comment='')[source]
check_image_evaluation(image, show_history=False, detail=False, tag=None, policy=None)[source]
Description

Check the latest policy evaluation for an image

Arguments
  • image: Input image can be in the following formats: registry/repo:tag

  • show_history: Show all previous policy evaluations

  • detail: Show detailed policy evaluation report

  • tag: Specify which TAG is evaluated for a given image ID or Image Digest

  • policy: Specify which POLICY to use for evaluate (defaults currently active policy)

Success Return Value

A JSON object representing the evaluation status.

clear_agents_config()
create_access_key()
Description

Create a new access key for Sysdig Monitor/Secure

Reslut

The access keys object

create_email_notification_channel(channel_name, email_recipients)
create_notification_channel(channel)
create_sysdig_capture(hostname, capture_name, duration, capture_filter='', folder='/')
Description

Create a new sysdig capture. The capture will be immediately started.

Arguments
  • hostname: the hostname of the instrumented host where the capture will be taken.

  • capture_name: the name of the capture.

  • duration: the duration of the capture, in seconds.

  • capture_filter: a sysdig filter expression.

  • folder: directory in the S3 bucket where the capture will be saved.

Success Return Value

A dictionary showing the details of the new capture.

Example

examples/create_sysdig_capture.py

create_team(name, memberships=None, filter='', description='', show='host', theme='#7BB0B2', perm_capture=False, perm_custom_events=False, perm_aws_data=False, perm_rapid_response=False)
Description

Creates a new team

Arguments
  • name: the name of the team to create.

  • memberships: dictionary of (user-name, team-role) pairs that should describe new memberships of the team.

  • filter: the scope that this team is able to access within Sysdig Monitor.

  • description: describes the team that will be created.

  • show: possible values are host, container.

  • theme: the color theme that Sysdig Monitor will use when displaying the team.

  • perm_capture: if True, this team will be allowed to take sysdig captures.

  • perm_custom_events: if True, this team will be allowed to view all custom events from every user and agent.

  • perm_aws_data: if True, this team will have access to all AWS metrics and tags, regardless of the team’s scope.

  • perm_rapid_response: if True, this team will have access rapid response feature.

Success Return Value

The newly created team.

Example

examples/user_team_mgmt.py

create_user(user_email, first_name=None, last_name=None, password=None)

Provisions a new user to use Sysdig without sending an email notification. If password is not set through this request a random one is generated for the user which requires them to reset password on first login.

Parameters
  • user_email (str) – Email of the user to provision.

  • first_name (str) – First name of the user to provision. Can be null.

  • last_name (str) – Last name of the user to provision. Can be null.

  • password (str) – Default password for the user to provision. If this is not set, a random one is generated.

Returns

The provisioned user information.

create_user_invite(user_email, first_name=None, last_name=None, system_role=None)
Description

Invites a new user to use Sysdig Monitor. This should result in an email notification to the specified address.

Arguments
  • user_email: the email address of the user that will be invited to use Sysdig Monitor

  • first_name: the first name of the user being invited

  • last_name: the last name of the user being invited

  • system_role: system-wide privilege level for this user regardless of team. specify ‘ROLE_CUSTOMER’ to create an Admin. if not specified, default is a non-Admin (‘ROLE_USER’).

Success Return Value

The newly created user.

Examples
deactivate_subscription(subscription_type, subscription_key)[source]
Description

Deactivate a subscription

Arguments
  • subscription_type: Type of subscription. Valid options:
    • ‘tag_update’: Receive notification when new image is pushed

    • ‘policy_eval’: Receive notification when image policy status changes

    • ‘vuln_update’: Receive notification when vulnerabilities are added, removed or modified

    • ‘repo_update’: Receive notification when a repo is updated

  • subscription_key: Fully qualified name of tag to subscribe to. Eg. docker.io/library/alpine:latest

delete_alert(policyid)

Delete the alert with the given id

Parameters

policyid – Unique identifier associated with this alert.

Examples

>>> client = ScanningAlertsClientV1(sdc_url=os.getenv("SDC_SECURE_URL", "https://secure.sysdig.com"),
>>>                                 token=os.getenv("SDC_SECURE_TOKEN"))
>>> client.delete_alert(alert_id)
delete_image(image, force=False)[source]
Description

Delete image from the scanner.

Arguments
  • None

delete_notification_channel(channel)
delete_policy(policyid, bundleid=None)[source]
Description

Delete the policy with the given id in the targeted policy Bundle

Arguments
  • policyid: Unique identifier associated with this policy.

  • policy_description: A dictionary with the policy description.

delete_registry(registry)[source]
Description

Delete an existing image registry

Arguments
  • registry: Full hostname/port of registry. Eg. myrepo.example.com:5000

delete_repo(repo)[source]
Description

Delete a repository from the watch list (does not delete already analyzed images)

Arguments
  • repo: Input repository can be in the following formats: registry/repo

delete_subscription(subscription_type, subscription_key)[source]
Description

Delete a subscription

Arguments
  • subscription_type: Type of subscription. Valid options:
    • ‘tag_update’: Receive notification when new image is pushed

    • ‘policy_eval’: Receive notification when image policy status changes

    • ‘vuln_update’: Receive notification when vulnerabilities are added, removed or modified

    • ‘repo_update’: Receive notification when a repo is updated

  • subscription_key: Fully qualified name of tag to subscribe to. Eg. docker.io/library/alpine:latest

delete_sysdig_capture(capture_id)

Removes an existing Sysdig Capture from Monitor

Parameters

capture_id – ID of the capture to remove

Returns: A touple of (bool, error) where the first value is false if there’s an error and the second value is the error.

delete_team(name)
Description

Deletes a team from Sysdig Monitor.

Arguments
  • name: the name of the team that will be deleted from Sysdig Monitor

Example

examples/user_team_mgmt.py

delete_user(user_email)
Description

Deletes a user from Sysdig Monitor.

Arguments
  • user_email: the email address of the user that will be deleted from Sysdig Monitor

Example

examples/user_team_mgmt.py

delete_vulnerability_exception(bundle, id)[source]
delete_vulnerability_exception_bundle(id)[source]
disable_access_key(access_key)
Description

Disable an existing access key

Arguments
  • access_key: the access key to be disabled

Reslut

The access keys object

download_cve_report_csv(vuln_type='os', scope_type='static')[source]

Downloads a CVE report in CSV format

Parameters
  • vuln_type (str) – Vulnerability type, can be either “os” or “non-os”.

  • scope_type (str) – Scope type. Can be either “static” or “runtime”.

Returns

A tuple of (bool, str). The first parameter, if true, means that the result is correct, while if false, means that there’s been an error. The second parameter will hold the response of the API call.

download_sysdig_capture(capture_id)
Description

Download a sysdig capture by id.

Arguments
  • capture_id: the capture id to download.

Success Return Value

The bytes of the scap

edit_team(name, memberships=None, filter=None, description=None, show=None, theme=None, perm_capture=None, perm_custom_events=None, perm_aws_data=None, perm_rapid_response=False)
Description

Edits an existing team. All arguments are optional. Team settings for any arguments unspecified will remain at their current settings.

Arguments
  • name: the name of the team to edit.

  • memberships: dictionary of (user-name, team-role) pairs that should describe new memberships of the team.

  • filter: the scope that this team is able to access within Sysdig Monitor.

  • description: describes the team that will be created.

  • show: possible values are host, container.

  • theme: the color theme that Sysdig Monitor will use when displaying the team.

  • perm_capture: if True, this team will be allowed to take sysdig captures.

  • perm_custom_events: if True, this team will be allowed to view all custom events from every user and agent.

  • perm_aws_data: if True, this team will have access to all AWS metrics and tags, regardless of the team’s scope.

  • perm_rapid_response: if True, this team will have access rapid response feature.

Success Return Value

The edited team.

Example

examples/user_team_mgmt.py

edit_user(user_email, firstName=None, lastName=None, systemRole=None)
enable_access_key(access_key)
Description

Enable an existing access key

Arguments
  • access_key: the access key to be enabled

Reslut

The access keys object

get_agents_config()
get_alert(alertid)

Retrieve the scanning alert with the given id

Parameters

alertid – Unique identifier associated with this alert.

Returns

A JSON object containing the alert description.

Examples

>>> client = ScanningAlertsClientV1(sdc_url=os.getenv("SDC_SECURE_URL", "https://secure.sysdig.com"),
>>>                                 token=os.getenv("SDC_SECURE_TOKEN"))
>>> ok, res = client.get_alert(alert_id)
>>> if not ok:
>>>     print(f"error retrieving alert {alert_id}: {res}")
>>> alert = res
get_anchore_users_account()[source]
Description

Get the anchore user account.

Arguments
  • None

Success Return Value

A JSON object containing user account information.

get_connected_agents()
Description

Return the agents currently connected to Sysdig Monitor for the current user.

Success Return Value

A list of the agents with all their attributes.

get_data(metrics, start_ts, end_ts=0, sampling_s=0, filter='', datasource_type='host', paging=None)
Description

Export metric data (both time-series and table-based).

Arguments
  • metrics: a list of dictionaries, specifying the metrics and grouping keys that the query will return. A metric is any of the entries that can be found in the Metrics section of the Explore page in Sysdig Monitor. Metric entries require an aggregations section specifying how to aggregate the metric across time and containers/hosts. A grouping key is any of the entries that can be found in the Show or Segment By sections of the Explore page in Sysdig Monitor. These entries are used to apply single or hierarchical segmentation to the returned data and don’t require the aggregations section. Refer to the Example link below for ready-to-use code snippets.

  • start_ts: the UTC time (in seconds) of the beginning of the data window. A negative value can be optionally used to indicate a relative time in the past from now. For example, -3600 means “one hour ago”.

  • end_ts: the UTC time (in seconds) of the end of the data window, or 0 to indicate “now”. A negative value can also be optionally used to indicate a relative time in the past from now. For example, -3600 means “one hour ago”.

  • sampling_s: the duration of the samples that will be returned. 0 means that the whole data will be returned as a single sample.

  • filter: a boolean expression combining Sysdig Monitor segmentation criteria that defines what the query will be applied to. For example: kubernetes.namespace.name=’production’ and container.image=’nginx’.

  • datasource_type: specify the metric source for the request, can be container or host. Most metrics, for example cpu.used.percent or memory.bytes.used, are reported by both hosts and containers. By default, host metrics are used, but if the request contains a container-specific grouping key in the metric list/filter (e.g. container.name), then the container source is used. In cases where grouping keys are missing or apply to both hosts and containers (e.g. tag.Name), datasource_type can be explicitly set to avoid any ambiguity and allow the user to select precisely what kind of data should be used for the request. examples/get_data_datasource.py contains a few examples that should clarify the use of this argument.

  • paging: if segmentation of the query generates values for several different entities (e.g. containers/hosts), this parameter specifies which to include in the returned result. It’s specified as a dictionary of inclusive values for from and to with the default being { "from": 0, "to": 9 }, which will return values for the “top 10” entities. The meaning of “top” is query-dependent, based on points having been sorted via the specified group aggregation, with the results sorted in ascending order if the group aggregation is min or none, and descending order otherwise.

Success Return Value

A dictionary with the requested data. Data is organized in a list of time samples, each of which includes a UTC timestamp and a list of values, whose content and order reflect what was specified in the metrics argument.

Examples
get_data_retention_info()
Description

Return the list of data retention intervals, with beginning and end UTC time for each of them. Sysdig Monitor performs rollups of the data it stores. This means that data is stored at different time granularities depending on how far back in time it is. This call can be used to know what precision you can expect before you make a call to get_data().

Success Return Value

A dictionary containing the list of available sampling intervals.

Example

examples/print_data_retention_info.py

get_image(image, show_history=False)[source]
Description

Find the image with the tag <image> and return its json description

Arguments
  • image: Input image can be in the following formats: registry/repo:tag

Success Return Value

A JSON object representing the image.

get_image_scan_result_by_id(image_id, full_tag_name, detail)[source]
Description

Get the anchore image scan result for an image id.

Arguments
  • image_id: Docker image id of the image whose scan result is to be fetched.

  • full_tag_name: The complete tag name of the image for e.g. docker.io/alpine:3.10.

  • detail: Boolean to indicate whether full scan result API is needed.

Success Return Value

A JSON object containing pass/fail status of image scan policy.

get_image_scanning_results(image_name, policy_id=None)[source]
Parameters
  • image_name (str) – Image name to retrieve the scanning results from

  • policy_id (str) – Policy ID to check against. If not specified, will check against all policies.

Returns

A tuple of (bool, str). The first parameter, if true, means that the result is correct, while if false, means that there’s been an error. The second parameter will hold the response of the API call.

get_latest_pdf_report_by_digest(image_digest, full_tag=None)[source]
Description

Get the latest pdf report of one image digest

Arguments
  • image_digest: Input image digest should be in the following formats: sha256:134dhgfd65765

  • tag: Specify which FULLTAG is evaluated for a given Image Digest: docker.io/alpine:latest

Success Return Value

The pdf content

get_n_connected_agents()
Description

Return the number of agents currently connected to Sysdig Monitor for the current user.

Success Return Value

An integer number.

get_notification_channel(id)
get_notification_ids(channels=None)
Description

Get an array of all configured Notification Channel IDs, or a filtered subset of them.

Arguments
  • channels: an optional array of dictionaries to limit the set of Notification Channel IDs returned. If not specified, IDs for all configured Notification Channels are returned. Each dictionary contains a type field that can be one of the available types of Notification Channel (EMAIL, SNS, PAGER_DUTY, SLACK, OPSGENIE, VICTOROPS, WEBHOOK) as well as additional elements specific to each channel type.

Success Return Value

An array of Notification Channel IDs (integers).

Examples
get_pdf_report(image, tag=None, date=None)[source]
Description

Get a pdf report of one image

Arguments
  • image: Input image can be in the following formats: registry/repo:tag

  • tag: Specify which TAG is evaluated for a given image ID or Image Digest

  • date: date for the report of interest, the format is ‘YYYY-MM-DDTHH:MM:SSZ’,

    if not provided the latest report will be returned

Success Return Value

The pdf content

get_policy(policyid, bundleid=None)[source]
Description

Retrieve the policy with the given id in the targeted policy bundle

Arguments
  • policyid: Unique identifier associated with this policy.

  • bundleid: Target bundle. If not specified, the currently active bundle will be used.

Success Return Value

A JSON object containing the policy description.

get_registry(registry)[source]
Description

Find the registry and return its json description

Arguments
  • registry: Full hostname/port of registry. Eg. myrepo.example.com:5000

Success Return Value

A JSON object representing the registry.

get_repo(repo)[source]
Description

Get a repository

Arguments
  • repo: Input repository can be in the following formats: registry/repo

Success Return Value

A JSON object representing the registry.

get_subscriptions(subscription_type=None, subscription_key=None)[source]
Description

Get the list of subscriptions

Arguments
  • subscription_type: Type of subscription. Valid options:
    • ‘tag_update’: Receive notification when new image is pushed

    • ‘policy_eval’: Receive notification when image policy status changes

    • ‘vuln_update’: Receive notification when vulnerabilities are added, removed or modified

    • ‘repo_update’: Receive notification when a repo is updated

  • subscription_key: Fully qualified name of tag to subscribe to. Eg. docker.io/library/alpine:latest

get_sysdig_captures(from_sec=None, to_sec=None, scope_filter=None)
Description

Returns the list of sysdig captures for the user.

Arguments
  • from_sec: the start of the timerange for which to get the captures

  • end_sec: the end of the timerange for which to get the captures

  • scope_filter: this is a SysdigMonitor-like filter (e.g ‘container.image=ubuntu’). When provided, events are filtered by their scope, so only a subset will be returned (e.g. ‘container.image=ubuntu’ will provide only events that have happened on an ubuntu container).

Success Return Value

A dictionary containing the list of captures.

Example

examples/list_sysdig_captures.py

get_team(name)
Description

Return the team with the specified team name, if it is present.

Arguments
  • name: the name of the team to return

Success Return Value

The requested team.

Example

examples/user_team_mgmt.py

get_team_ids(teams)
get_teams(team_filter='')
Description

Return the set of teams that match the filter specified. The team_filter should be a substring of the names of the teams to be returned.

Arguments
  • team_filter: the team filter to match when returning the list of teams

Success Return Value

The teams that match the filter.

get_topology_map(grouping_hierarchy, time_window_s, sampling_time_s)
get_user(user_email)
get_user_api_token(username, teamname)
get_user_ids(users)
get_user_info()
Description

Get details about the current user.

Success Return Value

A dictionary containing information about the user, for example its email and the maximum number of agents it can install.

Example

examples/print_user_info.py

get_user_token()
Description

Return the API token of the current user.

Success Return Value

A string containing the user token.

get_users()
Description

Return a list containing details about all users in the Sysdig Monitor environment. The API token must have Admin rights for this to succeed.

Success Return Value

A list user objects

get_vulnerability_details(id)[source]
get_vulnerability_exception_bundle(bundle)[source]
import_image(infile, image_id, digest_id, image_name, sync=False)[source]
Description

Import an image archive

Arguments
  • infile: An image archive file

  • sync: Whether the import should be synchronous or asynchronous

Success Return Value

If synchronous, A JSON object representing the image that was imported.

lasterr = None
list_access_keys()
Description

List all the access keys enabled and disabled for this instance of Sysdig Monitor/Secure

Reslut

A list of access keys objects

Example

examples/list_access_keys.py

list_alerts(limit=None, cursor=None)

List the current set of scanning alerts. :param limit: Maximum number of alerts in the response. :type limit: int :param cursor: An opaque string representing the current position in the list of alerts. It’s provided in the ‘responseMetadata’ of the list_alerts response.

Returns

A JSON containing the list of alerts in the ‘alerts’ field, and the current cursor position in the ‘responseMetadata’ field.

Examples

>>> client = ScanningAlertsClientV1(sdc_url=os.getenv("SDC_SECURE_URL", "https://secure.sysdig.com"),
>>>                                 token=os.getenv("SDC_SECURE_TOKEN"))
>>> ok, res =client.list_alerts()
>>> if not ok:
>>>     print(f"error listing alerts: {res}")
>>> for alert in res["alerts"]:
>>>     print(alert["alertId"])
>>>
>>> # Load more alerts
>>> if res["responseMetadata"] is not None:
>>>     ok, res = client.list_alerts(cursor=res["responseMetadata"]["next_cursor"])
list_image_tags()[source]

Lists the current set of image tags in the scanner.

Returns: A JSON object containing all the image tags.

list_images()[source]
Description

List the current set of images in the scanner.

Arguments
  • None

Success Return Value

A JSON object containing all the images.

list_memberships(team)
Description

List all memberships for specified team.

Arguments
  • team: the name of the team for which we want to see memberships

Result

Dictionary of (user-name, team-role) pairs that should describe memberships of the team.

Example

examples/user_team_mgmt_extended.py

list_notification_channels()
Description

List all configured Notification Channels

Arguments

none

Success Return Value

A JSON representation of all the notification channels

list_policies(bundleid=None)[source]
Description

List the current set of scanning policies.

Arguments
  • bundleid: Target bundle. If not specified, the currently active bundle will be used.

Success Return Value

A JSON object containing the list of policies.

list_policy_bundles(detail=False)[source]
list_registry()[source]
Description

List all current image registries

Arguments
  • None

Success Return Value

A JSON object representing the list of registries.

list_repos()[source]
Description

List added repositories

Arguments
  • None

Success Return Value

A JSON object representing the list of repositories.

list_runtime(scope='', skip_policy_evaluation=True, start_time=None, end_time=None)[source]
Description

List runtime containers

Arguments
  • scope: An AND-composed string of predicates that selects the scope in which the alert will be applied. (like: ‘host.domain = “example.com” and container.image != “alpine:latest”’)

  • skip_policy_evaluation: If true, no policy evaluations will be triggered for the images.

  • start_time: Start of the time range (integer of unix time).

  • end_time: End of the time range (integer of unix time).

Success Return Value

A JSON object representing the list of runtime containers.

list_subscription()[source]
Description

List all subscriptions

Arguments
  • None

Success Return Value

A JSON object representing the list of subscriptions.

list_vulnerability_exception_bundles()[source]
list_whitelisted_cves()[source]
Description

List the whitelisted global CVEs.

Arguments
  • None

Success Return Value

A JSON object containing all the whitelisted CVEs.

Deprecated

This method has been deprecated since the API has changed. Use the list_vulnerability_exception_bundles and get_vulnerability_exception_bundle methods.

poll_sysdig_capture(capture)
Description

Fetch the updated state of a sysdig capture. Can be used to poll the status of a capture that has been previously created and started with create_sysdig_capture().

Arguments
  • capture: the capture object as returned by get_sysdig_captures() or create_sysdig_capture().

Success Return Value

A dictionary showing the updated details of the capture. Use the status field to check the progress of a capture.

Example

examples/create_sysdig_capture.py

query_image_content(image, content_type='')[source]
Description

Find the image with the tag <image> and return its content.

Arguments
  • image: Input image can be in the following formats: registry/repo:tag

  • content_type: The content type can be one of the following types:
    • os: Operating System Packages

    • files: Files

    • npm: Node.JS NPM Module

    • gem: Ruby GEM

    • python: Python modules

    • java: Java packages

Success Return Value

A JSON object representing the image content.

query_image_metadata(image, metadata_type='')[source]
Description

Find the image with the tag <image> and return its metadata.

Arguments
  • image: Input image can be in the following formats: registry/repo:tag

  • metadata_type: The metadata type can be one of the types returned by running without a type specified

Success Return Value

A JSON object representing the image metadata.

query_image_vuln(image, vuln_type='', vendor_only=True)[source]
Description

Find the image with the tag <image> and return its vulnerabilities.

Arguments
  • image: Input image can be in the following formats: registry/repo:tag

  • vuln_type: Vulnerability type can be one of the following types:
    • os: CVE/distro vulnerabilities against operating system packages

Success Return Value

A JSON object representing the image vulnerabilities.

query_images_by_package(name, version=None, package_type=None)[source]
Description

Search system for images with the given package installed

Arguments
  • name: Search for images with this package name (e.g. sed)

  • version: Filter results to only packages with given version (e.g. 4.4-1)

  • package-type: Filter results to only packages of given type (e.g. dpkg)

Success Return Value

A JSON object representing the images.

query_images_by_vulnerability(vulnerability_id, namespace=None, package=None, severity=None, vendor_only=True)[source]
Description

Search system for images with the given vulnerability ID present

Arguments
  • vulnerability_id: Search for images vulnerable to this vulnerability ID (e.g. CVE-1999-0001)

  • namespace: Filter results to images with vulnerable packages in the given namespace (e.g. debian:9)

  • package: Filter results to images with the given vulnerable package name (e.g. sed)

  • severity: Filter results to images with the given vulnerability severity (e.g. Medium)

  • vendor_only: Only show images with vulnerabilities explicitly deemed applicable by upstream OS vendor, if present

Success Return Value

A JSON object representing the images.

remove_memberships(team, users)
Description

Remove user memberships from specified team.

Arguments
  • team: the name of the team from which user memberships are removed

  • users: list of usernames which should be removed from team

Example

examples/user_team_mgmt_extended.py

save_memberships(team, memberships)
Description

Create new user team memberships or update existing ones.

Arguments
  • team: the name of the team for which we are creating new memberships

  • memberships: dictionary of (user-name, team-role) pairs that should describe new memberships

Example

examples/user_team_mgmt_extended.py

set_agents_config(config)
unwatch_repo(repo)[source]
Description

Instruct engine to stop automatically watching the repo for image updates

Arguments
  • repo: Input repository can be in the following formats: registry/repo

update_alert(alertid, alert_description)[source]

Update the alert with the given id. Warning: update_alert is deprecated and will be removed soon, use update_runtime_alert or update_repository_alert from ScanningAlertsClientV1 instead.

Parameters
  • alertid (str) – Unique identifier associated with this alert.

  • alert_description (str) – A dictionary with the alert description.

Returns

A JSON object containing the alert description.

Deprecated since version `update_alert`: is deprecated and will be removed soon, use update_runtime_alert or update_repository_alert from ScanningAlertsClientV1 instead.

update_notification_channel(channel)
update_policy(policyid, policy_description)[source]
Description

Update the policy with the given id

Arguments
  • policyid: Unique identifier associated with this policy.

  • policy_description: A dictionary with the policy description.

Success Return Value

A JSON object containing the policy description.

update_registry(registry, registry_user, registry_pass, insecure=False, registry_type='docker_v2', validate=True)[source]
Description

Update an existing image registry.

Arguments
  • registry: Full hostname/port of registry. Eg. myrepo.example.com:5000

  • registry_user: Username

  • registry_pass: Password

  • insecure: Allow connection to registry without SSL cert checks (ex: if registry uses a self-signed SSL certificate)

  • registry_type: Specify the registry type. ‘docker_v2’ and ‘awsecr’ are supported (default=’docker_v2’)

  • validate: If set to ‘False’ will not attempt to validate registry/creds on registry add

Success Return Value

A JSON object representing the registry.

update_repository_alert(id, name=None, registry=None, repository=None, tag=None, description=None, triggers=None, notification_channels=None, enabled=None)

Updates a repository alert. Fields that are not specified, will not be modified.

Parameters
  • id (str) – Alert ID.

  • name (str) – The name of the alert.

  • registry (str) – Registry to alert (e.g. docker.io)

  • repository (str) – Repository to alert (e.g. sysdig/agent)

  • tag (str) – Tag to alert (e.g. latest)

  • description (str) – The description of the alert.

  • triggers (list) – A list of RepositoryAlertTrigger indicating which triggers should be enabled. (default: [ScanningAlertsClientV1.RuntimeAlertTrigger.unscanned_image])

  • notification_channels (list) – A list of notification channel ids.

  • enabled (bool) – Whether this alert should actually be applied. Defaults to true.

Returns

The updated alert.

Examples

>>> client = ScanningAlertsClientV1(sdc_url=os.getenv("SDC_SECURE_URL", "https://secure.sysdig.com"),
>>>                                 token=os.getenv("SDC_SECURE_TOKEN"))
>>> ok, res = client.update_repository_alert(
>>>     id=alert_id,
>>>     name="An updated name",
>>>     registry="updated_registry",
>>>     repository="updated_repository",
>>>     tag="v1",
>>>     description="An updated description",
>>>     triggers=[ScanningAlertsClientV1.RepositoryAlertTrigger.scan_result_change_fail]
>>> )
>>> if not ok:
>>>    print(f"error updating alert: {res}")
>>> alert_id = res["alertId"]
update_runtime_alert(id, name=None, description=None, scope=None, triggers=None, notification_channels=None, enabled=None)

Updates a runtime alert. Fields that are not specified, will not be modified.

Parameters
  • id (str) – Alert ID.

  • name (str) – The name of the alert.

  • description (str) – The description of the alert.

  • scope (str) – An AND-composed string of predicates that selects the scope in which the alert will be applied. (like: ‘host.domain = “example.com” and container.image != “alpine:latest”’)

  • triggers (list) – A list of RuntimeAlertTrigger indicating which triggers should be enabled. (default: [ScanningAlertsClientV1.RuntimeAlertTrigger.unscanned_image])

  • notification_channels (list) – A list of notification channel ids.

  • enabled (bool) – Whether this alert should actually be applied. Defaults to true.

Returns

The updated alert.

Examples

>>> client = ScanningAlertsClientV1(sdc_url=os.getenv("SDC_SECURE_URL", "https://secure.sysdig.com"),
>>>                                 token=os.getenv("SDC_SECURE_TOKEN"))
>>> ok, res = client.update_runtime_alert(
>>>     id=alert_id,
>>>     name="An updated name",
>>>     description="An updated description",
>>>     scope="agent.id = 'foo'",
>>>     triggers=[ScanningAlertsClientV1.RuntimeAlertTrigger.scan_result_change_fail]
>>> )
>>> if not ok:
>>>    print(f"error updating alert: {res}")
>>> alert_id = res["alertId"]
update_vulnerability_exception(bundle, id, cve, enabled, note, expiration_date)[source]
watch_repo(repo)[source]
Description

Instruct engine to start automatically watching the repo for image updates

Arguments
  • repo: Input repository can be in the following formats: registry/repo