Tenable.sc¶
-
class
TenableSC
(host, access_key=None, secret_key=None, username=None, password=None, port=443, ssl_verify=False, cert=None, adapter=None, scheme='https', retries=None, backoff=None, ua_identity=None, session=None, proxies=None, timeout=None, vendor=None, product=None, build=None, base_path='rest')[source]¶ TenableSC API Wrapper The Tenable.sc object is the primary interaction point for users to interface with Tenable.sc via the pyTenable library. All of the API endpoint classes that have been written will be grafted onto this class.
- Parameters
host (str) – The address of the Tenable.sc instance to connect to.
access_key (str, optional) – The API access key to use for sessionless authentication.
adapter (requests.Adaptor, optional) – If a requests session adaptor is needed to ensure connectivity to the Tenable.sc host, one can be provided here.
backoff (float, optional) – If a 429 response is returned, how much do we want to backoff if the response didn’t send a Retry-After header. The default backoff is
1
second.cert (tuple, optional) – The client-side SSL certificate to use for authentication. This format could be either a tuple or a string pointing to the certificate. For more details, please refer to the Requests Client-Side Certificates documentation.
password (str, optional) – The password to use for session authentication.
port (int, optional) – The port number to connect to on the specified host. The default is port
443
.retries (int, optional) – The number of retries to make before failing a request. The default is
5
.scheme (str, optional) – What HTTP scheme should be used for URI path construction. The default is
https
.secret_key (str, optional) – The API secret key to use for sessionless authentication.
session (requests.Session, optional) – If a requests Session is provided, the provided session will be used instead of constructing one during initialization.
ssl_verify (bool, optional) – Should the SSL certificate on the Tenable.sc instance be verified? Default is False.
username (str, optional) – The username to use for session authentication.
timeout (int, optional) – The connection timeout parameter informing the library how long to wait in seconds for a stalled response before terminating the connection. If unspecified, the default is 300 seconds.
Examples
A direct connection to Tenable.sc:
>>> from tenable.sc import TenableSC >>> sc = TenableSC('sc.company.tld')
A connection to Tenable.sc using SSL certificates:
>>> sc = TenableSC('sc.company.tld', ... cert=('/path/client.cert', '/path/client.key'))
Using an adaptor to use a passworded certificate (via the immensely useful requests_pkcs12 adaptor):
>>> from requests_pkcs12 import Pkcs12Adapter >>> adapter = Pkcs12Adapter( ... pkcs12_filename='certificate.p12', ... pkcs12_password='omgwtfbbq!') >>> sc = TenableSC('sc.company.tld', adapter=adapter)
Using API Keys to communicate to Tenable.sc:
>>> sc = TenableSC('sc.compant.tld', access_key='key', secret_key='key')
Using context management to handle
For more information, please See Tenable’s SC API documentation and the SC API Best Practices Guide.
-
login
(username=None, password=None, access_key=None, secret_key=None)[source]¶ Logs the user into Tenable.sc
- Parameters
username (str, optional) – Username
password (str, optional) – Password
access_key (str, optional) – API Access Key
secret_key (str, optional) – API Secret Key
- Returns
None
Examples
Using a username && password:
>>> sc = TenableSC('127.0.0.1', port=8443) >>> sc.login('username', 'password')
Using API Keys:
>>> sc = TenableSC('127.0.0.1', port=8443) >>> sc.login(access_key='ACCESSKEY', secret_key='SECRETKEY')
alerts¶
The following methods allow for interaction into the Tenable.sc Alert API.
Methods available on sc.alerts
:
-
class
AlertAPI
(api)[source]¶ -
create
(*filters, **kw)[source]¶ Creates a new alert. The fields below are explicitly checked, however any additional parameters mentioned in the API docs can be passed to the document constructor.
- Sc-api:’alert
create <Alert.html#alert_POST>`
- Parameters
*filters (tuple) – A filter expression. Refer to the detailed description within the analysis endpoint documentation for more details on how to formulate filter expressions.
data_type (str) – The type of filters being used. Must be of type
lce
,ticket
,user
, orvuln
. If no data-type is specified, then the default ofvuln
will be set.name (str) – The name of the alert.
description (str, optional) – A description for the alert.
trigger (tuple) – A tuple in the filter-tuple format detailing what would constitute a trigger. For example:
('sumip', '=', '1000')
.always_exec_on_trigger (bool, optional) – Should the trigger always execute when the trigger fires, or only execute when the returned data changes? Default is
False
.schedule (dict, optional) – This is the schedule dictionary that will inform Tenable.sc how often to run the alert. If left unspecified then we will default to
{'type': 'never'}
. For more information refer to Schedule Dictionariesaction (list) –
The action(s) that will be performed when the alert trigger fires. Each action is a dictionary detailing what type of action to take, and the details surrounding that action. The supported type of actions are
email
,notifications
,report
,scan
,syslog
, andticket
. The following examples lay out each type of action as an example:Email action type:
{'type': 'email', 'subject': 'Example Email Subject', 'message': 'Example Email Body' 'addresses': 'user1@company.com\nuser2@company.com', 'users': [{'id': 1}, {'id': 2}], 'includeResults': 'true'}
Notification action type:
{'type': 'notification', 'message': 'Example notification', 'users': [{'id': 1}, {'id': 2}]}
Report action type:
{'type': 'report', 'report': {'id': 1}}
Scan action type:
{'type': 'scan', 'scan': {'id': 1}}
Syslog action type:
{'type': 'syslog', 'host': '127.0.0.1', 'port': '514', 'message': 'Example Syslog Message', 'severity': 'Critical'}
Ticket action type:
{'type': 'ticket', 'assignee': {'id': 1}, 'name': 'Example Ticket Name', 'description': 'Example Ticket Description', 'notes': 'Example Ticket Notes'}
- Returns
The alert resource created.
- Return type
dict
Examples
>>> sc.alerts.create( ... ('severity', '=', '3,4'), ... ('exploitAvailable', '=', 'true'), ... trigger=('sumip', '>=', '100'), ... name='Too many High or Critical and Exploitable', ... action=[{ ... 'type': 'notification', ... 'message': 'Too many High or Crit Exploitable Vulns', ... 'users': [{'id': 1}] ... }])
-
delete
(id)[source]¶ Deletes the specified alert.
- Parameters
id (int) – The alert identifier.
- Returns
The response code of the action.
- Return type
str
Examples
>>> sc.alerts.delete(1)
-
details
(id, fields=None)[source]¶ Returns the details for a specific alert.
- Parameters
id (int) – The identifier for the alert.
fields (list, optional) – A list of attributes to return.
- Returns
The alert resource record.
- Return type
dict
Examples
>>> alert = sc.alerts.detail(1) >>> pprint(alert)
-
edit
(id, *filters, **kw)[source]¶ Updates an existing alert. All fields are optional and will overwrite the existing value.
- Parameters
if (int) – The alert identifier.
*filters (tuple) – A filter expression. Refer to the detailed description within the analysis endpoint documentation for more details on how to formulate filter expressions.
data_type (str) – The type of filters being used. Must be of type
lce
,ticket
,user
, orvuln
. If no data-type is specified, then the default ofvuln
will be set.name (str, optional) – The name of the alert.
description (str, optional) – A description for the alert.
trigger (tuple, optional) – A tuple in the filter-tuple format detailing what would constitute a trigger. For example:
('sumip', '=', '1000')
.always_exec_on_trigger (bool, optional) – Should the trigger always execute when the trigger fires, or only execute when the returned data changes? Default is
False
.schedule (dict, optional) – This is the schedule dictionary that will inform Tenable.sc how often to run the alert. If left unspecified then we will default to
{'type': 'never'}
. For more information refer to Schedule Dictionariesaction (list) – The action(s) that will be performed when the alert trigger fires. Each action is a dictionary detailing what type of action to take, and the details surrounding that action.
- Returns
The modified alert resource.
- Return type
dict
Examples
>>> sc.alerts.update(1, name='New Alert Name')
-
execute
(id)[source]¶ Executes the specified alert.
- Parameters
id (int) – The alert identifier.
- Returns
The alert resource.
- Return type
dict
-
accept_risks¶
The following methods allow for interaction into the Tenable.sc Accept Risk API.
Methods available on sc.accept_risks
:
-
class
AcceptRiskAPI
(api)[source]¶ -
apply
(id, repo)[source]¶ Applies the accept risk rule for either all repositories, or the repository specified.
- Parameters
id (int) – The identifier for the accept risk rule.
repo (int, optional) – A specific repository to apply the rule to. The default if not specified is all repositories (
0
).
- Returns
Empty string response from the API.
- Return type
str
Examples
>>> sc.accept_risks.apply(1)
-
create
(plugin_id, repos, **kw)[source]¶ Creates a new accept risk rule. Either ips, uuids, or asset_list must be specified.
- Parameters
plugin_id (int) – The plugin to apply the accept risk rule to.
repos (list) – The list of repositories to apply this accept risk rule to.
asset_list (int, optional) – The asset list id to apply the accept risk rule to. Please note that
asset_list
,ips
, anduuids
are mutually exclusive.comments (str, optional) – The comment associated to the accept risk rule.
expires (int, optional) – When should the rule expire? if no expiration is set, the rule will never expire.
ips (list, optional) – A list of IPs to apply the accept risk rule to. Please note that
asset_list
,ips
, anduuids
are mutually exclusive.port (int, optional) – The port to restrict this accept risk rule to. The default is unrestricted.
protocol (int, optional) – The protocol to restrict the accept risk rule to. The default is unrestricted.
uuids (list, optional) – The agent uuids to apply the accept risk rule to. Please note that
asset_list
,ips
, anduuids
are mutually exclusive.
- Returns
The newly created accept risk rule definition.
- Return type
dict
Examples
Create a rule to accept 97737 on 2 IPs for 90 days.
>>> rule = sc.accept_risks.create(97737, [1], ... ips=['192.168.0.101', '192.168.0.102'], expires=90)
Create a rule to accept 97737 on all IPs on repository 1:
>>> rule = sc.accept_risks.create(97737, [1])
-
delete
(id)[source]¶ Removes the accepted risk rule from Tenable.sc
- Parameters
id (int) – The identifier for the accept risk rule.
- Returns
Empty string response from the API.
- Return type
str
Examples
>>> sc.accept_risks.delete(1)
-
details
(id, fields=None)[source]¶ Retrieves the details of an accepted risk rule.
- Parameters
id (int) – The identifier for the accept risk rule.
fields (list, optional) – A list of attributes to return for each accepted risk rule.
- Returns
The accept risk rule details.
- Return type
dict
Examples
>>> rule = sc.accept_risks.details(1) >>> pprint(rule)
-
list
(repo_ids=None, plugin_id=None, port=None, org_ids=None, fields=None)[source]¶ Retrieves the list of accepted risk rules.
- Parameters
fields (list, optional) – A list of attributes to return for each accepted risk rule.
plugin_id (int, optional) – Plugin id to filter the response on.
port (int, optional) – Port number to filter the response on.
org_ids (list, optional) – List of organization ids to filter on.
repo_ids (list, optional) – List of repository ids to filter the response on.
- Returns
A list of accepted risk rules.
- Return type
Examples
>>> for rule in sc.accept_risks.list(): ... pprint(rule)
-
analysis¶
The following methods allow for interaction into the Tenable.sc
analysis API. The analysis area in Tenable.sc is
highly complex and allows for a wide range of varied inputs and outputs. This
single endpoint has been broken down in pyTenable to several methods in order to
apply some defaults to the expected data-types and options most likely to be
returned. As the filters are dependent on the tool and data-type that is being
referenced, the best solution to understanding what filters are available when
getting started is to simply pass a known bad filter string and use the
resulting error as an indicator of whats available. For example, you could
perform the following action below while attempting to see the available filters
for the mobile data-type when using the vulndetails
tool:
>>> x = sc.analysis.mobile(('something', '=', ''))
>>> x.next()
Traceback (most recent call last):
File "<input>", line 1, in <module>
x.next()
File "tenable/base.py", line 75, in next
self._get_page()
File "tenable/sc/analysis.py", line 43, in _get_page
resp = self._api.post('analysis', json=query).json()
File "tenable/base.py", line 436, in post
return self._request('POST', path, **kwargs)
File "tenable/base.py", line 379, in _request
raise self._error_codes[status](resp)
PermissionError: 00000000-0000-0000-0000-000000000000:403 {"type":"regular",
"response":"","error_code":146,"error_msg":"Invalid parameters specified for
mobile vuln query. The filter 'something' is invalid (valid filters:
repositoryIDs, port, pluginID, familyID, pluginOutput, lastSeen,
lastMitigated, severity, protocol, pluginName, baseCVSSScore,
exploitAvailable, pluginPublished, pluginModified, vulnPublished,
patchPublished, deviceID, mdmType, deviceModel, serialNumber, deviceUser,
deviceVersion, osCPE).","warnings":[],"timestamp":1545060739}
The resulting error details specifically what filters can be set.
When it comes to constructing filters, TenableSC uses a common filter structure
for the collapsed filter-set. This format is in the form of a 3 entry tuple
consisting of (‘filtername’, ‘operator’, ‘value’). For example, if you’re
looking to set the pluginID
filter to 19506
the filter would look like
('pluginID', '=', '19506')
. Severities are in level of criticality, from 0
(informational) to 4 (critical). Filters like these can be a string of comma-
separated values to indicate multiple items. So for high and critical vulns,
('severity', '=', '3,4')
would return only what your looking for.
Asset list calculations in filters are a bit more complex, but still shouldn’t be too difficult. Tenable.sc leverages nested pairs for the asset calculations combined with a operator to define how that pair are to be combined. Each of the elements within the pair can further be nested, allowing for some quite complex asset list math to happen.
On the simple side, if you just want to look for The the combined results of
asset lists 1 or 2, you would perform:
('asset', '~', ('or', 1, 2))
.
Note the tilda, informing the filtering engine that it will need to perform some
sort of calculation first. The tilda is only used when using the asset filter.
Now for a more complex calculation, you could look for the IPs that exist in
both 1 or 2, but not 3:
('asset', '~', ('and', ('or', 1, 2), ('not', 3)))
As you can see it’s just a matter of nesting out from “1 or 2”. The only new
concept here is the paired tuple for not. asking for the inverse of an asset
list requires that you wrap it in a tuple with the not operator.
Methods available on sc.analysis
:
-
class
AnalysisAPI
(api)[source]¶ -
console
(*filters, **kw)[source]¶ Queries the analysis API for log data from the Tenable.sc Console itself.
- Parameters
filters (tuple, optional) – The analysis module provides a more compact way to write filters to the analysis endpoint. The purpose here is to aid in more readable code and reduce the amount of boilerplate that must be written to support a filtered call to analysis. The format is simply a list of tuples. Each tuple is broken down into (field, operator, value).
date (str, optional) – A date in YYYYMM format. the default is simply “all”.
pages (int, optional) – The number of pages to query. Default is all.
limit (int, optional) – How many entries should be in each page? Default is 200.
offset (int, optional) – How many entries to skip before processing. Default is 0.
sort_field (str, optional) – The field to sort the results on.
sort_direction (str, optional) – The direction in which to sort the results. Valid settings are
asc
anddesc
. The default isasc
.
- Returns
An iterator object handling data pagination.
- Return type
:obj:` AnalysisResultsIterator`
-
events
(*filters, **kw)[source]¶ Queries the analysis API for event data from the Log Correlation Engine
- Parameters
filters (tuple, optional) – The analysis module provides a more compact way to write filters to the analysis endpoint. The purpose here is to aid in more readable code and reduce the amount of boilerplate that must be written to support a filtered call to analysis. The format is simply a list of tuples. Each tuple is broken down into (field, operator, value).
pages (int, optional) – The number of pages to query. Default is all.
limit (int, optional) – How many entries should be in each page? Default is 200.
offset (int, optional) – How many entries to skip before processing. Default is 0.
source (str, optional) – The data source location. Allowed sources are
lce
andarchive
. Defaults tolce
.silo_id (int, optional) – If a silo id is specified, then the results fetched will be from the lce silo specified and not from the cumulative result set.
sort_field (str, optional) – The field to sort the results on.
sort_direction (str, optional) – The direction in which to sort the results. Valid settings are
asc
anddesc
. The default isasc
.tool (str, optional) – The analysis tool for formatting and returning a specific view into the information. If no tool is specified, the default will be
vulndetails
. Available tools are:listdata
,sumasset
,sumclassa
,sumclassb
,sumclassc
,sumconns
,sumdate
,sumdstip
,sumevent
,sumevent2
,sumip
,sumport
,sumprotocol
,sumsrcip
,sumtime
,sumtype
,sumuser
,syslog
,timedist
- Returns
An iterator object handling data pagination.
- Return type
AnalysisResultsIterator
-
mobile
(*filters, **kw)[source]¶ Queries the analysis API for mobile data collected from querying one or many MDM solutions.
- Parameters
filters (tuple, optional) – The analysis module provides a more compact way to write filters to the analysis endpoint. The purpose here is to aid in more readable code and reduce the amount of boilerplate that must be written to support a filtered call to analysis. The format is simply a list of tuples. Each tuple is broken down into (field, operator, value).
pages (int, optional) – The number of pages to query. Default is all.
limit (int, optional) – How many entries should be in each page? Default is 200.
offset (int, optional) – How many entries to skip before processing. Default is 0.
sort_field (str, optional) – The field to sort the results on.
sort_direction (str, optional) – The direction in which to sort the results. Valid settings are
asc
anddesc
. The default isasc
.tool (str, optional) – The analysis tool for formatting and returning a specific view into the information. If no tool is specified, the default will be
vulndetails
. Available tools are:listvuln
,sumdeviceid
,summdmuser
,summodel
,sumoscpe
,sumpluginid
,sumseverity
,vulndetails
- Returns
An iterator object handling data pagination.
- Return type
AnalysisResultsIterator
-
scan
(scan_id, *filters, **kw)[source]¶ Queries the analysis API for vulnerability data from a specific scan.
- Parameters
scan_id (int) – If a scan id is specified, then the results fetched will be from the scan specified and not from the cumulative result set.
filters (tuple, optional) – The analysis module provides a more compact way to write filters to the analysis endpoint. The purpose here is to aid in more readable code and reduce the amount of boilerplate that must be written to support a filtered call to analysis. The format is simply a list of tuples. Each tuple is broken down into (field, operator, value).
pages (int, optional) – The number of pages to query. Default is all.
limit (int, optional) – How many entries should be in each page? Default is 200.
offset (int, optional) – How many entries to skip before processing. Default is 0.
source (str, optional) – The data source location. Allowed sources are
cumulative
andpatched
. Defaults tocumulative
.sort_field (str, optional) – The field to sort the results on.
sort_direction (str, optional) – The direction in which to sort the results. Valid settings are
asc
anddesc
. The default isasc
.tool (str, optional) – The analysis tool for formatting and returning a specific view into the information. If no tool is specified, the default will be
vulndetails
. Available tools are:cceipdetail
,cveipdetail
,iavmipdetail
,iplist
,listmailclients
,listservices
,listos
,listsoftware
,listsshservers
,listvuln
,listwebclients
,listwebservers
,sumasset
,sumcce
,sumclassa
,sumclassb
,sumclassc
,sumcve
,sumdnsname
,sumfamily
,sumiavm
,sumid
,sumip
,summsbulletin
,sumprotocol
,sumremediation
,sumseverity
,sumuserresponsibility
,sumport
,trend
,vulndetails
,vulnipdetail
,vulnipsummary
view (str, optional) – The type of vulnerability slice you’d like to have returned. The returned data can be either
all
,new
, orpatched
. If no view is specified, then the default will beall
.
- Returns
An iterator object handling data pagination.
- Return type
AnalysisResultsIterator
Examples
A quick example showing how to get the information for a specific scan from SecurityCenter. As the default is for the scan method to return data from the vulndetails tool, we can handle this without actually doing anything other than calling
>>> for vuln in sc.analysis.scan(1): ... pprint(vuln)
To ask for a specific subset of information (like only critical and exploitable vulns) you’d want to pass the filter tuples into the query like so:
>>> vulns = sc.analysis.scan(1 ... ('severity', '=', '4'), ... ('exploitAvailable', '=', 'true'))
To request a different data format (like maybe an IP summary of vulns) you just need to specify the appropriate tool:
>>> ips = sc.analysis.scan(1 ... ('severity', '=', '4'), ... ('exploitAvailable', '=', 'true'), tool='sumip')
-
vulns
(*filters, **kw)[source]¶ Query’s the analysis API for vulnerability data within the cumulative repositories.
- Parameters
filters (tuple, optional) – The analysis module provides a more compact way to write filters to the analysis endpoint. The purpose here is to aid in more readable code and reduce the amount of boilerplate that must be written to support a filtered call to analysis. The format is simply a list of tuples. Each tuple is broken down into (field, operator, value).
query_id (int, optional) – The ID number of the SC Query where filters should be pulled from in place of the tuple filters. This is mutually exclusive with the tuple filters.
pages (int, optional) – The number of pages to query. Default is all.
limit (int, optional) – How many entries should be in each page? Default is 200.
offset (int, optional) – How many entries to skip before processing. Default is 0.
source (str, optional) – The data source location. Allowed sources are
cumulative
andpatched
. Defaults tocumulative
.scan_id (int, optional) – If a scan id is specified, then the results fetched will be from the scan specified and not from the cumulative result set.
sort_field (str, optional) – The field to sort the results on.
sort_direction (str, optional) – The direction in which to sort the results. Valid settings are
asc
anddesc
. The default isasc
.tool (str, optional) – The analysis tool for formatting and returning a specific view into the information. If no tool is specified, the default will be
vulndetails
. Available tools are:cceipdetail
,cveipdetail
,iavmipdetail
,iplist
,listmailclients
,listservices
,listos
,listsoftware
,listsshservers
,listvuln
,listwebclients
,listwebservers
,sumasset
,sumcce
,sumclassa
,sumclassb
,sumclassc
,sumcve
,sumdnsname
,sumfamily
,sumiavm
,sumid
,sumip
,summsbulletin
,sumprotocol
,sumremediation
,sumseverity
,sumuserresponsibility
,sumport
,trend
,vulndetails
,vulnipdetail
,vulnipsummary
- Returns
An iterator object handling data pagination.
- Return type
AnalysisResultsIterator
Examples
A quick example showing how to get all of the information stored in SecurityCenter. As the default is for the vulns method to return data from the vulndetails tool, we can handle this without actually doing anything other than calling
>>> from pprint import pprint >>> for vuln in sc.analysis.vulns(): ... pprint(vuln)
To ask for a specific subset of information (like only critical and exploitable vulns) you’d want to pass the filter tuples into the query like so:
>>> vulns = sc.analysis.vulns( ... ('severity', '=', '4'), ... ('exploitAvailable', '=', 'true'))
To request a different data format (like maybe an IP summary of vulns) you just need to specify the appropriate tool:
>>> ips = sc.analysis.vulns( ... ('severity', '=', '4'), ... ('exploitAvailable', '=', 'true'), tool='sumip')
-
asset_lists¶
The following methods allow for interaction into the Tenable.sc Assets API. These items are typically seen under the Assets section of Tenable.sc.
Methods available on sc.asset_lists
:
-
class
AssetListAPI
(api)[source]¶ -
create
(name, list_type, **kw)[source]¶ Creates an asset-list.
- Parameters
name (str) – The name for the asset list to create.
list_type (str) – The type of list to create. Supported values are
combination
,dnsname
,dnsnameupload
,dynamic
,ldapquery
,static
,staticeventfilter
,staticvulnfilter
,templates
,upload
,watchlist
,watchlisteventfilter
, andwatchlistupload
.combinations (tuple, optional) – An asset combination tuple. For further information refer to the asset combination logic described at
tenable.sc.analysis
.data_fields (list, optional) – A list of data fields as required for a given asset list type. Each item within the list should be formatted in the following way:
{'fieldName': 'name', 'fieldValue': 'value'}
description (str, optional) – The description for the asset list being created.
dn (str, optional) – The base DN to use for an LDAP query. Must also provide a
search_string
and anldap_id
.dns_names (list, optional) – When defining a DNS asset list, use this attribute to provide the list of DNS addresses.
exclude_managed_ips (bool, optional) – Determines whether or not managed IPs should be excluded from the asset list.
filters (list, optional) – A list of filter tuples to use when defining filtered asset list types. Follows the same format as filters within the rest of pyTenable.
fobj (FileObject, optional) – A file-like object to use when uploading an asset list.
ips (list, optional) – A list of IP Addresses, CIDRs, and/or IP Address ranges to use for the purposes of a static asset list.
lce_id (int, optional) – When defining a event-based asset list, which LCE should be used to generate the asset list query.
ldap_id (int, optional) – The numeric identifier pertaining to the LDAP server to use for an LDAP query. must also provide a
dn
and asearch_string
.prep (bool, optional) – Should asset preperation be run after the list is created? If unspecified, the default action is
True
.rules (tuple, optional) –
For a dynamic asset list, the tuple definition of the rules to determine what Ips are associated to this asset list. Rules follow a similar pattern to the asset combination logic and are written in a way to follow the same visual methodology as the UI.
For example, a simple dynamic ruleset may look like:
('any', ('dns', 'contains', 'svc.company.tld'), ('dns', 'contains', 'prod.company.tld'))
Which would match all assets with either svc.company.tld or prod.company.tld in their DNS names. Rule gropups can be nested as well, by supplying a new group tuple instead of a rule:
('any', ('dns', 'contains', 'svc.company.tld'), ('dns', 'contains', 'prod.company.tld'), ('any', ('ip', 'contains', '192.168.140'), ('ip', 'contains', '192.168.141')))
In this example we have nested another group requiring that the ip may contain either of the values in addition to any of the DNS rules.
It’s also possible to constrain the rule to a specific plugin or plugins as well by adding a 4th element in a rule tuple. Defining them would look like so:
# Singular Plugin ID ('plugintext', 'contains', 'credentialed', 19506) # Multiple Plugin IDs ('plugintext', 'contains', 'stuff', [19506, 10180])
Available rules are
dns
,exploitAvailable
,exploitFrameworks
,firstseen
,mac
,os
,ip
,lastseen
,netbioshost
,netbiosworkgroup
,pluginid
,plugintext
,port
,severity
,sshv1
,sshv2
,tcpport
,udpport
, andxref
.Available operators are
contains
,eq
,lt
,lte
,ne
,gt
,gte
,regex
,pcre
.Group alauses are either
any
orall
. Any is a logical or. All is a logical and.
scan_id (int, optional) – When defining an “individual” source_type, the numeric id of the scan instance to base the query upon.
search_string (str, optional) – The search string to use as part of an LDAP Query. Must also provide a
dn
and anldap_id
.sort_dir (str, optional) – When defining a filtered asset list type, determines the direction of the sort to use. This field must be passed when defining a sort_field.
sort_field (str, optional) – When defining a filtered asset list type, determines what field to sort the resulting query on.
source_type (str, optional) – The source of the data to query from when defining a filtered asset list type.
start_offset (int, optional) – The start offset of the filter to use when defining a filtered asset list type.
tags (str, optional) – A tag to associate to the asset list.
template (int, optional) – The numeric id of the template to use.
tool (str, optional) – When specifying filtered asset list types, the analysis tool to use for determining what IPs should be included within the asset list.
view (str, optional) – When the source_type is “individual”, the view defined what subset of the data to use.
- Returns
The newly created asset-list.
- Return type
dict
Examples
>>> asset-list = sc.asset_lists.create()
-
delete
(id)[source]¶ Removes a asset-list.
- Parameters
id (int) – The numeric identifier for the asset-list to remove.
- Returns
The deletion response dict
- Return type
dict
Examples
>>> sc.asset_lists.delete(1)
-
details
(id, fields=None)[source]¶ Returns the details for a specific asset-list.
- Parameters
id (int) – The identifier for the asset-list.
fields (list, optional) – A list of attributes to return.
- Returns
The asset-list resource record.
- Return type
dict
Examples
>>> asset-list = sc.asset_lists.details(1) >>> pprint(asset-list)
-
edit
(id, **kw)[source]¶ Edits an asset-list.
- Parameters
id (int) – The numeric id of the asset list to edit.
combinations (tuple, optional) – An asset combination tuple. For further information refer to the asset combination logic described at
tenable.sc.analysis
.data_fields (list, optional) – A list of data fields as required for a given asset list type. Each item within the list should be formatted in the following way:
{'fieldName': 'name', 'fieldValue': 'value'}
description (str, optional) – The description for the asset list being created.
dn (str, optional) – The base DN to use for an LDAP query. Must also provide a
search_string
and anldap_id
.dns_names (list, optional) – When defining a DNS asset list, use this attribute to provide the list of DNS addresses.
exclude_managed_ips (bool, optional) – Determines whether or not managed IPs should be excluded from the asset list.
filters (list, optional) – A list of filter tuples to use when defining filtered asset list types. Follows the same format as filters within the rest of pyTenable.
fobj (FileObject, optional) – A file-like object to use when uploading an asset list.
ips (list, optional) – A list of IP Addresses, CIDRs, and/or IP Address ranges to use for the purposes of a static asset list.
lce_id (int, optional) – When defining a event-based asset list, which LCE should be used to generate the asset list query.
ldap_id (int, optional) – The numeric identifier pertaining to the LDAP server to use for an LDAP query. must also provide a
dn
and asearch_string
.name (str, optional) – The name for the asset list to create.
prep (bool, optional) – Should asset preperation be run after the list is created? If unspecified, the default action is
True
.rules (tuple, optional) – For a dynamic asset list, the tuple definition of the rules to determine what Ips are associated to this asset list. Rules follow a similar pattern to the asset combination logic and are written in a way to follow the same visual methodology as the UI.
scan_id (int, optional) – When defining an “individual” source_type, the numeric id of the scan instance to base the query upon.
search_string (str, optional) – The search string to use as part of an LDAP Query. Must also provide a
dn
and anldap_id
.sort_dir (str, optional) – When defining a filtered asset list type, determines the direction of the sort to use. This field must be passed when defining a sort_field.
sort_field (str, optional) – When defining a filtered asset list type, determines what field to sort the resulting query on.
source_type (str, optional) – The source of the data to query from when defining a filtered asset list type.
start_offset (int, optional) – The start offset of the filter to use when defining a filtered asset list type.
tags (str, optional) – A tag to associate to the asset list.
template (int, optional) – The numeric id of the template to use.
tool (str, optional) – When specifying filtered asset list types, the analysis tool to use for determining what IPs should be included within the asset list.
type (str, optional) – The type of list to create. Supported values are
combination
,dnsname
,dnsnameupload
,dynamic
,ldapquery
,static
,staticeventfilter
,staticvulnfilter
,templates
,upload
,watchlist
,watchlisteventfilter
, andwatchlistupload
.view (str, optional) – When the source_type is “individual”, the view defined what subset of the data to use.
- Returns
The newly updated asset-list.
- Return type
dict
Examples
>>> asset-list = sc.asset_lists.edit()
-
audit_files¶
The following methods allow for interaction into the Tenable.sc Audit File API and the Audit File Template API. These items are typically seen under the Scans: Audit Files section of Tenable.sc.
Methods available on sc.audit_files
:
-
class
AuditFileAPI
(api)[source]¶ -
create
(name, audit_file=None, tailoring_file=None, **kw)[source]¶ Creates a audit file.
- Parameters
name (str) – The name of the audit file.
audit_file (FileObject, optional) – The file-like object containing the audit file if uploading a custom audit file.
benchmark (str, optional) – When the type is set to either SCAP datatype, this specifies the name of the benchmark.
data_stream (str, optional) – When using version 1.2 of either SCAP datatype, you must specify the name of the data stream.
description (str, optional) – A description of for the audit file.
profile (str, optional) – When the type is set to either SCAP datatype, this specifies the name of the profile.
tailoring_file (FileObject, optional) – When the SCAP version is set to 1.2, this tailoring file can optionally be provided.
template (int, optional) – The audit file template it to use. If using a template, then no file is uploaded.
type (str, optional) – The type of audit file to upload. Generally only used when uploading SCAP content as it will default to the Tenable-created audit-file format. Supported SCAP values are
scapWindows
andscapLinux
.vars (dict, optional) – If a template is specified, then this dictionary specifies the parameters within the template to customize and what those values should be. The values are provided within the template definition.
version (str, optional) – When specifying a SCAP datatype, this informs Tenable.sc what version of SCAP this audit checklist is. Supported values are
1.0
,1.1
, and1.2
.
- Returns
The newly created audit file.
- Return type
dict
Examples
>>> audit = sc.audit_files.create()
-
delete
(id)[source]¶ Removes a audit file.
- Parameters
id (int) – The numeric identifier for the audit file to remove.
- Returns
An empty response.
- Return type
str
Examples
>>> sc.audit_files.delete(1)
-
details
(id, fields=None)[source]¶ Returns the details for a specific audit file.
- Parameters
id (int) – The identifier for the audit file.
fields (list, optional) – A list of attributes to return.
- Returns
The audit file resource record.
- Return type
dict
Examples
>>> audit = sc.audit_files.details(1) >>> pprint(audit)
-
edit
(id, audit_file=None, tailoring_file=None, **kw)[source]¶ Edits a audit file.
- Parameters
audit_file (FileObject, optional) – The file-like object containing the audit file if uploading a custom audit file.
benchmark (str, optional) – When the type is set to either SCAP datatype, this specifies the name of the benchmark.
data_stream (str, optional) – When using version 1.2 of either SCAP datatype, you must specify the name of the data stream.
description (str, optional) – A description of for the audit file.
name (str, optional) – The name of the audit file.
profile (str, optional) – When the type is set to either SCAP datatype, this specifies the name of the profile.
tailoring_file (FileObject, optional) – When the SCAP version is set to 1.2, this tailoring file can optionally be provided.
template (int, optional) – The audit file template it to use. If using a template, then no file is uploaded.
type (str, optional) – The type of audit file to upload. Generally only used when uploading SCAP content as it will default to the Tenable-created audit-file format. Supported SCAP values are
scapWindows
andscapLinux
.vars (dict, optional) – If a template is specified, then this dictionary specifies the parameters within the template to customize and what those values should be. The values are provided within the template definition.
version (str, optional) – When specifying a SCAP datatype, this informs Tenable.sc what version of SCAP this audit checklist is. Supported values are
1.0
,1.1
, and1.2
.
- Returns
The newly updated audit file.
- Return type
dict
Examples
>>> audit = sc.audit_files.edit()
-
list
(fields=None)[source]¶ Retrieves the list of scan zone definitions.
- Parameters
fields (list, optional) – A list of attributes to return for each audit file.
- Returns
A list of audit file resources.
- Return type
Examples
>>> for audit in sc.audit_files.list(): ... pprint(audit)
-
template_categories
()[source]¶ Returns the audit file template categories
- Returns
List of audit file category listing dicts.
- Return type
- Exmaples:
>>> for cat in sc.audit_files.template_categorties(): ... pprint(cat)
-
template_details
(id, fields=None)[source]¶ Returns the details for the specified audit file template id.
- Parameters
id (int) – The numeric identifier for the audit file template.
fields (list, optional) – A list of attributes to return.
- Returns
The audit file template record.
- Return type
dict
- Exmaples:
>>> tmpl = sc.audit_files.template_details(1)
-
template_list
(category=None, search=None, fields=None)[source]¶ Returns the list of audit file templates.
- Parameters
category (int, optional) – Restrict the results to only the specified category id.
fields (list, optional) – A list of attributes to return.
search (str, optional) – Restrict the response to only audit file names that match the search string specified.
- Returns
List of audit file records.
- Return type
- Exmaples:
>>> for tmpl in sc.audit_files.template_list(): ... pprint(tmpl)
-
credentials¶
The following methods allow for interaction into the Tenable.sc Scan Credentials API. These items are typically seen under the Scan Credentials section of Tenable.sc.
Methods available on sc.credentials
:
-
class
CredentialAPI
(api)[source]¶ -
create
(name, cred_type, auth_type, **kw)[source]¶ Creates a credential.
- Parameters
name (str) – The name for the credential.
cred_type (str) – The type of credential to store. Valid types are
database
,snmp
,ssh
, andwindows
.auth_type (str) – The type of authentication for the credential. Valid types are
beyondtrust
,certificate
, cyberark``,kerberos
,lieberman
,lm
,ntlm
,password
,publickey
,thycotic
.beyondtrust_api_key (str, optional) – The API key to use for authenticating to Beyondtrust.
beyondtrust_duration (int, optional) – The length of time to cache the checked-out credentials from Beyondtrust. This value should be less than the password change interval within Beyondtrust.
beyondtrust_host (str, optional) – The host address for the Beyondtrust application.
beyondtrust_port (int, optional) – The port number associated with the Beyondtrust application.
beyondtrust_use_escalation (bool, optional) – If enabled, informs the scanners to use Beyondtrust for privilege escalation.
beyondtrust_use_private_key (bool, optional) – If enabled, informs the scanners to use key-based auth for SSH connections instead of password auth.
beyondtrust_use_ssl (bool, optional) – Should the scanners communicate to Beyondtrust over SSL for credential retrieval? If left unspecified, the default is set to
True
.beyondtrust_verify_ssl (bool, optional) – Should the SSL certificate be validated when communicating to Beyondtrust? If left unspecified, the default is
False
.community_string (str, optional) – The SNMP community string to use for authentication.
db_type (str, optional) – The type of database connection that will be performed. Valid types are
DB2
,Informix/DRDA
,MySQL
,Oracle
,PostgreSQL
,SQL Server
.description (str, optional) – A description to associate to the credential.
domain (str, optional) – The Active Directory domain to use if the user is a member of a domain.
escalation_path (str, optional) – The path in which to run the escalation commands.
escalation_password (str, optional) – The password to use for the escalation.
escalation_su_use (str, optional) – If performing an SU escalation, this is the user to escalate to.
escalation_username (str, optional) – The username to escalate to.
kdc_ip (str, optional) – The kerberos host supplying the session tickets.
kdc_port (int, optional) – The port to use for kerberos connections. If left unspecified the default is
88
.kdc_protocol (str, optional) – The protocol to use for kerberos connections. Valid options are
tcp
andudp
. If left unspecified then the default istcp
.kdc_realm (str, optional) – The Kerberos realm to use for authentication.
lieberman_host (str, optional) – The address for the Lieberman vault.
lieberman_port (int, optional) – The port number where the Lieberman service is listening.
lieberman_pam_password (str, optional) – The password to authenticate to the Lieberman RED API.
lieberman_pam_user (str, optional) – The username to authenticate to the Lieberman RED API.
lieberman_system_name (str, optional) – The name for the credentials in Lieberman.
lieberman_use_ssl (bool, optional) – Should the scanners communicate to Lieberman over SSL for credential retrieval? If left unspecified, the default is set to
True
.lieberman_verify_ssl (bool, optional) – Should the SSL certificate be validated when communicating to Lieberman? If left unspecified, the default is
False
.password (str, optional) – The password for the credential.
port (int, optional) – A valid port number for a database credential.
privilege_escalation (str, optional) – The type of privilege escalation to perform once authenticated. Valid values are
.k5login
,cisco
,dzdo
,none
,pbrun
,su
,su+sudo
,sudo
. If left unspecified, the default isnone
.oracle_auth_type (str, optional) – The type of authentication to use when communicating to an Oracle database server. Supported values are
sysdba
,sysoper
, andnormal
. If left unspecified, the default option isnormal
.oracle_service_type (str, optional) – The type of service identifier specified in the
sid
parameter. Valid values are eithersid
orservice_name
. If left unspecified, the default issid
.sid (str, optional) – The service identifier or name for a database credential.
sql_server_auth_type (str, optional) – The type of authentication to perform to the SQL Server instance. Valid values are
SQL
andWindows
. The default value if left unspecified isSQL
.tags (str, optional) – A tag to associate to the credential.
username (str, optional) – The username for the OS credential.
thycotic_domain (str, optional) – The domain, if set, within Thycotic.
thycotic_organization (str, optional) – The organization to use if using a cloud instance of Thycotic.
thycotic_password (str, optional) – The password to use when authenticating to Thycotic.
thycotic_private_key (bool, optional) – If enabled, informs the scanners to use key-based auth for SSH connections instead of password auth.
thycotic_secret_name (str, optional) – The secret name value on the Tycotic server.
thycotic_url (str, optional) – The absolute URL path pointing to the Thycotic secret server.
thycotic_username (str, optional) – The username to use to authenticate to Thycotic.
thycotic_verify_ssl (bool, optional) – Should the SSL certificate be validated when communicating to Thycotic? If left unspecified, the default is
False
.vault_account_name (str, optional) – The unique name of the credential to retrieve from CyberArk. Generally referred to as the name paramater within CyberArk.
vault_address (str, optional) – The domain for the CyberArk account. SSL must be configured through IIS on the CCP before using.
vault_app_id (str, optional) – The AppID to use with CyberArk.
vault_cyberark_client_cert (file, optional) – The fileobject containing the CyberArk client certificate.
vault_cyberark_url (str, optional) – The URL for the CyberArk AIM web service. If left unspecified, the default URL path of
/AIMWebservice/v1.1/AIM.asmx
will be used..vault_cyberark_private_key (file, optional) – The fileobject containing the CyberArk client private key.
vault_cyberark_private_key_passphrase (str, optional) – The passhrase for the private key.
vault_folder (str, optional) – The folder to use within CyberArk for credential retrieval.
vault_host (str, optional) – The CyberArk Vault host.
vault_password (str, optional) – The password to use for authentication to the vault if the CyberArk Central Credential Provider is configured for basic auth.
vault_policy_id (int, optional) – The CyberArk PolicyID assigned to the credentials to retrieve.
vault_port (int, optional) – The port in which the CyberArk Vault resides.
vault_safe (str, optional) – The CyberArk safe that contains the credentials to retrive.
vault_use_ssl (bool, optional) – Should the scanners communicate to CyberArk over SSL for credential retrieval? If left unspecified, the default is set to
True
.vault_username (str, optional) – The username to use for authentication to the vault if the CyberArk Central Credential Provider is configured for basic auth.
vault_verify_ssl (bool, optional) – Should the SSL certificate be validated when communicating to the vault? If left unspecified, the default is
False
.
- Returns
The newly created credential.
- Return type
dict
Examples
Creating a Windows AD credential:
>>> cred = sc.credentials.create( ... 'Example AD User', 'windows', 'ntlm', ... username='scanneruser', ... password='sekretpassword', ... domain='Company.com')
Creating a root user SSH credential:
>>> cred = sc.credentials.create( ... 'Example SSH Cred', 'ssh', 'password', ... username='root', ... password='sekretpassword')
Creating a root user SSH cred with a private key:
>>> with open('privatekeyfile', 'rb') as keyfile: ... cred = sc.credentials.create( ... 'Example SSH Keys', 'ssh', 'publicKey', ... username='root', ... private_key=keyfile)
Creating a normal user SSH cred with sudo for privilege escalation:
>>> cred = sc.credentials.create( ... 'Example SSH Sudo', 'ssh', 'password', ... username='user', ... password='sekretpassword', ... privilege_escalation='sudo', ... escalation_password='sekretpassword')
Creating a SQL Server cred set:
>>> cred = sc.credentials.create( ... 'Example SQL Server', 'database', 'SQL Server', ... username='sa', ... password='sekretpassword', ... sql_server_auth_type='SQL', ... sid='database_name')
-
delete
(id)[source]¶ Removes a credential.
- Parameters
id (int) – The numeric identifier for the credential to remove.
- Returns
An empty response.
- Return type
str
Examples
>>> sc.credentials.delete(1)
-
details
(id, fields=None)[source]¶ Returns the details for a specific credential.
- Parameters
id (int) – The identifier for the credential.
fields (list, optional) – A list of attributes to return.
- Returns
The credential resource record.
- Return type
dict
Examples
>>> cred = sc.credentials.details(1) >>> pprint(cred)
-
edit
(id, **kw)[source]¶ Edits a credential.
- Parameters
auth_type (str, optional) – The type of authentication for the credential. Valid types are
beyondtrust
,certificate
, cyberark``,kerberos
,lieberman
,lm
,ntlm
,password
,publickey
,thycotic
.beyondtrust_api_key (str, optional) – The API key to use for authenticating to Beyondtrust.
beyondtrust_duration (int, optional) – The length of time to cache the checked-out credentials from Beyondtrust. This value should be less than the password change interval within Beyondtrust.
beyondtrust_host (str, optional) – The host address for the Beyondtrust application.
beyondtrust_port (int, optional) – The port number associated with the Beyondtrust application.
beyondtrust_use_escalation (bool, optional) – If enabled, informs the scanners to use Beyondtrust for privilege escalation.
beyondtrust_use_private_key (bool, optional) – If enabled, informs the scanners to use key-based auth for SSH connections instead of password auth.
beyondtrust_use_ssl (bool, optional) – Should the scanners communicate to Beyondtrust over SSL for credential retrieval? If left unspecified, the default is set to
True
.beyondtrust_verify_ssl (bool, optional) – Should the SSL certificate be validated when communicating to Beyondtrust? If left unspecified, the default is
False
.community_string (str, optional) – The SNMP community string to use for authentication.
db_type (str, optional) – The type of database connection that will be performed. Valid types are
DB2
,Informix/DRDA
,MySQL
,Oracle
,PostgreSQL
,SQL Server
.description (str, optional) – A description to associate to the credential.
domain (str, optional) – The Active Directory domain to use if the user is a member of a domain.
escalation_path (str, optional) – The path in which to run the escalation commands.
escalation_password (str, optional) – The password to use for the escalation.
escalation_su_use (str, optional) – If performing an SU escalation, this is the user to escalate to.
escalation_username (str, optional) – The username to escalate to.
kdc_ip (str, optional) – The kerberos host supplying the session tickets.
kdc_port (int, optional) – The port to use for kerberos connections. If left unspecified the default is
88
.kdc_protocol (str, optional) – The protocol to use for kerberos connections. Valid options are
tcp
andudp
. If left unspecified then the default istcp
.kdc_realm (str, optional) – The Kerberos realm to use for authentication.
lieberman_host (str, optional) – The address for the Lieberman vault.
lieberman_port (int, optional) – The port number where the Lieberman service is listening.
lieberman_pam_password (str, optional) – The password to authenticate to the Lieberman RED API.
lieberman_pam_user (str, optional) – The username to authenticate to the Lieberman RED API.
lieberman_system_name (str, optional) – The name for the credentials in Lieberman.
lieberman_use_ssl (bool, optional) – Should the scanners communicate to Lieberman over SSL for credential retrieval? If left unspecified, the default is set to
True
.lieberman_verify_ssl (bool, optional) – Should the SSL certificate be validated when communicating to Lieberman? If left unspecified, the default is
False
.name (str, optional) – The name for the credential.
password (str, optional) – The password for the credential.
port (int, optional) – A valid port number for a database credential.
privilege_escalation (str, optional) – The type of privilege escalation to perform once authenticated. Valid values are
.k5login
,cisco
,dzdo
,none
,pbrun
,su
,su+sudo
,sudo
. If left unspecified, the default isnone
.oracle_auth_type (str, optional) – The type of authentication to use when communicating to an Oracle database server. Supported values are
sysdba
,sysoper
, andnormal
. If left unspecified, the default option isnormal
.oracle_service_type (str, optional) – The type of service identifier specified in the
sid
parameter. Valid values are eithersid
orservice_name
. If left unspecified, the default issid
.sid (str, optional) – The service identifier or name for a database credential.
sql_server_auth_type (str, optional) – The type of authentication to perform to the SQL Server instance. Valid values are
SQL
andWindows
. The default value if left unspecified isSQL
.tags (str, optional) – A tag to associate to the credential.
type (str. optional) – The type of credential to store. Valid types are
database
,snmp
,ssh
, andwindows
.username (str, optional) – The username for the OS credential.
thycotic_domain (str, optional) – The domain, if set, within Thycotic.
thycotic_organization (str, optional) – The organization to use if using a cloud instance of Thycotic.
thycotic_password (str, optional) – The password to use when authenticating to Thycotic.
thycotic_private_key (bool, optional) – If enabled, informs the scanners to use key-based auth for SSH connections instead of password auth.
thycotic_secret_name (str, optional) – The secret name value on the Tycotic server.
thycotic_url (str, optional) – The absolute URL path pointing to the Thycotic secret server.
thycotic_username (str, optional) – The username to use to authenticate to Thycotic.
thycotic_verify_ssl (bool, optional) – Should the SSL certificate be validated when communicating to Thycotic? If left unspecified, the default is
False
.vault_account_name (str, optional) – The unique name of the credential to retrieve from CyberArk. Generally referred to as the name paramater within CyberArk.
vault_address (str, optional) – The domain for the CyberArk account. SSL must be configured through IIS on the CCP before using.
vault_app_id (str, optional) – The AppID to use with CyberArk.
vault_cyberark_client_cert (file, optional) – The fileobject containing the CyberArk client certificate.
vault_cyberark_url (str, optional) – The URL for the CyberArk AIM web service. If left unspecified, the default URL path of
/AIMWebservice/v1.1/AIM.asmx
will be used..vault_cyberark_private_key (file, optional) – The fileobject containing the CyberArk client private key.
vault_cyberark_private_key_passphrase (str, optional) – The passhrase for the private key.
vault_folder (str, optional) – The folder to use within CyberArk for credential retrieval.
vault_host (str, optional) – The CyberArk Vault host.
vault_password (str, optional) – The password to use for authentication to the vault if the CyberArk Central Credential Provider is configured for basic auth.
vault_policy_id (int, optional) – The CyberArk PolicyID assigned to the credentials to retrieve.
vault_port (int, optional) – The port in which the CyberArk Vault resides.
vault_safe (str, optional) – The CyberArk safe that contains the credentials to retrive.
vault_use_ssl (bool, optional) – Should the scanners communicate to CyberArk over SSL for credential retrieval? If left unspecified, the default is set to
True
.vault_username (str, optional) – The username to use for authentication to the vault if the CyberArk Central Credential Provider is configured for basic auth.
vault_verify_ssl (bool, optional) – Should the SSL certificate be validated when communicating to the vault? If left unspecified, the default is
False
.
- Returns
The newly updated credential.
- Return type
dict
Examples
>>> cred = sc.credentials.edit()
-
current¶
The following methods allow for interaction with the Tenable.sc CurrentOrganization API and the CurrentUser API.
Methods available on sc.current
:
-
class
CurrentSessionAPI
(api)[source]¶ -
associate_cert
()[source]¶ Associates the certificate passed to the server with the current user’s account. This allows for authentication via certificate in subsequent logins.
- Returns
The updated user record.
- Return type
dict
Examples
>>> sc.current.associate_cert()
-
org
(fields=None)[source]¶ Returns the organization of the current session.
- Parameters
fields (list, optional) – The list of fields that are desired to be returned. For details on what fields are available, please refer to the details on the request within the organization list API doc.
- Returns
The organization record.
- Return type
dict
Examples
>>> org = sc.current.org()
-
user
(fields=None)[source]¶ Returns the user of the current session.
- Parameters
fields (list, optional) – The list of fields that are desired to be returned. For details on what fields are available, please refer to the details on the request within the organization list API doc.
- Returns
The user record.
- Return type
dict
Examples
>>> org = sc.current.org()
-
feeds¶
The following methods allow for interaction into the Tenable.sc Feed API.
Methods available on sc.feeds
:
-
class
FeedAPI
(api)[source]¶ -
process
(feed_type, fobj)[source]¶ Initiates an off-line feed update based on the specified feed_type using the file object passed as the update file.
- Parameters
feed_type (str) – The feed type to specifically return. Valid types are active, passive, lce, sc, or all.
fobj (FileObject) – The file object to upload into SecurityCenter and use as the update package.
- Returns
Update successfully requested.
- Return type
None
Examples
updating the active plugins:
>>> with open('sc-plugins-diff.tar.gz', 'rb') as plugfile: ... sc.feeds.process('active', plugfile)
-
status
(feed_type=None)[source]¶ Returns the status of either a specific feed type (if requested) or all of the feed types if nothing is specifically asked.
- Parameters
feed_type (str, optional) – The feed type to specifically return. Valid types are active, passive, lce, sc, or all.
- Returns
If no specific feed type is specified, then a dictionary with each type listed with a sub-dictionary detailing the status is returned. If a specific feed type is requested, then only the status information for that feed type is returned.
- Return type
dict
Examples
Getting all of the feed types returned:
>>> status = sc.feed.status()
Getting the feed status for a specific type (e.g. active).
>>> status = sc.feeds.status('active')
-
update
(feed_type=None)[source]¶ Initiates an on-line feed update based on the specified feed_type. If no feed type is specified, then it will default to initiating an update for all feed types.
- Parameters
feed_type (str, optional) – The feed type to specifically return. Valid types are active, passive, lce, sc, or all.
- Returns
Update successfully requested.
- Return type
None
-
files¶
The following methods allow for interaction into the Tenable.sc File API.
Methods available on sc.files
:
-
class
FileAPI
(api)[source]¶ -
clear
(filename)[source]¶ Removes the requested file from Tenable.sc.
- Parameters
filename (str) – The file identifier associated to the file.
- Returns
The file location on disk that was removed.
- Return type
str
-
groups¶
The following methods allow for interaction into the Tenable.sc Group API. These items are typically seen under the User Groups section of Tenable.sc.
Methods available on sc.groups
:
-
class
GroupAPI
(api)[source]¶ -
create
(name, **kw)[source]¶ Creates a group.
- Parameters
name (str) – The name of the user group
asset_lists (list, optional) – List of asset list ids to allow this group to access.
audit_files (list, optional) – List of audit file ids to allow this group to access.
dashboards (list, optional) – List of dashboard ids to allow this group to access.
lce_ids (list, optional) – List of LCE ionstance ids to allow this group to access.
query_ids (list, optional) – List of query ids to allow this group to access.
report_cards (list, optional) – List of report card ids to allow this group to access.
repos (list, optional) – List of repository ids to allow this group to access.
scan_creds (list, optional) – List of scanning credential ids to allow this group to access.
scan_policies (list, optional) – List of scan policy ids to allow this group to access.
viewable (list, optional) – List of asset list ids to use for the purposes of restricting what members of this group can see within Tenable.sc.
- Returns
The newly created group.
- Return type
dict
Examples
>>> group = sc.groups.create('New Group')
-
delete
(id)[source]¶ Removes a group.
- Parameters
id (int) – The numeric identifier for the group to remove.
- Returns
An empty response.
- Return type
str
Examples
>>> sc.groups.delete(1)
-
details
(id, fields=None)[source]¶ Returns the details for a specific group.
- Parameters
id (int) – The identifier for the group.
fields (list, optional) – A list of attributes to return.
- Returns
The group resource record.
- Return type
dict
Examples
>>> group = sc.groups.details(1) >>> pprint(group)
-
edit
(id, **kw)[source]¶ Edits a group.
- Parameters
asset_lists (list, optional) – List of asset list ids to allow this group to access.
audit_files (list, optional) – List of audit file ids to allow this group to access.
dashboards (list, optional) – List of dashboard ids to allow this group to access.
lce_ids (list, optional) – List of LCE ionstance ids to allow this group to access.
name (str, optional) – The name of the user group
query_ids (list, optional) – List of query ids to allow this group to access.
report_cards (list, optional) – List of report card ids to allow this group to access.
repos (list, optional) – List of repository ids to allow this group to access.
scan_creds (list, optional) – List of scanning credential ids to allow this group to access.
scan_policies (list, optional) – List of scan policy ids to allow this group to access.
viewable (list, optional) – List of asset list ids to use for the purposes of restricting what members of this group can see within Tenable.sc.
- Returns
The newly updated group.
- Return type
dict
Examples
>>> group = sc.groups.edit()
-
organization¶
The following methods allow for interaction with the Tenable.sc Organization API. These items are typically seen under the Organization section of Tenable.sc.
Methods available on sc.organizations
:
-
class
OrganizationAPI
(api)[source]¶ -
create
(name, **kw)[source]¶ Create a new organization
- Parameters
name (str) – The name for organization.
info_links (list, optional) – A list of custom analysis links provided to users within the host vulnerability details when analyzing data outside of SecurityCenter is desired. Links shall be described in a tuple format with
(name, link)
format. For example:('SANS', 'https://isc.sans.edu/ipinfo.html?ip=%IP%')
lce_ids (list, optional) – What Log Correlation Engines (if any) should this organization be allowed to access? If left unspecified no LCE engined will be granted to this organization.
ldap_ids (list, optional) – What ldap server configuration ids should be used with this organization?
nessus_managers (list, optional) – Nessus Manager scanner for Nessus Agent scan imports.
pub_sites (list, optional) – A list of publishing site ids to associate this organization.
repos (list, optional) – A list of Repository ids to associate to this organization.
restricted_ips (list, optional) – A list of IP addresses, CIDRs, and/or IP ranges that should never be scanned.
vuln_score_low (int) – The vulnerability weighting to apply to low criticality vulnerabilities for scoring purposes. (Default: 1)
vuln_score_medium (int) – The vulnerability weighting to apply to medium criticality vulnerabilities for scoring purposes. (Default: 3)
vuln_score_high (int) – The vulnerability weighting to apply to high criticality vulnerabilities for scoring purposes. (Default: 10)
vuln_score_critical (int) – The vulnerability weighting to apply to critical criticality vulnerabilities for scoring purposes.(Default: 40)
zone_selection (str) – What type of scan zone selection should be performed? Available selection types are as follows:
auto_only
,locked
,selectable+auto
,selectable+auto_restricted
. If left unspecified, the default isauto_only
.zones (list, optional) – When
zone_selection
is notauto_only
, this field must be filled with list of ids from available scan zone(s).
- Returns
The organization resource record for the newly created Org.
- Return type
dict
Examples
Creating a new organization with automatic scan zone selection:
>>> org = sc.organization.create('Sample Organization')
Creating a new organization with custom analysis links:
>>> org = sc.organization.create(Sample Organization', info_links=[ ... ('SANS', 'https://isc.sans.edu/ipinfo.html?ip=%IP%)])
-
list
(fields=None)[source]¶ Retrieves a list of organizations.
- Parameters
fields (list, optional) – The list of fields that are desired to be returned. For details on what fields are available, please refer to the details on the request within the organization list API doc.
- Returns
List of organization definitions.
- Return type
Examples
Retrieve all of all of the organizations:
>>> repos = sc.organizations.list()
-
details
(id, fields=None)[source]¶ Retrieves the details for the specified organization.
- Parameters
id (int) – The numeric id of the organization.
fields (list, optional) – The list of fields that are desired to be returned. For details on what fields are available, please refer to the details on the request within the organization details API doc.
- Returns
The organization resource record.
- Return type
dict
Examples
>>> org = sc.organization.details(1)
-
edit
(id, **kw)[source]¶ Updates an existing organization
Edits the Organization associated with {id}, changing only the passed in fields.
- Parameters
info_links (list, optional) – A list of custom analysis links provided to users within the host vulnerability details when analyzing data outside of SecurityCenter is desired.
lce_ids (list, optional) – What Log Correlation Engines (if any) should this organization be allowed to access? If left unspecified no LCE engined will be granted to this organization.
ldap_ids (list, optional) – What ldap server configuration ids should be used with this organization?
name (str, optional) – The name for organization.
nessus_managers (list, optional) – Nessus Manager scanner for Nessus Agent scan imports.
pub_sites (list, optional) – A list of publishing site ids to associate this organization.
repos (list, optional) – A list of Repository ids to associate to this organization.
restricted_ips (list, optional) – A list of IP addresses, CIDRs, and/or IP ranges that should never be scanned.
vuln_score_low (int) – The vulnerability weighting to apply to low criticality vulnerabilities for scoring purposes. (Default: 1)
vuln_score_medium (int) – The vulnerability weighting to apply to medium criticality vulnerabilities for scoring purposes. (Default: 3)
vuln_score_high (int) – The vulnerability weighting to apply to high criticality vulnerabilities for scoring purposes. (Default: 10)
vuln_score_critical (int) – The vulnerability weighting to apply to critical criticality vulnerabilities for scoring purposes.(Default: 40)
zone_selection (str) – What type of scan zone selection should be performed? Available selection types are as follows:
auto_only
,locked
,selectable+auto
,selectable+auto_restricted
. If left unspecified, the default isauto_only
.zones (list, optional) – When
zone_selection
is notauto_only
, this field must be filled with list of ids from available scan zone(s).
- Returns
The updated organization resource record.
- Return type
dict
Examples
>>> sc.organization.edit(1, name='New Name')
-
delete
(id)[source]¶ Remove the specified organization from Tenable.sc
- Parameters
id (int) – The numeric id of the organization to delete.
- Returns
Empty response string
- Return type
str
Examples
>>> sc.organization.delete(1)
-
accept_risk_rules
(id, repos=None, plugin=None, port=None)[source]¶ Retrieves the accepted risk rules for the organization and optionally will filter based on the paramaters specified.
organization: accept-risk-rule
- Parameters
id (int) – The organization id.
repos (list, optional) – A list of repository ids to restrict the search to.
plugin (int, optional) – A plugin id to restrict the search to.
port (int, optional) – A port number to restrict the search to.
- Returns
A list of rules that match the request.
- Return type
Examples
>>> for rule in sc.organizations.accept_risk_rules(1): ... pprint(rule)
-
recast_risk_rules
(id, repos=None, plugin=None, port=None)[source]¶ Retrieves the recasted risk rules for the organization and optionally will filter based on the paramaters specified.
organization: recast-risk-rule
- Parameters
id (int) – The organization id.
repos (list, optional) – A list of repository ids to restrict the search to.
plugin (int, optional) – A plugin id to restrict the search to.
port (int, optional) – A port number to restrict the search to.
- Returns
A list of rules that match the request.
- Return type
Examples
>>> for rule in sc.organizations.recast_risk_rules(1): ... pprint(rule)
-
manager_create
(org_id, username, password, role, **kw)[source]¶ Creates a new security manager for the given org. For a complete list of parameters that are supported for this call, please refer to
tio.users.create()
for more details.organization-security-manager: create
- Parameters
org_id – (int): The numeric identifier for the organization.
username (str) – The username for the account
password (str) – The password for the user to create
role (int) – The role that should be assigned to this user.
**kw (dict) – The keyword args to pass to the user constructor.
- Returns
The newly created security manager.
- Return type
dict
Examples
>>> secmngr = sc.organizations.manager_create(1, ... 'username', 'password', 1)
-
manager_delete
(org_id, user_id, migrate_to=None)[source]¶ Removes the user specified.
organization-security-manager: delete
- Parameters
org_id – (int): The numeric identifier for the organization.
user_id – (int): The numeric identifier for the user.
Examples
>>> sc.organizations.manager_delete(1, 1)
-
manager_details
(org_id, user_id, fields=None)[source]¶ Retrieves the details of a specified security manager within a specified organization.
organization-security-manager: details
- Parameters
org_id – (int): The numeric identifier for the organization.
user_id – (int): The numeric identifier for the user.
fields (list, optional) – The list of fields that are desired to be returned. For details on what fields are available, please refer to the details on the request within the organization list API doc.
- Returns
The user resource record.
- Return type
dict
Examples
>>> secmngr = sc.organizations.manager_details(1, 1)
-
manager_edit
(org_id, user_id, **kw)[source]¶ Edits the specified security manager within the specified organization. For details on the supported arguments that may be passed, please refer to
tio.users.edit()
for more details.organization-security-manager: edit
- Parameters
org_id – (int): The numeric identifier for the organization.
user_id – (int): The numeric identifier for the user.
**kw (dict) – The keyword args to pass to the user constructor.
- Returns
The updated user record.
- Return type
dict
Examples
>>> secmngr = sc.organizations.manager_edit(1, 1, ... username='updated')
-
managers_list
(org_id, fields=None)[source]¶ Retrieves a list of security managers.
organization-security-manager: list
- Parameters
org_id – (int): The numeric identifier for the organization.
fields (list, optional) – The list of fields that are desired to be returned. For details on what fields are available, please refer to the details on the request within the organization list API doc.
- Returns
List of user definitions.
- Return type
Examples
Retrieve all of the security managers for a given org.:
>>> repos = sc.organizations.managers_list()
-
plugins¶
The following methods allow for interaction with the Tenable.sc Plugins API. These items are typically seen under the Plugins section of Tenable.sc.
Methods available on sc.plugins
:
-
class
PluginAPI
(api)[source]¶ -
list
(**kw)[source]¶ Retrieves the list of plugins.
- Parameters
fields (list, optional) – A list of attributes to return.
filter (tuple, optional) – A filter tuple for which to filter the plugins. Filter tuples must be
('name', 'operator', 'value')
and follow a similar yet different format to the analysis filters.limit (int, optional) – How many records should be returned in each page of data. If none is specified, the default is 1000 records.
offset (int, optional) – At what offset within the data should we start returning data. If none is specified, the default is 0.
pages (int, optional) – How many pages of data should we return. If none is specified then all pages will return.
sort_field (str, optional) – The field to sort the results on.
sort_direction (str, optional) – The direction in which to sort the results. Valid settings are
asc
anddesc
. The default isasc
.type (str, optional) – The type of plugins to return. Available types are
active
,all
,compliance
,custom
,lce
,notPassive
, andpassive
. If nothing is specified, thenall
is assumed.
- Returns
an iterator object handling data pagination.
- Return type
PluginResultsIterator
Examples
To retrieve all of the plugins, you’ll simply need to call the list method like so:
>>> plugins = sc.plugins.list() >>> for plugin in plugins: ... pprint(plugin)
If you only want the plugins with java in the name, you’d run a query similar to this one:
>>> plugins = sc.plugins.list( ... filter=('name', 'like', 'java'))
For just the active plugins, we’d run:
>>> plugins = sc.plugins.list(type='active')
-
details
(id, fields=None)[source]¶ Returns the details for a specific plugin.
- Parameters
id (int) – The identifier for the plugin.
fields (list, optional) – A list of attributes to return.
- Returns
The plugin resource record.
- Return type
dict
Examples
>>> plugin = sc.alerts.detail(19506) >>> pprint(plugin)
-
policies¶
The following methods allow for interaction into the Tenable.sc Scan Policies API. These items are typically seen under the Scan Policies section of Tenable.sc.
Methods available on sc.policies
:
-
class
ScanPolicyAPI
(api)[source]¶ -
copy
(id, name=None)[source]¶ Clones the specified scan policy
- Parameters
id (int) – The unique identifier for the source policy to clone.
name (str, optional) – The name of the new policy.
- Returns
The scan policy resource record for the newly created policy.
- Return type
dict
Examples
>>> policy = sc.policies.copy(10001) >>> pprint(policy)
-
create
(**kw)[source]¶ Creates a new scan policy
- Parameters
name (str) – The Name of the new scan policy
audit_files (list, optional) – A list of audit files (by integer id) to be used for the scan policy.
description (str, optional) – An optional description for the policy
preferences (dict, optional) – A dictionary of settings that override the defaults within a policy template.
profile_name (str, optional) – The profile of the scan. Default is an empty string.
owner_id (int, optional) – Define who shall own the policy by that user’s integer identifer
tags (str, optional) – An optional tag identifier for the policy
template_id (int, optional) – The identifier of the policy template to use. If none is specified, the default id for the “Advanced Policy” will be used.
xccdf (bool, optional) – Should XCCDF results be generated? The default is False.
- Returns
The created scan policy resource.
- Return type
dict
Examples
An example advanced policy with all of the default preferences.
>>> sc.policies.create( ... name='Example Advanced Policy')
An example policy where we want to modify
-
delete
(id)[source]¶ Removes a configured scan policy.
- Parameters
id (int) – The unique identifier for the policy to remove.
- Returns
The empty response from the API.
- Return type
str
Examples
>>> sc.policies.delete(10001)
-
details
(id, fields=None)[source]¶ Retrieves the details for a specified policy.
- Parameters
id (int) – The unique identifier for the policy
fields (list, optional) – The list of fields that are desired to be returned. For details on what fields are available, please refer to the details on the request within the policy details API doc.
- Returns
Details about the scan policy template
- Return type
dict
Examples
>>> policy = sc.policies.details(2) >>> pprint(policy)
-
edit
(id, **kw)[source]¶ Edits an existing scan policy
- Parameters
id (int) – The unique identifier to the scan policy to edit
audit_files (list, optional) – A list of audit files (by integer id) to be used for the scan policy.
description (str, optional) – An optional description for the policy
name (str, optional) – The Name of the new scan policy
preferences (dict, optional) – A dictionary of settings that override the defaults within a policy template.
profile_name (str, optional) – The profile of the scan. Default is an empty string.
remove_prefs (list, optional) – A list of preferences to remove from the policy.
owner_id (int, optional) – Define who shall own the policy by that user’s integer identifer
tags (str, optional) – An optional tag identifier for the policy
template_id (int, optional) – The identifier of the policy template to use. If none is specified, the default id for the “Advanced Policy” will be used.
xccdf (bool, optional) – Should XCCDF results be generated? The default is False.
- Returns
The updated scan policy resource.
- Return type
dict
Examples
An example advanced policy with all of the default preferences.
>>> sc.policies.edit(10001, ... name='Updated Example Advanced Policy')
To remove a preference, you would perform the following:
>>> sc.policies.edit(10001, ... remove_prefs=['scan_malware'])
-
export_policy
(id, fobj=None)[source]¶ Export the specified scan policy
- Parameters
id (int) – The unique identifier for the scan policy to export.
fobj (FileObject, optional) – The file-like object to write the resulting file into. If no file-like object is provided, a BytesIO objects with the downloaded file will be returned. Be aware that the default option of using a BytesIO object means that the file will be stored in memory, and it’s generally recommended to pass an actual file-object to write to instead.
- Returns
The file-like object with the resulting export.
- Return type
FileObject
Examples
>>> with open('example_policy.xml', 'wb') as fobj: ... sc.policies.export_policy(1001, fobj)
-
import_policy
(name, fobj, description=None, tags=None)[source]¶ Imports a scan policy into Tenable.sc
- Parameters
name (str) – The name of the imported scan policy.
fobj (FileObject) – The file-like object containing the scan policy.
description (str, optional) – A description for the scan policy.
tags (str, optional) – A tag for the scan policy.
- Returns
An empty response from the API.
- Return type
str
Examples
>>> with open('example_policy.xml', 'rb') as fobj: ... sc.policies.import_policy('Example Policy', fobj)
-
list
(fields=None)[source]¶ Retrieved the list of Scan policies configured.
- Parameters
fields (list, optional) – The list of fields that are desired to be returned. For details on what fields are available, please refer to the details on the request within the policy list API doc.
- Returns
usable & manageable scan policies.
- Return type
dict
Examples
>>> policies = sc.policies.list() >>> for policy in policies['manageable']: ... pprint(policy)
-
share
(id, *groups)[source]¶ Shares the policy with other user groups.
- Parameters
id (int) – The unique identifier for the scan policy to share.
*groups (int) – The list of user group ids to share the policy to.
- Returns
The updated scan policy resource.
- Return type
dict
Examples
Share the scan policy with groups 1, 2, and 3:
>>> sc.policies.share(10001, 1, 2, 3)
-
template_details
(id, fields=None, remove_editor=True)[source]¶ Retrieves the details for a specified policy template.
- Parameters
id (int) – The unique identifier for the policy template
fields (list, optional) – The list of fields that are desired to be returned. For details on what fields are available, please refer to the details on the request within the policy template details API doc.
remove_editor (bol, optional) – Should the response have the raw editor string removed? The default is yes.
- Returns
Details about the scan policy template
- Return type
dict
Examples
>>> template = sc.policies.template_details(2) >>> pprint(template)
-
template_list
(fields=None)[source]¶ Retrieved the list of scan policy templates.
- Parameters
fields (list, optional) – The list of fields that are desired to be returned. For details on what fields are available, please refer to the details on the request within the policy template list API doc.
- Returns
List of available policy templates
- Return type
Examples
>>> templates = sc.policies.template_list() >>> for policy in templates: ... pprint(policy)
-
queries¶
The following methods allow for interaction into the Tenable.sc Query API. These items are typically seen under the Workflow -> Query section of Tenable.sc.
Methods available on sc.queries
:
-
class
QueryAPI
(api)[source]¶ -
create
(name, tool, data_type, *filters, **kw)[source]¶ Creates a query.
- Parameters
name (str) – The name of the new query
tool (str) – The tool to use to query the data.
data_type (str) – The type of data to query.
*filters (tuple, optional) – The filters to use for the query. Refer to the documentation within the :ref:’tenable.sc.analysis’ for more information on how to construct these.
browse_cols (list, optional) – What columns are set to be browsable for the analysis view.
browse_sort_col (str, optional) – The browsable column in which to sort on.
browse_sort_dir (str, optional) – The direction in which to sort. Valid values are
asc
anddesc
.description (str, optional) – The description for the query.
limit (int, optional) – The limit to the number of records to return. If nothing is specified, the API defaults to 100 records.
offset (int, optional) – The number of records to skip before returning results. If nothing is specified, then the default is 0.
owner_id (int, optional) – The identifier stating the owner of the query. If left unspecified, then the default is the current user.
sort_direction (str, optional) – The direction in which to sort. Valid values are
asc
anddesc
.sort_field (str, optional) – The field in which to sort the results.
tags (str, optional) – Tags definition for the query.
- Returns
The newly created query.
- Return type
dict
Examples
>>> query = sc.queries.create('New Query', 'vulndetails', 'vuln', ... ('pluginID', '=', '19506'))
-
delete
(id)[source]¶ Removes a query.
- Parameters
id (int) – The numeric identifier for the query to remove.
- Returns
An empty response.
- Return type
str
Examples
>>> sc.queries.delete(1)
-
details
(id, fields=None)[source]¶ Returns the details for a specific query.
- Parameters
id (int) – The identifier for the query.
fields (list, optional) – A list of attributes to return.
- Returns
The query resource record.
- Return type
dict
Examples
>>> query = sc.queries.details(1) >>> pprint(query)
-
edit
(id, *filters, **kw)[source]¶ Edits a query.
- Parameters
*filters (tuple, optional) – The filters to use for the query. Refer to the documentation within the :ref:’tenable.sc.analysis’ for more information on how to construct these.
browse_cols (str, optional) – What columns are set to be browsable for the analysis view.
browse_sort_col (list, optional) – The browsable column in which to sort on.
browse_sort_dir (str, optional) – The direction in which to sort. Valid values are
asc
anddesc
.description (str, optional) – The description for the query.
limit (int, optional) – The limit to the number of records to return. If nothing is specified, the API defaults to 100 records.
name (str, optional) – The name of the new query
offset (int, optional) – The number of records to skip before returning results. If nothing is specified, then the default is 0.
owner_id (int, optional) – The identifier stating the owner of the query. If left unspecified, then the default is the current user.
sort_direction (str, optional) – The direction in which to sort. Valid values are
asc
anddesc
.sort_field (str, optional) – The field in which to sort the results.
tags (str, optional) – Tags definition for the query.
tool (str, optional) – The tool to use to query the data.
type (str, optional) – The type of data to query.
- Returns
The newly updated query.
- Return type
:obj:` dict`
Examples
>>> query = sc.queries.edit()
-
list
(fields=None)[source]¶ Retrieves the list of query definitions.
- Parameters
fields (list, optional) – A list of attributes to return for each query.
- Returns
A list of query resources.
- Return type
Examples
>>> for query in sc.queries.list(): ... pprint(query)
-
share
(id, *groups)[source]¶ Shares the specified query to another user group.
- Parameters
id (int) – The numeric id for the query.
*groups (int) – The numeric id of the group(s) to share to.
- Returns
The updated query resource.
- Return type
dict
Examples
>>> sc.queries.share(1, group_1, group_2)
-
repositories¶
The following methods allow for interaction with the Tenable.sc Repository API. These items are typically seen under the Repositories section of Tenable.sc.
Methods available on sc.repositories
:
-
class
RepositoryAPI
(api)[source]¶ -
accept_risk_rules
(id, **kw)[source]¶ Retrieves the accepted risk rules associated with the specified repository.
- Parameters
id (int) – The numeric id of the repository.
fields (list, optional) – The list of fields that are desired to be returned. For details on what fields are available, please refer to the details on the request within the repository accept risk rules API doc.
- Returns
List of the accepted risk rules that apply to the repo.
- Return type
list
Examples
>>> rules = sc.repositories.accept_risk_rules(1)
-
asset_intersections
(id, uuid=None, ip=None, dns=None)[source]¶ Retrieves the asset lists that a UUID, DNS address, or IP exists in.
repository: asst intersections
- Parameters
id (int) – The numeric identifier of the repository to query.
dns (str) – The DNS name to query
ip (str) – The IP address to query
uuid (str) – The UUID to query.
- Returns
The list of assets matching the criteria.
- Return type
list
Examples
>>> assetlists = sc.repositories.asset_intersection(1, ... ip='192.168.0.1')
-
create
(**kw)[source]¶ Creates a new repository
- Parameters
name (str) – The name for the respository.
allowed_ips (list, optional) – Allowed IPs will restrict incoming data being inserted into the repository to only the IPs that exist within the configured CIDR ranges. Accepts a list of CIDR strings based on the repository format (IPv4 or IPv6). If left unspecified, then it will default to the CIDR equivalent of “allow all” for that IP version. IPv4=0.0.0.0/0, IPv6=::/0.
description (str, optional) – A description for the repository.
format (str, optional) – The format of the repository. Valid choices are
agent
,IPv4
,IPv6
, andmobile
. The default if unspecified isIPv4
.fulltext_search (bool, optional) – Should full-text searching be enabled? This option is used for IPv4, IPv6, and agent repository formats and determins whether the plugin output is trended along with the normalized data. If left unspecified, the default is set to
False
.lce_correlation (list, optional) – What Log Correlation Engines (if any) should correlate against this repository. A list of configured LCE numeric IDs is supplied. This option is used on IPv4, IPv6, and agent formats and is defaulted to nothing if left unspecified.
nessus_sched (dict, optional) – This is the .Nessus file generation schedule for IPv4 and IPv6 repository formats. This option should only be used if there is a need to consume the Repository in a raw Nessus XML format. If left unspecified, it will default to
{'type': 'never'}
. For more information refer to Schedule Dictionariesmobile_sched (dict, optional) – When using the mobile repository format, this option will inform Tenable.sc how often to perform the MDM synchronization into the repository. If left unspecified, it will default to
{'type': 'never'}
. For more information refer to Schedule Dictionariesorgs (list, optional) – A list of Organization IDs used to assign the repository to 1 or many organizations.
preferences (dict, optional) – When using a mobile repository type, this dictionary details the required preferences to inject into the backend scan needed to communicate to the MDM solution.
remote_ip (str, optional) – When the Remote repository type is used, this is the IP address of the Tenable.sc instance that the repository will be pulled from.
remote_repo (int, optional) – When the Remote repository type is used, this is the numeric ID of the repository on the remote host that will be pulled.
remote_sched (dict, optional) – When the Remote repository type is used, this is the schedule dictionary that will inform Tenable.sc how often to synchronize with the downstream Tenable.sc instance. If left unspecified then we will default to
{'type': 'never'}
. For more information refer to Schedule Dictionariesrepo_type (str, optional) – What type of repository is this? Valid choices are
Local
,Remote
, andOffline
. The default if unspecified isLocal
.scanner_id (int, optional) – When using the mobile repository format, we must specify the scanner from which to query the MDM source.
trending (int, optional) – How many days of trending snapshots should be created for this repository. This value is only used for IPv4, IPv6, and agent repositories. If not supplied, the default will be 0.
- Returns
The repository resource record for the newly created Repo.
- Return type
dict
Examples
Creating a new IPv4 Repository leveraging the defaults:
>>> repo = sc.repositories.create(name='Example IPv4')
Creating a new IPv4 Repository with 90 days of trending and linked to the first Organization:
>>> repo = sc.repositories.create( ... name='Example Trending', trending=90, orgs=[1])
Creating an IPv6 repository:
>>> repo = sc.repositories.create( ... name='Example IPv6', format='IPv6')
Creating an agent repository:
>>> repo = sc.repositories.create( ... name='Example Agent', format='agent')
Creating an MDM repository for ActiveSync that will sync every day at 6am eastern:
>>> repo = sc.repositories.create( ... name='Example ActiveSync', mdm_id=1, scanner_id=1, ... format='mobile', orgs=[1], ... mobile_sched={ ... 'repeatRule': 'FREQ=DAILY;INTERVAL=1', ... 'start': 'TZID=America/New_York:20190212T060000', ... 'type': 'ical', ... }, ... preferences={ ... 'domain': 'AD_DOMAIN', ... 'domain_admin': 'DA_ACCOUNT_NAME', ... 'domain_controller': 'dc1.company.tld', ... 'password': 'DA_ACCOUNT_PASSWORD' ... })
Creating a new repository to remotely sync the downstream Tenable.sc instance’s repository 1 to this host and institute trending for 90 days:
>>> repo = sc.repositories.create( ... name='Example Remote Repo', ... repo_type='Remote', ... remote_ip='192.168.0.101', ... remote_repo=1, ... trending=90, ... orgs=[1], ... remote_sched={ ... 'type': 'ical', ... 'start': 'TZID=America/NewYork:20190212T060000', ... 'repeatRule': 'FREQ=DAILY;INTERVAL=1' ... })
-
delete
(id)[source]¶ Remove the specified repository from Tenable.sc
- Parameters
id (int) – The numeric id of the repository to delete.
- Returns
Empty response string
- Return type
str
Examples
>>> sc.repositories.delete(1)
-
details
(id, fields=None)[source]¶ Retrieves the details for the specified repository.
- Parameters
id (int) – The numeric id of the repository.
fields (list, optional) – The list of fields that are desired to be returned. For details on what fields are available, please refer to the details on the request within the repository details API doc.
- Returns
The repository resource record.
- Return type
dict
Examples
>>> repo = sc.repositories.details(1)
-
device_info
(id, dns=None, ip=None, uuid=None, fields=None)[source]¶ Retrieves the device information for the requested device on the associated repository.
repository: ip info <Repository.html#RepositoryRESTReference-/repository/{id}/ipInfo>
- Parameters
id (int) – The numeric id for the repository to query.
dns (str) – The DNS name to query
fields (list, optional) – The list of fields that are desired to be returned. For details on what fields are available, please refer to the details on the request within the repository device info API doc.
ip (str) – The IP address to query
uuid (str) – The UUID to query.
- Returns
The device resource.
- Return type
dict
Examples
>>> host = sc.repositories.device_info(1, ip='192.168.0.1')
-
edit
(id, **kw)[source]¶ Updates an existing repository
- Parameters
id (int) – The numeric id of the repository to edit.
allowed_ips (list, optional) – Allowed IPs will restrict incoming data being inserted into the repository to only the IPs that exist within the configured CIDR ranges. Accepts a list of CIDR strings based on the repository format (IPv4 or IPv6).
description (str, optional) – A description for the repository.
lce_correlation (list, optional) – What Log Correlation Engines (if any) should correlate against this repository. A list of configured LCE numeric IDs is supplied. This option is used on IPv4, IPv6, and agent formats.
name (str, optional) – The name for the repository.
nessus_sched (dict, optional) – This is the .Nessus file generation schedule for IPv4 and IPv6 repository formats. This option should only be used if there is a need to consume the Repository in a raw Nessus XML format. For more information refer to Schedule Dictionaries
mobile_sched (dict, optional) – When using the mobile repository format, this option will inform Tenable.sc how often to perform the MDM synchronization into the repository. For more information refer to Schedule Dictionaries
orgs (list, optional) – A list of Organization IDs used to assign the repository to 1 or many organizations.
preferences (dict, optional) – When using a mobile repository type, this dictionary details the required preferences to inject into the backend scan needed to communicate to the MDM solution.
remote_ip (str, optional) – When the Remote repository type is used, this is the IP address of the Tenable.sc instance that the repository will be pulled from.
remote_repo (int, optional) – When the Remote repository type is used, this is the numeric ID of the repository on the remote host that will be pulled.
remote_sched (dict, optional) – When the Remote repository type is used, this is the schedule dictionary that will inform Tenable.sc how often to synchronize with the downstream Tenable.sc instance. For more information refer to Schedule Dictionaries
scanner_id (int, optional) – When using the mobile repository format, we must specify the scanner from which to query the MDM source.
trending (int, optional) – How many days of trending snapshots should be created for this repository. This value is only used for IPv4, IPv6, and agent repositories.
- Returns
The repository resource record for the newly created Repo.
- Return type
dict
Examples
>>> repo = sc.repositories.edit(1, name='Example IPv4')
-
export_repository
(id, fobj)[source]¶ Exports the repository and writes the archive tarball into the file object passed.
- Parameters
id (int) – The numeric id associated to the repository.
fobj (FileObject) – The file-like object for the repository archive.
- Returns
The export response record.
- Return type
dict
Example
>>> with open('repo.tar.gz', 'wb') as archive: ... sc.repositories.export_repository(1, archive)
-
import_repository
(id, fobj)[source]¶ Imports the repository archive for an offline repository.
- Parameters
id (int) – The numeric id associated to the offline repository.
fobj (FileObject) – The file-like object containing the repository archive.
- Returns
The import response record.
- Return type
dict
Example
>>> with open('repo.tar.gz', 'rb') as archive: ... sc.repositories.import_repository(1, archive)
-
recast_risk_rules
(id, **kw)[source]¶ Retrieves the recast risk rules associated with the specified repository.
- Parameters
id (int) – The numeric id of the repository.
fields (list, optional) – The list of fields that are desired to be returned. For details on what fields are available, please refer to the details on the request within the repository recast risk rules API doc.
- Returns
List of the recast risk rules that apply to the repo.
- Return type
list
Examples
>>> rules = sc.repositories.recast_risk_rules(1)
-
remote_authorize
(host, username, password)[source]¶ Authorized communication to a downstream Tenable.sc instance with the provided username and password.
- Parameters
host (str) – The downstream Tenable.sc instance ip address.
username (str) – The username to authenticate with.
password (str) –
- Returns
Empty response object
- Return type
str
Examples
>>> sc.repositories.remote_authorize( ... '192.168.0.101', 'admin', 'password')
-
remote_fetch
(host)[source]¶ Retrieves the list of repositories from the specified downstream Tenable.sc instance.
- Parameters
host (str) – The downstream Tenable.sc instance ip address.
- Returns
The list of repositories on the downstream Tenable.sc instance.
- Return type
list
-
remote_sync
(id)[source]¶ Initiates a remote synchronization with a downstream Tenable.sc instance. This action can only be performed on an offline repository.
- Parameters
id (int) – The numeric id for the remote repository.
- Returns
The sync response record.
- Return type
dict
Examples
>>> sc.repositories.remote_sync(1)
-
roles¶
The following methods allow for interaction into the Tenable.sc Roles API. These items are typically seen under the User Roles section of Tenable.sc.
Methods available on sc.roles
:
-
class
RoleAPI
(api)[source]¶ -
create
(name, **kw)[source]¶ Creates a role.
- Parameters
name (str) – The name of the new role to create.
descrioption (str, optional) – A description for the role to be created.
can_agent_scan (bool, optional) – Are members of this role allowed to perform agent scans? If left unspecified the default is
False
.can_feed_update (bool, optional) – Are members of this role allowed to perform feed updates? If left unspecified, the default is
False
.can_import_scan (bool, optional) – Are members of this role allowed to import scans? If left unspecified, the default is
False
.can_scan (bool, optional) – Are members of this role allowed to perform scans? If left unspecified, the default is
False
.can_share (bool, optional) – Are members of this role allowed to share objects with other groups? If left unspecified, the default is
False
.can_view_logs (bool, optional) – Are members of this role allowed to view the organizational logs from Tenable.sc? If left unspecified, the default is
False
.create_alerts (bool, optional) – Are members of this role allowed to create alerts? If left unspecified, the default is
False
.create_auditfiles (bool, optional) – Are members of this role allowed to create their own audit files? If left unspecified, the default is
False
.create_ldap_assets (bool, optional) – Are members of this role allowed to create LDAP Query Asset Lists? If left unspecified, the default is
False
.create_policies (bool, optional) – Are members of this role allowed to create scan policies? If left unspecified, the default is
False
.create_tickets (bool, optional) – Are members of this role allowed to create tickets? If left unspecified, the default is
False
.manage_accepted_risk_rules (bool, optional) – Are members of this role allowed to manage accepted risk rules? If left unspecified, the default is
False
.manage_attributes (bool, optional) – Are members of this role allowed to manage attribute sets? If left unspecified, the default is
False
.manage_blackout_windows (bool, optional) – Are members of this role allowed to manage scanning blackout windows? If left unspecified, the default is
False
.manage_groups (bool, optional) – Are members of this role allowed to manage user groups? If left unspecified, the default is
False
.manage_images (bool, optional) – Are members of this role allowed to manage report images? If left unspecified, the default is
False
.manage_recast_risk_rules (bool, optional) – Are members of this role allowed to manage recast risk rules? If left unspecified, the default is
False
.manage_relationships (bool, optional) – Are members of this role allowed to manage the user group relationships? If left unspecified, the default is
False
.manage_roles (bool, optional) – Are members of this role allowed to manage group role configurations? If left unspecified, the default is
False
.
- Returns
The newly created role.
- Return type
dict
Examples
>>> role = sc.roles.create('Example Role', ... can_scan=True, can_import_scan=True)
-
delete
(id)[source]¶ Removes a role.
- Parameters
id (int) – The numeric identifier for the role to remove.
- Returns
An empty response.
- Return type
str
Examples
>>> sc.roles.delete(1)
-
details
(id, fields=None)[source]¶ Returns the details for a specific role.
- Parameters
id (int) – The identifier for the role.
fields (list, optional) – A list of attributes to return.
- Returns
The role resource record.
- Return type
dict
Examples
>>> role = sc.roles.details(1) >>> pprint(role)
-
edit
(id, **kw)[source]¶ Edits a role.
- Parameters
id (int) – The numeric identifier for the role.
name (str, optional) – The name of the new role to create.
description (str, optional) – A description for the role to be created.
can_agent_scan (bool, optional) – Are members of this role allowed to perform agent scans? If left unspecified the default is
False
.can_feed_update (bool, optional) – Are members of this role allowed to perform feed updates? If left unspecified, the default is
False
.can_import_scan (bool, optional) – Are members of this role allowed to import scans? If left unspecified, the default is
False
.can_scan (bool, optional) – Are members of this role allowed to perform scans? If left unspecified, the default is
False
.can_share (bool, optional) – Are members of this role allowed to share objects with other groups? If left unspecified, the default is
False
.can_view_logs (bool, optional) – Are members of this role allowed to view the organizational logs from Tenable.sc? If left unspecified, the default is
False
.create_alerts (bool, optional) – Are members of this role allowed to create alerts? If left unspecified, the default is
False
.create_auditfiles (bool, optional) – Are members of this role allowed to create their own audit files? If left unspecified, the default is
False
.create_ldap_assets (bool, optional) – Are members of this role allowed to create LDAP Query Asset Lists? If left unspecified, the default is
False
.create_policies (bool, optional) – Are members of this role allowed to create scan policies? If left unspecified, the default is
False
.create_tickets (bool, optional) – Are members of this role allowed to create tickets? If left unspecified, the default is
False
.manage_accepted_risk_rules (bool, optional) – Are members of this role allowed to manage accepted risk rules? If left unspecified, the default is
False
.manage_attributes (bool, optional) – Are members of this role allowed to manage attribute sets? If left unspecified, the default is
False
.manage_blackout_windows (bool, optional) – Are members of this role allowed to manage scanning blackout windows? If left unspecified, the default is
False
.manage_groups (bool, optional) – Are members of this role allowed to manage user groups? If left unspecified, the default is
False
.manage_images (bool, optional) – Are members of this role allowed to manage report images? If left unspecified, the default is
False
.manage_recast_risk_rules (bool, optional) – Are members of this role allowed to manage recast risk rules? If left unspecified, the default is
False
.manage_relationships (bool, optional) – Are members of this role allowed to manage the user group relationships? If left unspecified, the default is
False
.manage_roles (bool, optional) – Are members of this role allowed to manage group role configurations? If left unspecified, the default is
False
.
- Returns
The newly updated scan zone.
- Return type
dict
Examples
>>> role = sc.roles.create()
-
scan_zones¶
The following methods allow for interaction into the Tenable.sc Scan Zone API. These items are typically seen under the Scan Zones section of Tenable.sc.
Methods available on sc.scan_zones
:
-
class
ScanZoneAPI
(api)[source]¶ -
create
(name, **kw)[source]¶ Creates a scan zone.
- Parameters
name (str) – The name of the scan zone
description (str, optional) – A description for the scan zone.
ips (list, optional) – The list of IP addresses, CIDRs, or IP ranges that encompass the scan zone.
scanner_ids (list, optional) – A list of scanner ids to associate to the scan zone.
- Returns
The newly created scan zone.
- Return type
dict
Examples
>>> zone = sc.scan_zones.create('Example Scan Zone', ... ips=['127.0.0.1'], scanner_ids=[1])
-
delete
(id)[source]¶ Removes the specified scan zone.
- Parameters
id (int) – The numeric identifier for the scan-zone to remove.
- Returns
An empty response.
- Return type
str
Examples
>>> sc.scan_zones.delete(1)
-
details
(id, fields=None)[source]¶ Returns the details for a specific scan zone.
- Parameters
id (int) – The identifier for the scan.
fields (list, optional) – A list of attributes to return.
- Returns
The scan zone resource record.
- Return type
dict
Examples
>>> zone = sc.scan_zones.details(1) >>> pprint(zone)
-
edit
(id, **kw)[source]¶ Edits a scan zone.
- Parameters
description (str, optional) – A description for the scan zone.
ips (list, optional) – The list of IP addresses, CIDRs, or IP ranges that encompass the scan zone.
name (str, optional) – The name of the scan zone
scanner_ids (list, optional) – A list of scanner ids to associate to the scan zone.
- Returns
The newly updated scan zone.
- Return type
dict
Examples
>>> zone = sc.scan_zones.create(1, ... ips=['127.0.0.1'], scanner_ids=[1])
-
scans¶
The following methods allow for interaction into the Tenable.sc Scan API. While the api endpoints obliquely refers to the model in which this collection of actions modifies as “Scans”, Tenable.sc is actually referring to the scan definitions, which are the un-launched and/or scheduled scans typically seen within the Active Scans section within Tenable.sc.
Methods available on sc.scans
:
-
class
ScanAPI
(api)[source]¶ -
copy
(id, name, user_id)[source]¶ Copies an existing scan definition.
- Parameters
id (int) – The scan definition identifier to copy.
name (str) – The name of the copy thats created.
user_id (int) – The user id to assign as the owner of the new scan definition.
- Returns
Scan definition resource.
- Return type
dict
Examples
>>> sc.scans.copy(1, name='Cloned Scan')
-
create
(name, repo, **kw)[source]¶ Creates a scan definition.
- Parameters
name (str) – The name of the scan.
repo (int) – The repository id for the scan.
auto_mitigation (int, optional) – How many days to hold on to data before mitigating it? The default value is 0.
asset_lists (list, optional) – A list of asset list ids to run the scan against. A logical OR will be performed to compute what hosts to scan against.
creds (list, optional) – A list of credential ids to use for the purposes of this scan. This list should be treated as an un-ordered list of credentials.
description (str, optional) – A description for the scan.
email_complete (bool, optional) – Should we notify the owner upon completion of the scan? The default is
False
.email_launch (bool, optional) – Should we notify the owner upon launching the scan? The default is
False
.host_tracking (bool, optional) – Should DHCP host tracking be enabled? The default is False.
max_time (int, optional) – The maximum amount of time that the scan may run in seconds.
0
or less for unlimited. The default is3600
seconds.policy_id (int, optional) – The policy id to use for a policy-based scan.
plugin_id (int, optional) – The plugin id to use for a plugin-based scan.
reports (list, optional) – What reports should be run upon completion of the scan? Each report dictionary requires an id for the report definition and the source for which to run the report against. Example:
{'id': 1, 'reportSource': 'individual'}
.rollover (str, optional) – How should rollover scans be created (assuming the scan is configured to create a rollover scan with the timeout action). The available actions are to automatically start the
nextDay
at the same time the scan was originally configured to run, and to generate a rollovertemplate
. The default action is to generate atemplate
.scan_zone (int, optional) – The zone identifier to use for the scan. If non is selected then the default of “0” or “All Zones” is selected.
schedule (dict, optional) – A dictionary detailing the repeating schedule of the scan. For more information refer to Schedule Dictionaries
targets (list, optional) – A list of valid targets. These targets could be IPs, FQDNs, CIDRs, or IP ranges.
timeout (str, optional) – How should an incomplete scan be handled? The available actions are
discard
,import
, androllover
. The default action isimport
.vhosts (bool, optional) – Should virtual host logic be enabled for the scan? The default is
False
.
- Returns
The scan resource for the created scan.
- Return type
dict
Examples
Creating a scan for a single host:
>>> sc.scans.create('Example scan', 1, policy_id=1001, ... targets=['127.0.0.1'])
-
delete
(id)[source]¶ Removes the specified scan from SecurityCenter.
- Parameters
id (int) – The identifier for the scan to delete.
- Returns
The list of scan id removed.
- Return type
Examples
>>> sc.scans.delete(1)
-
details
(id, fields=None)[source]¶ Returns the details for a specific scan.
- Parameters
id (int) – The identifier for the scan.
fields (list, optional) – A list of attributes to return.
- Returns
The alert resource record.
- Return type
dict
Examples
>>> alert = sc.alerts.detail(1) >>> pprint(alert)
-
edit
(id, **kw)[source]¶ Edits an existing scan definition.
- Parameters
id (int) – The identifier for the scan.
auto_mitigation (int, optional) – How many days to hold on to data before mitigating it?
asset_lists (list, optional) – A list of asset list ids to run the scan against. A logical OR will be performed to compute what hosts to scan against.
creds (list, optional) – A list of credential ids to use for the purposes of this scan. This list should be treated as an un-ordered list of credentials.
description (str, optional) – A description for the scan.
email_complete (bool, optional) – Should we notify the owner upon completion of the scan?
email_launch (bool, optional) – Should we notify the owner upon launching the scan?
host_tracking (bool, optional) – Should DHCP host tracking be enabled?
max_time (int, optional) – The maximum amount of time that the scan may run in seconds.
0
or less for unlimited.name (str, optional) – The name of the scan.
policy (int, optional) – The policy id to use for a policy-based scan.
plugin (int, optional) – The plugin id to use for a plugin-based scan.
reports (list, optional) – What reports should be run upon completion of the scan? Each report dictionary requires an id for the report definition and the source for which to run the report against. Example:
{'id': 1, 'reportSource': 'individual'}
.repo (int, optional) – The repository id for the scan.
rollover (str, optional) – How should rollover scans be created (assuming the scan is configured to create a rollover scan with the timeout action). The available actions are to automatically start the
nextDay
at the same time the scan was originally configured to run, and to generate a rollovertemplate
.scan_zone (int, optional) – The zone identifier to use for the scan.
schedule (dict, optional) – A dictionary detailing the repeating schedule of the scan. For more information refer to Schedule Dictionaries
targets (list, optional) – A list of valid targets. These targets could be IPs, FQDNs, CIDRs, or IP ranges.
timeout (str, optional) – How should an incomplete scan be handled? The available actions are
discard
,import
, androllover
.vhosts (bool, optional) – Should virtual host logic be enabled for the scan?
- Returns
The scan resource for the created scan.
- Return type
dict
Examples
Creating a scan for a single host:
>>> sc.scans.edit(1, name='Example scan')
-
launch
(id, diagnostic_target=None, diagnostic_password=None)[source]¶ Launches a scan definition.
- Parameters
id (int) – The scan definition identifier to launch.
diagnostic_target (str, optional) – A valid IP or hostname to launch a diagnostic scan against. The
diagnostic_password
must also be specified or else this parameter will be ignored.diagnostic_password (str, optional) – A password to use for the diagnostic scan. The
diagnostic_target
must also be specified or else this parameter will be ignored.
- Returns
A scan result resource for the newly launched scan.
- Return type
dict
Examples
>>> running = sc.scans.launch(1) >>> print('The Scan Result ID is {}'.format( ... running['scanResult']['id']))
-
scan_instances¶
The following methods allow for interaction into the Tenable.sc Scan Result API. While the Tenable.sc API refers to the model these endpoints interact with as ScanResult, were actually interacting with an instance of a scan definition stored within the Scan API endpoints. These scan instances could be running scans, stopped scans, errored scans, or completed scans. These items are typically seen under the Scan Results section of Tenable.sc.
Methods available on sc.scan_instances
:
-
class
ScanResultAPI
(api)[source]¶ -
copy
(id, *users)[source]¶ Clones the scan instance.
- Parameters
id (int) – The identifier of the scan instance to clone.
*users (int) – A user id to associate to the scan instance.
- Returns
The cloned scan instance record.
- Return type
dict
Examples
>>> sc.scan_instances.copy(1)
-
delete
(id)[source]¶ Removes the scan instance from TenableSC.
- Parameters
id (int) – The identifier of the scan instance to delete.
- Returns
An empty string.
- Return type
str
Examples
>>> sc.scan_instances.delete(1)
-
details
(id, fields=None)[source]¶ Retreives the details for the specified scan instance.
- Parameters
id (int) – The identifier for the scan instance to be retrieved.
fields (list, optional) – List of fields to return. Refer to the API documentation referenced above for a list of available fields.
- Returns
The scan instance resource record.
- Return type
dict
Examples
Getting the details of a scan instance with just the default parameters:
>>> scan = sc.scan_instances.details(1) >>> pprint(scan)
Specifying what fields you’d like to be returned:
>>> scan = sc.scan_instances.details(1, ... fields=['name', 'status', 'scannedIPs', 'startTime', 'finishTime']) >>> pprint(scan)
-
email
(id, *emails)[source]¶ Emails the scan results of the requested scan to the email addresses defined.
- Parameters
id (int) – The identifier for the specified scan instance.
*emails (str) – Valid email address.
- Returns
Empty string response.
- Return type
str
Examples
>>> sc.scan_instances.email(1, 'email@company.tld')
-
export_scan
(id, fobj=None, export_format=None)[source]¶ Downloads the results of the scan.
- Parameters
id (int) – The scan instance identifier.
export_format (str, optional) – The format of the resulting data. Allowable values are
scap1_2
andv2
.v2
is the default value if none are specified.fobj (FileObject, optional) – The file-like object to write the resulting file into. If no file-like object is provided, a BytesIO objects with the downloaded file will be returned. Be aware that the default option of using a BytesIO object means that the file will be stored in memory, and it’s generally recommended to pass an actual file-object to write to instead.
- Returns
The file-like object with the resulting zipped report.
- Return type
FileObject
Examples
>>> with open('example.zip', 'wb') as fobj: ... sc.scan_instances.export_scan(1, fobj)
-
import_scan
(fobj, repo, **kw)[source]¶ Imports a nessus file into Tenable.sc.
- Parameters
fobj (FileObject) – The file-like object containing the Nessus file to import.
repo (int) – The repository id for the scan.
auto_mitigation (int, optional) – How many days to hold on to data before mitigating it? The default value is 0.
host_tracking (bool, optional) – Should DHCP host tracking be enabled? The default is False.
vhosts (bool, optional) – Should virtual host logic be enabled for the scan? The default is
False
.
- Returns
An empty string response.
- Return type
str
Examples
>>> with open('example.nessus') as fobj: ... sc.scan_instances.import_scan(fobj, 1)
-
list
(fields=None, start_time=None, end_time=None)[source]¶ Retrieves the list of scan instances.
- Parameters
fields (list, optional) – A list of attributes to return.
start_time (int, optional) – Epoch time to start search (searches against createdTime and defaults to now-30d)
end_time (int, optional) – Epoch time to end search (searches against createdTime and defaults to now)
- Returns
A list of scan instance resources.
- Return type
dict
Examples
Retreiving all of the manageable scans instances:
>>> for scan in sc.scan_instances.list()['manageable']: ... pprint(scan)
-
pause
(id)[source]¶ Pauses a running scan instance. Note that this will not impact agent scan instances.
“sc-api:scan-result: pause <Scan-Result.html#ScanResultRESTReference-/scanResult/{id}/pause>
- Parameters
id (int) – The unique identifier for the scan instance.
- Returns
The Scan instance state
- Return type
dict
Examples
>>> sc.scan_instances.pause(1)
-
reimport_scan
(id, **kw)[source]¶ Re-imports an existing scan into the cumulative repository.
- Parameters
id (int) – The scan instance identifier.
auto_mitigation (int, optional) – How many days to hold on to data before mitigating it? The default value is 0.
host_tracking (bool, optional) – Should DHCP host tracking be enabled? The default is False.
vhosts (bool, optional) – Should virtual host logic be enabled for the scan? The default is
False
.
- Returns
An empty string response.
- Return type
str
Examples
>>> sc.scan_instances.reimport_scan(1)
-
resume
(id)[source]¶ Resumes a paused scan instance. Note that this will not impact agent scan instances.
- Parameters
id (int) – The unique identifier for the scan instance.
- Returns
The Scan instance state
- Return type
dict
Examples
>>> sc.scan_instances.resume(1)
-
scanners¶
The following methods allow for interaction into the Tenable.sc Scanner API. These items are typically seen under the Scanners section of Tenable.sc.
Methods available on sc.scanners
:
-
class
ScannerAPI
(api)[source]¶ -
agent_scans
(id, search, results=None)[source]¶ Retrieves the list of agent scans that meed the specified search criteria.
- Parameters
id (int) – The numeric id of the scanner.
search (str) – The search string to send to the scanner.
results (list, optonal) – The list of results ids to test.
- Returns
The list of scans that match the search criteria.
- Return type
Examples
>>> scans = sc.scanners.agent_scans('*')
-
create
(name, address, **kw)[source]¶ Creates a scanner.
- Parameters
address (str) – The address of the scanner
name (str) – The name of the scanner
agent_capable (bool, optional) – Is this scanner an agent capable scanner? If left unspecified the default is
False
.description (str, optional) – The description of the scanner.
enabled (bool, optional) – Is this scanner enabled? If left unspecified, the default is
True
.managed (bool, optional) – Is the plugin set for this scanner managed? If left unspecified then the default is
False
.orgs (list, optional) – If the scanner is an agent capable scanner, then a list of organization ids is to be specified to attach the scanner for the purposes of agent scanning.
port (int, optional) – What is the port that the Nessus service is running on. If left unspecified, then the default is
8834
.proxy (bool, optional) – Is this scanner behind a proxy? If left unspecified then the default is
False
.zone_ids (list, optional) – List of scan zones that this scanner is to be a member of.
- Returns
The newly created scanner.
- Return type
dict
Examples
>>> scanner = sc.scanners.create('Example Scanner', '192.168.0.1')
-
delete
(id)[source]¶ Removes the specified scanner.
- Parameters
id (int) – The numeric identifier for the scanner to remove.
- Returns
An empty response.
- Return type
str
Examples
>>> sc.scanners.delete(1)
-
details
(id, fields=None)[source]¶ Returns the details for a specific scanner.
- Parameters
id (int) – The identifier for the scanner.
fields (list, optional) – A list of attributes to return.
- Returns
The scanner resource record.
- Return type
dict
Examples
>>> scanner = sc.scan_zones.details(1) >>> pprint(scanner)
-
edit
(id, **kw)[source]¶ Edits a scanner.
- Parameters
id (int) – The numeric identifier for the scanner.
address (str, optional) – The address of the scanner
agent_capable (bool, optional) – Is this scanner an agent capable scanner? If left unspecified the default is
False
.description (str, optional) – The description of the scanner.
enabled (bool, optional) – Is this scanner enabled? If left unspecified, the default is
True
.managed (bool, optional) – Is the plugin set for this scanner managed? If left unspecified then the default is
False
.name (str, optional) – The name of the scanner
orgs (list, optional) – If the scanner is an agent capable scanner, then a list of organization ids is to be specified to attach the scanner for the purposes of agent scanning.
port (int, optional) – What is the port that the Nessus service is running on. If left unspecified, then the default is
8834
.proxy (bool, optional) – Is this scanner behind a proxy? If left unspecified then the default is
False
.zone_ids (list, optional) – List of scan zones that this scanner is to be a member of.
- Returns
The newly updated scanner.
- Return type
dict
Examples
>>> scanner = sc.scanners.edit(1, enabled=True)
-
list
(fields=None)[source]¶ Retrieves the list of scanner definitions.
- Parameters
fields (list, optional) – A list of attributes to return for each scanner.
- Returns
A list of scanner resources.
- Return type
Examples
>>> for scanner in sc.scanners.list(): ... pprint(scanner)
-
status¶
The following methods allow for interaction into the Tenable.sc Status API. These API calls are typically used to understand the current job and license statuses.
Methods available on sc.status
:
system¶
The following methods allow for interaction into the Tenable.sc System API. These API calls are typically used to understand timezones, system version, etc.
Methods available on sc.system
:
-
class
SystemAPI
(api)[source]¶ -
current_locale
()[source]¶ Retreives the current system locale that Tenable.sc has been set to.
- Returns
locale resource
- Return type
dict
Examples
>>> sc.system.current_locale()
-
details
()[source]¶ Retrieves information about the Tenable.sc instance. This method should only be called before authentication has occurred. As most of the information within this call already happens upon instantiation, there should be little need to call this manually.
- Sc-api:’system
get <System.html#system_GET>`
- Returns
The response dictionary
- Return type
dict
Examples
>>> info = sc.system.details()
-
diagnostics
(task=None, options=None, fobj=None)[source]¶ Generates and downloads a diagnostic file for the purpose of troubleshooting an ailing Tenable.sc instance.
- Parameters
fobj (FileObject, optional) – The file-like object to write the diagnostics file to. If nothing is specified, a BytesIO object will be returnbed with the file.
options (list, optional) – If performing a diagnostics generation, then which items should be bundled into the diagnostics file? Available options are
all
,apacheLog
,configuration
,dependencies
,dirlist
,environment
,installLog
,logs
,sanitize
,scans
,serverConf
,setup
,sysinfo
, andupgradeLog
. If nothing is specified, it will default to['all']
.task (str, optional) – Which task to perform. Available options are
appStatus
anddiagnosticsFile
. If nothing is specified, it will default todiagnosticFile
.
- Returns
A file-like object with the diagnostics file specified.
- Return type
FileObject
Examples
>>> with open('diagnostics.tar.gz', 'wb') as fobj: ... sc.system.diagnostics(fobj=fobj)
-
list_locales
()[source]¶ Retreives the available system locales that Tenable.sc can be set to.
- Returns
locales dictionary
- Return type
dict
Examples
>>> sc.system.list_locales()
-
set_locale
(locale)[source]¶ Sets the system locale to be used. This requires an administrator to perform this task and will be a global change. The locale determines which pluginset language to use.
- Parameters
locale (str) – The plugin locale name
- Returns
The new plugin locale.
- Return type
str
Examples
Set the system locale to Japanese:
>>> sc.system.set_locale('ja')
-
users¶
The following methods allow for interaction into the Tenable.sc User API. These items are typically seen under the Users section of Tenable.sc.
Methods available on sc.users
:
-
class
UserAPI
(api)[source]¶ -
create
(username, password, role, **kw)[source]¶ Creates a user.
- Parameters
username (str) – The username for the account
password (str) – The password for the user to create
role (int) – The role that should be assigned to this user.
address (str, optional) – Optional street address information to associate to the user.
auth_type (str, optional) – The Authentication type to use for the user. Valid options are
ldap
,legacy
,saml
, andtns
. If left unspecified the default istns
.city (str, optional) – Optional city information to associate to the user.
country (str, optional) – Optional country information to associate to the user.
default_dashboards (bool, optional) – Should the default dashboards be created for the user? If left unspecified, the default is True.
default_reportcards (bool, optional) – Should the default report cards be created for the user? If left unspecified, the default is True.
default_reports (bool, optional) – Should the default reports be created fro the user? If left unspecified, the default is True.
email (str, optional) – The email address to associate to the user.
email_notice (str, optional) – What type of events should generate an email notification? Valid types are
id
,password
,both
,none
.fax (str, optional) – A fax number to associate to the user.
fingerprint (str, optional) – A fingerprint to associate to the user.
firstname (str, optional) – A first name to associate to the user.
group (int, optional) – A group to associate to the user. This parameter is required for users that are not Administrators.
is_locked (bool, optional) – If the account locked? If left unspecified the default is False.
ldap_id (int, optional) – If specifying an LDAP auth type, this is the numeric identifier for the LDAP configuration to use.
managed_usergroups (list, optional) – A list of group ids that the user is allowed to manage users within.
managed_userobjs (list, optional) – A list of group ids that the user is allowed to manage objects within. This includes asset lists, reports, etc.
org (int, optional) – If logged in as an administrator, and creating a security manager account, the organization id must be passed in order to inform Tenable.sc which organization to create the security manager within.
phone (str, optional) – A phone number to associate to the user.
responsibility (int, optional) – The asset list detailing what assets the user is responsible for. A value of
0
denotes all assets, any other non-zero integer must be the id of the asset list to associate to the user.state (str, optional) – The state to associate to the user.
timezone (str, optional) – A timezone other than the system timezone to associate to the user. This will impact all times displayed within the user interface.
title (str, optional) – A title to associate to the user.
update_password (bool, optional) – Should the user be forced to update their password next login? If left unspecified, the default is False.
- Returns
The newly created user.
- Return type
dict
Examples
>>> user = sc.users.create('username', 'password', 1, group=1)
-
delete
(id)[source]¶ Removes a user.
- Parameters
id (int) – The numeric identifier for the user to remove.
- Returns
An empty response.
- Return type
str
Examples
>>> sc.users.delete(1)
-
details
(id, fields=None)[source]¶ Returns the details for a specific user.
- Parameters
id (int) – The identifier for the user.
fields (list, optional) – A list of attributes to return.
- Returns
The user resource record.
- Return type
dict
Examples
>>> user = sc.users.details(1) >>> pprint(user)
-
edit
(id, **kw)[source]¶ Edits a user.
- Parameters
address (str, optional) – Optional street address information to associate to the user.
auth_type (str, optional) – The Authentication type to use for the user. Valid options are
ldap
,legacy
,saml
, andtns
. If left unspecified the default istns
.city (str, optional) – Optional city information to associate to the user.
country (str, optional) – Optional country information to associate to the user.
default_dashboards (bool, optional) – Should the default dashboards be created for the user? If left unspecified, the default is True.
default_reportcards (bool, optional) – Should the default report cards be created for the user? If left unspecified, the default is True.
default_reports (bool, optional) – Should the default reports be created fro the user? If left unspecified, the default is True.
email (str, optional) – The email address to associate to the user.
email_notice (str, optional) – What type of events should generate an email notification? Valid types are
id
,password
,both
,none
.fax (str, optional) – A fax number to associate to the user.
fingerprint (str, optional) – A fingerprint to associate to the user.
firstname (str, optional) – A first name to associate to the user.
group (int, optional) – A group to associate to the user. This parameter is required for users that are not Administrators.
is_locked (bool, optional) – If the account locked? If left unspecified the default is False.
ldap_id (int, optional) – If specifying an LDAP auth type, this is the numeric identifier for the LDAP configuration to use.
managed_usergroups (list, optional) – A list of group ids that the user is allowed to manage users within.
managed_userobjs (list, optional) – A list of group ids that the user is allowed to manage objects within. This includes asset lists, reports, etc.
org (int, optional) – If logged in as an administrator, and creating a security manager account, the organization id must be passed in order to inform Tenable.sc which organization to create the security manager within.
password (str, optional) – The user password
phone (str, optional) – A phone number to associate to the user.
responsibility (int, optional) – The asset list detailing what assets the user is responsible for. A value of
0
denotes all assets, any other non-zero integer must be the id of the asset list to associate to the user.role (int, optional) – The role that should be assigned to this user.
state (str, optional) – The state to associate to the user.
timezone (str, optional) – A timezone other than the system timezone to associate to the user. This will impact all times displayed within the user interface.
title (str, optional) – A title to associate to the user.
update_password (bool, optional) – Should the user be forced to update their password next login? If left unspecified, the default is False.
username (str, optional) – The username for the account
- Returns
The newly updated user.
- Return type
dict
Examples
>>> user = sc.users.edit(1, username='newusername')
-
Common Themes¶
Tenable.sc CRUD within pyTenable¶
pyTenable allows for the ability to leverage both the naturalized inputs as well as passing the raw parameters within the same structure. In some cases this doesn’t seem immediately obvious, however allows for the ability to pass parameters that either haven’t yet been, or in some cases, may never be interpreted by the library.
For example, in the alerts API, you could pass the snake_cased
always_exec_on_trigger
or you could pass what the API endpoint itself
expects, which is executeOnEveryTrigger
. The snake-cased version expects a
boolean value, which will be converted into the string value that camelCased
variant expects. You’ll see this behavior a lot throughout the library, and is
intended to allow you to sidestep most things should you need to. For example,
in the alerts API again, you may not want to pass a trigger as
trigger=('sumip', '>=', '100')
and instead pass as the parameters that are
to be written into the JSON request:
triggerName='sumip', triggerOperator='>=', triggerValue='100'
. Both of
these methods will produce the same JSON request, and the the option is yours
to use the right way for the job.
Along these same lines, its possible to see how the JSON documents are being
constructed by simply looking at the _constructor
methods for each
APIEndpoint class. If pyTenable is getting in your way, you can almost always
sidestep it and pass the exact dictionary you wish to pass on to the API.
Schedule Dictionaries¶
A dictionary detailing the repeating schedule within Tenable.sc. This
dictionary consists of 1 or 3 parameters, depending on the type of schedule.
In all of the definitions except ical
, a single parameter of type
is
passed with lone of the following values: ical
, never
, rollover
, and
template
. If no document is specified, then the default of never
is
assumed. For repeating scans, you’ll have to use the type of ical
and also
specify the start
and repeatRule
parameters as well. The start
parameter is an
iCal DateTime Form #3
formatted string specifying the date and time in which to start the repeating
event. The repeatRule
parameter is an
iCal Recurrance Rule
formatted string.
Example Never Declaration:
{'type': 'never'}
Example daily event starting at 9am Eastern
{
'type': 'ical',
'start': 'TZID=America/New_York:20190214T090000',
'repeatRule': 'FREQ=DAILY;INTERVAL=1'
}
Example weekly event every Saturday at 8:30pm Eastern
{
'type': 'ical',
'start': 'TZID=America/New_York:20190214T203000',
'repeatRule': 'FREQ=WEEKLY;BYDAY=SA;INTERVAL=1'
}
There are detailed instructions in the RFC documentation on how to construct these recurrence rules. Further there are some packages out there to aid in converting more human-readable text into recurrence rules, such as the recurrent package for example.
Raw HTTP Calls¶
Even though the TenableSC
object pythonizes the Tenable.sc API for
you, there may still bee the occasional need to make raw HTTP calls to the
Tenable.sc API. The methods listed below aren’t run through any
naturalization by the library aside from the response code checking. These
methods effectively route directly into the requests session. The responses
will be Response objects from the requests
library. In all cases, the path
is appended to the base url
parameter that the TenableSC
object was
instantiated with.
Example:
resp = sc.get('feed')
-
class
TenableSC
[source] -
get
(path, **kwargs)¶ Initiates an HTTP GET request using the specified path. Refer to
requests.request
for more detailed information on what keyword arguments can be passed:- Parameters
path (str) – The path to be appended onto the base URL for the request.
**kwargs (dict) – Keyword arguments to be passed to the Requests Sessions request method.
- Returns
requests.Response
-
post
(path, **kwargs)¶ Initiates an HTTP POST request using the specified path. Refer to the
requests.request
for more detailed information on what keyword arguments can be passed:- Parameters
path (str) – The path to be appented onto the base URL for the request.
**kwargs (dict) – Keyword arguments to be passed to the Requests Sessions request method.
- Returns
requests.Response
-
put
(path, **kwargs)¶ Initiates an HTTP PUT request using the specified path. Refer to the
requests.request
for more detailed information on what keyword arguments can be passed:- Parameters
path (str) – The path to be appended onto the base URL for the request.
**kwargs (dict) – Keyword arguments to be passed to the Requests Sessions request method.
- Returns
requests.Response
-
delete
(path, **kwargs)¶ Initiates an HTTP DELETE request using the specified path. Refer to the
requests.request
for more detailed information on what keyword arguments can be passed:- Parameters
path (str) – The path to be appended onto the base URL for the request.
**kwargs (dict) – Keyword arguments to be passed to the Requests Sessions request method.
- Returns
requests.Response
-