def bridge(un, pw, host, scanid, repoid, a, s): from tenable.sc import TenableSC sc = TenableSC(host) if un and pw: sc.login(un, pw) if a and s: sc.login(access_key=a, secret_key=s) try: click.echo("\nExporting your Scan ID: {} now\n".format(scanid)) with open('{}.nessus'.format(str(scanid)), 'wb') as nessus: tio.scans.export(scanid, fobj=nessus) click.echo("Importing your Scan into Repo {} at https://{}\n".format( repoid, host)) with open('{}.nessus'.format(str(scanid))) as file: sc.scan_instances.import_scan(file, repoid) # delete the scan os.remove('{}.nessus'.format(str(scanid))) except: pass sc.logout()
def security_center(request, vcr): ''' test fixture for sc(security center) ''' setup_logging_to_file() with vcr.use_cassette('sc_login', filter_post_data_parameters=['username', 'password' ]): tenable_security_center = TenableSC( os.getenv('SC_TEST_HOST', 'securitycenter.home.cugnet.net'), vendor='pytest', product='pytenable-automated-testing') tenable_security_center.login( os.getenv('SC_TEST_USER', 'username'), os.getenv('SC_TEST_PASS', 'password')) tenable_security_center.version # noqa: PLW0104 def teardown(): try: with vcr.use_cassette('sc_login'): tenable_security_center.logout() except NotFoundError as error: log_exception(error) request.addfinalizer(teardown) return tenable_security_center
def upload_file(target_filename): with open(target_filename, 'r') as myfile: sc = TenableSC(SC_HOST_IP) sc.login(access_key=access_key, secret_key=secret_key) file_uploaded = sc.files.upload(myfile) print(file_uploaded) return file_uploaded
def get_info(): # Set User data hostname = "" username = "" password = "" # Set SC object sc = TenableSC(hostname) # login to SC sc.login(username, password) # Get data # check Development tools in chrome -> Network tab --> Under Name, choose analysis --> Headers tab --> Request Payload # EXAMPLE: sc.analysis.vulns(('pluginID', '=', '19506'), ('firstSeen', '=', '0:60'),('repository','=',[{"id" : "1"}]), tool='sumip') current_devices = [] for device in sc.analysis.vulns(('lastSeen', '=', '0:30'), tool='sumip'): current_devices.append(device) # logout of SC sc.logout() return render_template('index.html', current_devices=current_devices)
def tsc_login(): try: sc = TenableSC(sc_address, port=sc_port) sc.login(access_key=sc_access_key, secret_key=sc_secret_key) except (NameError) as err: print("Please verify connection details.") exit() except (ConnectionError) as err: raise SystemExit(err) return sc
def admin(request, vcr): with vcr.use_cassette('sc_login', filter_post_data_parameters=['username', 'password']): sc = TenableSC(os.getenv('SC_TEST_HOST', 'securitycenter.home.cugnet.net')) sc.login( os.getenv('SC_TEST_ADMIN_USER', 'admin'), os.getenv('SC_TEST_ADMIN_PASS', 'password')) def teardown(): with vcr.use_cassette('sc_login'): sc.logout() request.addfinalizer(teardown) return sc
def main(): hostip = '<IP>' username = '******' password = '******' sc = TenableSC(hostip) sc.login(username, password) for item in sc.get('scanResult').json()['response']['manageable']: if 'Running' in item['status']: print('{id}: {name}'.format(**item)) sc.logout()
def run(self): if len(sys.argv) != 3: print( "Usage: python2 sc-scan-webhook.py [scan ID] 'target list to add to message text sent in webhook'" ) sys.exit(0) scanID = sys.argv[1] targetTXT = sys.argv[2] try: sc = TenableSC(self.ip) print("Logging in to SecurityCenter") response = sc.login(self.login, self.password) targets = targetTXT print('targets set: ' + targets) results = self.run_scan(sc, targets, scanID) sc.logout() except Exception as ex: print('Error: ' + str(ex))
def sc(request, vcr): with vcr.use_cassette('sc_login', filter_post_data_parameters=['username', 'password']): sc = TenableSC(os.getenv('SC_TEST_HOST', 'securitycenter.home.cugnet.net'), vendor='pytest', product='pytenable-automated-testing') sc.login(os.getenv('SC_TEST_USER', 'username'), os.getenv('SC_TEST_PASS', 'password')) def teardown(): with vcr.use_cassette('sc_login'): sc.logout() request.addfinalizer(teardown) return sc
def run(self): Analyzer.run(self) if self.data_type != 'ip' and self.data_type != 'fqdn': self.error('Invalid data type') try: sc = TenableSC(self.ip) sc.login(self.login, self.password) results = self._run_scan(sc) sc.logout() except Exception as ex: self.error('Error: %s' % ex) self.report(results)
def ConnectSC(DEBUG, username, password, host, port): #Create the connection to Tenable.sc try: sc = TenableSC(host, port=port) except: print("Error connecting to SecurityCenter", sys.exc_info()[0], sys.exc_info()[1]) return (False) try: sc.login(username, password) except: print("Error logging into to SecurityCenter", sys.exc_info()[0], sys.exc_info()[1]) if DEBUG: print("Username:", username) return (False) return (sc)
def admin(request, vcr): ''' test fixture for admin ''' with vcr.use_cassette('sc_login', filter_post_data_parameters=['username', 'password' ]): sc = TenableSC( # noqa: PLC0103 os.getenv('SC_TEST_HOST', 'securitycenter.home.cugnet.net'), vendor='pytest', product='pytenable-automated-testing') sc.login( os.getenv('SC_TEST_ADMIN_USER', 'admin'), os.getenv('SC_TEST_ADMIN_PASS', 'password')) sc.version # noqa: PLW0104 def teardown(): with vcr.use_cassette('sc_login'): sc.logout() request.addfinalizer(teardown) return sc
def main(): # create an instance of the API and login sc = TenableSC(SC_HOST_IP) sc.login(access_key=sc_accessKey, secret_key=sc_secretKey) # run the diagnostic scan scan_result_id = sc.scans.launch(id=active_scan_id, diagnostic_target=target_ip, diagnostic_password=diagnostic_password)['scanResult']['id'] print(f"Launched diagnostic scan run of Active Scan {active_scan_id}, with Scan Result ID {scan_result_id}.") # wait until the scan is finished wait_time_seconds = 0 while wait_time_seconds < SCAN_MAX_WAIT_SECONDS: if is_scan_completed(sc, scan_result_id): print(f"Scan finished running after waiting {wait_time_seconds} seconds.") break else: print(f"Waited {wait_time_seconds} seconds, scan is still running.") time.sleep(SCAN_REFRESH_DELAY_SECONDS) wait_time_seconds += SCAN_REFRESH_DELAY_SECONDS if wait_time_seconds > SCAN_MAX_WAIT_SECONDS: print("ERROR: Script timed out waiting for the scan to complete.") exit(-1)
def test_log_in(vcr): ''' test log in ''' tsc = TenableSC(url='https://localhost') tsc._version = '5.12.0' with pytest.raises(ConnectionError): tsc.login(access_key='access_key', secret_key='secret_key') tsc._version = '5.14.0' tsc.login(access_key='access_key', secret_key='secret_key') assert tsc._auth_mech == 'keys' tsc._version = None tsc._auth_mech = None with vcr.use_cassette('sc_login_5_20_0'): tsc.login(access_key='access_key', secret_key='secret_key') assert tsc._auth_mech == 'keys'
""" The tag you want to delete is the first argument on the command line. For example: rm_dyn_ls.py acme """ tagg = sys.argv[1] """ Put access key in file called acc.key. Just the key, one line. Don't press enter. Just save. Put secret key in a file called sec.key. Just the key, one line. The next 2 lines read your access and secret keys so you don't have to expose them in your code. """ accesskey = open('acc.key').read().strip() secretkey = open('sec.key').read().strip() sc = TenableSC('127.0.0.1', port=8443) sc.login(access_key = accesskey, secret_key = secretkey) """ Read manageable asset lists into sclist then obtain the length of the list and assign it to total. total will be the range for our inner loop. We use i to count and compare to total so we know when to break out of the loop. We loop through sclist to obtain the asset list id, then use the id in the call to sc.asset_lists.details() to get that list's tag. tag is not in sc.asset_lists so we have to make the call to the .details method. Once we have identified an asset list with the target tag, we call the .delete() method and pass it the id. You can also us the usable asset lists as well.... but it seems that manageable asset lists are a super set. manageable = read write usable = read only """ i = 0 """ I make two calls to TSC below. This first call, sclist = sc.asset_lists.list() puts all asset lists into sclist. Next, in the loops
def run_module(): module_args = dict( asset_name=dict(type='str', required=True), asset_type=dict(type='str', required=True), targets=dict(type='str', required=False, default='.*'), file_location=dict(type='str', required=True), server=dict(type='str', required=True), nessus_username=dict(type='str', required=True), nessus_password=dict(type='str', required=True) ) result = dict( changed=False, original_message='', message='' ) module = AnsibleModule( argument_spec=module_args, supports_check_mode=True ) if not HAS_PYTENABLE: module.fail_json(msg = 'pyTenable required. pip install pytenable') if not HAS_PANDAS: module.fail_json(msg = 'Pandas required. pip install panda') if module.check_mode: module.exit_json(**result) asset_name = module.params['asset_name'] asset_type = module.params['asset_type'] targets = module.params['targets'] file_location = module.params['file_location'] server = module.params['server'] nessus_username = module.params['nessus_username'] nessus_password = module.params['nessus_password'] try: sc = TenableSC(server) sc.login(nessus_username, nessus_password) except: module.fail_json(msg='Issues connecting to Nessus.sc. Please check connectivity and credetials') try: df = pd.read_csv(file_location,low_memory=False) except: module.fail_json(msg='Issues loading CSV file' + file_location) asset_list = sc.asset_lists.list()['usable'] asset_id = [item for item in asset_list if item["name"] == asset_name] # overwrite existing asset list if asset_id: sc.asset_lists.delete(int(asset_id[0]['id'])) if asset_type.lower() == 'dns': host_list = list(df[df['hostname'].str.contains(pat=targets)]['hostname']) try: sc.asset_lists.create(asset_name,list_type='dnsname',dns_names=host_list) except: module.fail_json(msg="Error creating Nessus asset list [" + asset_name + "]") elif asset_type.lower() == 'ip': ip_list = list(df[df['ip'].str.contains(pat=targets)]['ip']) try: sc.asset_lists.create(asset_name,list_type='static',ips=ip_list) except: module.fail_json(msg="Error creating Nessus asset list [" + asset_name + "]") result['changed'] = True result['output'] = "Nessus.sc Asset list name: [" + asset_name + "]" module.exit_json(**result)
def dnp3_TCP_header_probe(**kwargs): sc = TenableSC(CONFIG['tenable_ip'], port=CONFIG['tenable_port']) try: sc.login(CONFIG['tenable_username'], CONFIG['tenable_password']) except tenable_errors.APIError as APIerror: _log.debug("Tenable API error: " + str(APIerror)) return { 'TARGET_IPADDR': kwargs['TARGET_IPADDR'], 'SCAN_NAME': 'dnp3_TCP_header_probe', 'SCAN_RESULT': -1, 'SCAN_RESULT_DESC': json.loads(APIerror.response.text)['error_msg'] } sc.scans.edit(1, targets=[kwargs['TARGET_IPADDR']]) running = sc.scans.launch(1) scan_results_id = int(running['scanResult']['id']) scan_status = sc.scan_instances.details(scan_results_id, fields=['status']) while scan_status['status'] != 'Completed': time.sleep(15) scan_status = sc.scan_instances.details(scan_results_id, fields=['status']) if scan_status['status'] == 'Partial' or scan_status[ 'status'] == 'Error': scan_error = sc.scan_instances.details(scan_results_id, fields=['errorDetails']) return { 'TARGET_IPADDR': kwargs['TARGET_IPADDR'], 'SCAN_NAME': 'dnp3_TCP_header_probe', 'SCAN_RESULT': -1, 'SCAN_RESULT_DESC': str(scan_error) } time.sleep(15) # Give Tenable.sc some time to generate scan results filename = str(scan_results_id) + "_" + str( kwargs['TARGET_IPADDR']) + "tcp_scan_data.zip" unzipped_filename = str(scan_results_id) + ".nessus" with open(filename, 'wb') as fobj: sc.scan_instances.export_scan(scan_results_id, fobj) if zipfile.is_zipfile(filename): with zipfile.ZipFile(filename, 'r') as zipf: zipf.extractall("./") mydoc = minidom.parse(unzipped_filename) else: mydoc = minidom.parse(filename) report_items = mydoc.getElementsByTagName('ReportItem') results = dict.fromkeys([ 'TARGET_IPADDR', 'SCAN_NAME', 'TTL', 'WINDOW', 'SCALE', 'SACK', 'TIMESTAMP', 'TCP_SIG', 'SCAN_RESULT', 'SCAN_RESULT_DESC' ]) results['TARGET_IPADDR'] = kwargs['TARGET_IPADDR'] results['SCAN_NAME'] = 'dnp3_TCP_header_probe' plugin_found = False for elem in report_items: if elem.attributes['pluginID'].value == '999999': plugin_found = True plugin_output = elem.getElementsByTagName( 'plugin_output')[0].childNodes[0].data sig = plugin_output.split("Signature:")[1].lstrip().rstrip() if plugin_found: results['SCAN_RESULT'] = 1 results['SCAN_RESULT_DESC'] = 'Success' new_sig = sig.split(':')[1:3] + sig.split(':')[4:] results['TCP_SIG'] = ':' for part in new_sig: results['TCP_SIG'] = results['TCP_SIG'] + part + ':' results['TCP_SIG'] = results['TCP_SIG'][:-1] results['TTL'] = sig.split(':')[3] results['WINDOW'] = sig.split(':')[4] if 'W' in sig.split(':')[5]: results['SCALE'] = sig.split(':')[6] else: results['SCALE'] = 'N' if 'S' in sig.split(':')[5]: results['SCALE'] = 'Y' else: results['SACK'] = 'N' if 'T' in sig.split(':')[5]: results['TIMESTAMP'] = 'Y' else: results['TIMESTAMP'] = 'N' os.remove(filename) os.remove(unzipped_filename) return results
def snmp_device_info(**kwargs): sc = TenableSC(CONFIG['tenable_ip'], port=CONFIG['tenable_port']) try: sc.login(CONFIG['tenable_username'], CONFIG['tenable_password']) except tenable_errors.APIError as APIerror: _log.error("Tenable API error: " + str(APIerror)) return { 'TARGET_IPADDR': kwargs['TARGET_IPADDR'], 'SCAN_NAME': 'snmp_device_info', 'SCAN_RESULT': -1, 'SCAN_RESULT_DESC': json.loads(APIerror.response.text)['error_msg'] } sc.scans.edit(3, targets=[kwargs['TARGET_IPADDR']]) running = sc.scans.launch(3) scan_results_id = int(running['scanResult']['id']) scan_status = sc.scan_instances.details(scan_results_id, fields=['status']) while scan_status['status'] != 'Completed': time.sleep(15) scan_status = sc.scan_instances.details(scan_results_id, fields=['status']) if scan_status['status'] == 'Partial' or scan_status[ 'status'] == 'Error': scan_error = sc.scan.instances.details(scan_results_id, fields=['errorDetails']) return { 'TARGET_IPADDR': kwargs['TARGET_IPADDR'], 'SCAN_NAME': 'snmp_device_info', 'SCAN_RESULT': -1, 'SCAN_RESULT_DESC': str(scan_error) } time.sleep(15) # Give Tenable.sc some time to generate scan results filename = str(scan_results_id) + "_" + str( kwargs['TARGET_IPADDR']) + "tcp_scan_data.zip" unzipped_filename = str(scan_results_id) + ".nessus" with open(filename, 'wb') as fobj: sc.scan_instances.export_scan(scan_results_id, fobj) if zipfile.is_zipfile(filename): with zipfile.ZipFile(filename, 'r') as zipf: zipf.extractall("./") mydoc = minidom.parse(unzipped_filename) else: mydoc = minidom.parse(filename) report_items = mydoc.getElementsByTagName('ReportItem') results = dict.fromkeys([ 'TARGET_IPADDR', 'SCAN_NAME', 'VENDOR', 'MODEL', 'SCAN_RESULT', 'SCAN_RESULT_DESC' ]) found_known_device = False for elem in report_items: if elem.attributes['pluginID'].value == '10800': plugin_output = elem.getElementsByTagName( 'plugin_output')[0].childNodes[0].data for line in plugin_output.split('\n'): #TODO: Refactor this to use utils.py with a dictionary of values associated with searchable strings if '7UT613' in line: found_known_device = True results['MODEL'] = '7UT613' results['VENDOR'] = 'siemens' if '7SJ64' in line: found_known_device = True results['MODEL'] = '7SJ64' results['VENDOR'] = 'siemens' if found_known_device == True: results['SCAN_RESULTS'] = 1 results['SCAN_RESULTS_DESC'] = 'Success' else: results['SCAN_RESULTS'] = 0 results[ 'SCAN_RESULTS_DESC'] = 'Could not determine identity of device at {} from SNMP device info'.format( kwargs['TARGET_IPADDR']) results['TARGET_IPADDR'] = kwargs['TARGET_IPADDR'] results['SCAN_NAME'] = 'snmp_device_info' os.remove(filename) os.remove(unzipped_filename) return results
def tenablelol(user1, pass1): sc = TenableSC('tenable.partners.org') sc.login(user1, pass1) for rule in sc.accept_risks.list(): print(rule)
#!/usr/bin/env python3 #Disclaimer: This is NOT supported By Tenable! #This script reaches out to Tenable IO and pulls down all of the current IPs of any Agent #Then pushes those IPs into a Static IP address list in Security Center. from tenable.sc import TenableSC from tenable.io import TenableIO sc = TenableSC("") sc.login("", "") tio = TenableIO(access_key='', secret_key='') #Get Agent IPs from Tenable.io def get_ips(): #great an empty list list = [] for agent in tio.agents.list(): ip = agent['ip'] list.append(ip) return list def get_or_create(): #load all of the current asset lists for parsing asset_lists = sc.asset_lists.list() #grab the latest agent IPs from Tenable.io list = get_ips()
def main(): if not config: print('Creating new config file \u2026 ', end='') save(create_new()) print('Created') print('Edit the configuration file with the appropriate information and re-run.') exit() start = time.time() connected = False SC = None while time.time() < start + 60: import logging try: logging.getLogger().setLevel(logging.NOTSET) print(f"Looking for SecurityCenter at: '{config.hostname}' \u2026 ", end='') SC = TenableSC(config.hostname) print('Found.') access_type, (access_name, access_secret) = config.get() if access_type == 'api': print(f"Attempting to log in with API Key \u2026 ", end='') SC.login(access_key=access_name, secret_key=access_secret) else: print(f"Attempting to log in as: '{access_name}' \u2026 ", end='') SC.login(user=access_name, passwd=access_secret) logged_in = False try: logged_in = isinstance(SC.status.status(), dict) except tenable.errors.APIError: pass if logged_in: print('Logged In.') connected = True break else: print() except tenable.errors.ConnectionError as err: print(f'{err.msg}\tRetrying for {round(start + 60 - time.time())} more seconds.') time.sleep(2) except tenable.errors.APIError as err: print(err.response.json()['error_msg']) break except Exception as err: raise err finally: logging.getLogger().setLevel(logging.WARNING) if not connected: print(f'Unable to connect to {config.hostname}') if isinstance(SC, tenable.sc.TenableSC) and 'X-SecurityCenter' in SC.session.headers: SC.logout() exit(1) def loop(): global exit_loop while True: key = getKey() if key == 'q': with threading.Lock(): exit_loop = True print('Quitting \u2026') break thread = threading.Thread(name='GetKey Thread', target=loop, daemon=True) display = None thread.start() global exit_loop exit_loop = False while True: current_loop = time.time() if display: os.system('cls' if os.name == 'nt' else 'clear') print(display, end='\r\n') print("Press 'q' to quit.", end='\r\n') display_updated = False while time.time() < current_loop + 5: if not display_updated: if not exit_loop: running_scans = SC.get('scanResult?filter=running&fields=id').json()['response']['manageable'] if not exit_loop: try: running_scans = [SC.scan_instances.details(int(scan_id['id'])) for scan_id in running_scans] except tenable.errors.APIError: running_scans = [] if not exit_loop: for index in range(len(running_scans)): try: running_scans[index]['scan'] = SC.scans.details(running_scans[index]['scan']['id']) except tenable.errors.APIError: pass if not exit_loop: display = all_scans_display(running_scans=running_scans) display_updated = True if exit_loop: logged_in = False try: logged_in = isinstance(SC.status.status(), dict) except tenable.errors.APIError: pass if logged_in: SC.logout() exit()
#!/usr/bin/env python3 #Disclaimer: This is NOT supported By Tenable! #This script pull the licensing information from SC from tenable.sc import TenableSC sc = TenableSC("1.1.1.1") sc.login("admin", "password") def status_Check(): sc_license = sc.status.status() active_ips = sc_license['activeIPs'] licensed_ips = sc_license['licensedIPs'] utilization = int(100 * int(active_ips) / int(licensed_ips)) print("Your License Status") print("-------------------") print("Your Purchased license for this SC is : {} ".format(licensed_ips)) print("Your License Usage is : {} ".format(active_ips)) print("Your current utilization is : {}% ".format(utilization)) if __name__ == '__main__': status_Check()
from email.mime.text import MIMEText import smtplib import datetime from tenable.sc import TenableSC import logging logging.basicConfig( filename='app.log', level=logging.DEBUG, format='%(asctime)s - %(name)s - %(levelname)s - %(message)s', datefmt='%d-%b-%y %H:%M:%S') #Log in security center securityCenter = TenableSC() print("Logging into Security Center") securityCenter.login('', '') logging.info('Signed into Tenable') #create a dictionary for month conversion monthConversion = { 'Jan': '1', 'Feb': '2', 'Mar': '3', 'Apr': '4', 'May': '5', 'Jun': '6', 'Jul': '7', 'Aug': '8', 'Sep': '9', 'Oct': '10', 'Nov': '11',
from tenable.sc import TenableSC from pprint import pprint import getpass import logging #logging.basicConfig(level=logging.DEBUG) ''' sc登录设置 仅需替换SC地址 ==> TenableSC("192.168.0.51") ''' sc = TenableSC("192.168.0.70") # 替换SC地址 username = input('Input Username: '******'Input Password: '******'scan', '111') #使用固定的用户名、密码 for tup in list(enumerate(sc.asset_lists.list( fields=['name', 'ipCount'])['usable'])): if int(tup[1]['ipCount']) != 0: print(tup) asset_id = input("\n输入上表中的资产'id': ") _ = input('是否打印Repo名称? [Y/N]') if _.lower() == 'y':
#!/usr/bin/env python from tenable.sc import TenableSC # Login to Tenable.sc sc = TenableSC('ADDRESS') sc.login('USERNAME', 'PASSWORD') # Build the Counter Dictionary sevs = {'Critical': 0, 'High': 0, 'Medium': 0, 'Low': 0} # Iterate through the Vulnerability Summary, counting up the vulns based on\ # criticality. for vuln in sc.analysis.vulns(('severity', '=', '4,3,2,1'), tool='sumid'): if vuln['severity']['name'] in sevs: sevs[vuln['severity']['name']] += 1 # Output the final counts: print('Crits : {Critical}\nHighs : {High}\nMediums : {Medium}\nLows : {Low}'. format(**sevs))
#!/usr/bin/env python3 #Disclaimer: This is NOT supported By Tenable! #This script downloads all the all-2.0.tar file using the special URL provided in the offline updates document #https://docs.tenable.com/sccv/5_8/Content/OfflineNessusPluginUpdate.htm #https://docs.tenable.com/sccv/5_8/Content/OfflineSCFeedUpdate.htm #This script changes the name of the all-2.0.tar to the supported names and imports them in to T.sc from tenable.sc import TenableSC import requests sc = TenableSC('192.168.128.22') sc.login('admin', "password") url = 'special url' plugins = requests.get(url) open('sc-plugins-diff.tar.gz', 'wb').write(plugins.content) with open('sc-plugins-diff.tar.gz', 'rb') as pubfile: print(sc.feeds.process('active', pubfile)) open('SecurityCenterFeed48.tar.gz', 'wb').write(plugins.content) with open('SecurityCenterFeed48.tar.gz', 'rb') as feed: print(sc.feeds.process('sc', feed)) sc.logout()
try: if args.tsc_port[0] != "": tsc_port = args.tsc_port[0] except: pass try: import_repo = int(args.import_repo[0]) except: print("Invalid repo ID") exit(-1) # Create the connection to whatever platform has been specified. conn = connector.connect() sc = TenableSC(tsc_host, port=tsc_port) sc.login(tsc_username, tsc_password) if conn is False: print("Unable to connect.") exit(-1) scan_list = connector.list_scans() if scan_list is False: print("Could not get scan list.") exit(-1) for scan in scan_list: if connector.export_scan(scan['id']) is True: print("Uploading file to Tenable.sc repo ID",import_repo) with open(str(scan['id'])+".nessus") as nessus_file: response = sc.scan_instances.import_scan(nessus_file, import_repo)
# -*- coding: utf-8 -*- """ Ed Matthews 10-9-19 Tenable python connection test """ from tenable.sc import TenableSC sc = TenableSC('insert your tenable url here') sc.login('login', 'password') for vuln in sc.analysis.vulns(): ('listos', '=', 'Windows') # Change above OS print(vuln)
from tenable.sc import TenableSC import csv import os import time sc = TenableSC('SC IP address') sc.login('username', 'password') def callRecastFunction(recast_payload, pluginList): for x in range(0, len(pluginList)): recast_payload["plugin"]["id"] = pluginList[x] print(recast_payload) sc.post('recastRiskRule', json=recast_payload) def load_RecastFile(): flag = 0 recast_payload = {} #repositories=[] pluginList = [] newSeverity = {} hostType = "" port = "" protocol = "" comments = "" if os.path.exists('x/home/radpai/recast.csv'): with open('x/home/radpai/recast.csv') as RecastFile: reader = csv.reader(RecastFile) for row in reader:
from tenable.sc import TenableSC from zipfile import ZipFile SC_HOST_IP = '192.168.50.12' # the IP address of the Tenable.SC server accessKey = '' secretKey = '' """ This script takes a given plugin ID and source_hostname/IP. It then uses the Tenable.SC API to find the last observed date for the vuln on that target, and identifies the exact scan result it's from, as well as information on the Active Scan, Scan Policy, and Audit File, if applicable. """ # create an instance of the API and login sc = TenableSC(SC_HOST_IP) sc.login(access_key=accessKey, secret_key=secretKey) SCAN_TIME_THRESHOLD = 600 # the number of seconds before or after the timestamp to look for a Scan finish/import time logging.basicConfig( filename='last_observed.log', level=logging.DEBUG, format="%(asctime)-15s [%(levelname)s]: %(message)s", ) logging.getLogger('requests').setLevel(logging.WARNING) logging.getLogger("urllib3").setLevel(logging.WARNING) def get_last_observed(sc, plugin_id: str, ip: str) -> str: filters = [("pluginID", "=", plugin_id), ("ip", "=", ip)]