def status():

    res = {'page': 'status', "scans": this.scans}

    if table.count(Query().status == 'SCANNING') == APP_MAXSCANS:
        this.scanner['status'] = "BUSY"
        res.update({
            "status": "BUSY",
            "reason": "Max concurrent active scans reached ({})".format(APP_MAXSCANS)
        })
        return jsonify(res)

    # Check if the remote service is available
    try:
        scan = {}
        if 'access_key' in this.scanner.keys() and 'secret_key' in this.scanner.keys():
            scan = ness6rest.Scanner(
                url="https://{}:{}".format(this.scanner['server_host'], this.scanner['server_port']),
                api_akey=this.scanner['access_key'],
                api_skey=this.scanner['secret_key'],
                insecure=True)
        elif 'server_username' in this.scanner.keys() and 'server_password' in this.scanner.keys():
            scan = ness6rest.Scanner(
                url="https://{}:{}".format(this.scanner['server_host'], this.scanner['server_port']),
                login=this.scanner['server_username'],
                password=this.scanner['server_password'],
                insecure=True)
        if 'status' in scan.res.keys():
            this.scanner['status'] = "READY"
            res.update({
                'status': 'READY',
                'details': {
                    'server_host': this.scanner['server_host'],
                    'server_port': this.scanner['server_port'],
                    'status': scan.res['status']
                }
            })
        elif scan.res['scanners'][0]['status'] == "on":
            this.scanner['status'] = "READY"
            res.update({
                'status': 'READY',
                'details': {
                    'server_host': this.scanner['server_host'],
                    'server_port': this.scanner['server_port'],
                    'engine_version': scan.res['scanners'][0]['engine_version'],
                    'engine_build': scan.res['scanners'][0]['engine_build'],
                    'scan_count': scan.res['scanners'][0]['scan_count']
                }
            })
        else:
            this.scanner['status'] = "ERROR"
            res.update({'status': 'ERROR', 'details': {'reason': 'Nessus engine not available'}})
    except Exception:
        this.scanner['status'] = "ERROR"
        res.update({'status': 'ERROR', 'details': {'reason': 'Nessus engine not available'}})
    return jsonify(res)
def _loadconfig():
    conf_file = BASE_DIR + '/nessus.json'
    if os.path.exists(conf_file):
        json_data = open(conf_file)
        this.scanner = json.load(json_data)
        os.environ['NO_PROXY'] = this.scanner["server_host"]
    else:
        app.logger.debug("Error: config file '{}' not found".format(conf_file))
        return {
            "status": "error",
            "details": {
                "reason": "config file not found"
            }
        }

    try:
        # Check authentication methods (login/pass vs. api)
        if 'access_key' in this.scanner.keys(
        ) and 'secret_key' in this.scanner.keys():
            this.nessscan = ness6rest.Scanner(
                url="https://{}:{}".format(this.scanner['server_host'],
                                           this.scanner['server_port']),
                api_akey=this.scanner['access_key'],
                api_skey=this.scanner['secret_key'],
                insecure=True)
        elif 'server_username' in this.scanner.keys(
        ) and 'server_password' in this.scanner.keys():
            this.nessscan = ness6rest.Scanner(
                url="https://{}:{}".format(this.scanner['server_host'],
                                           this.scanner['server_port']),
                login=this.scanner['server_username'],
                password=this.scanner['server_password'],
                insecure=True)
        if this.nessscan.res['scanners'][0]['status'] == "on":
            return {"status": "success"}
        else:
            return {
                "status": "error",
                "details": {
                    "reason":
                    "connection error to Nessus instance (bad credz? not available ?)"
                }
            }
    except Exception:
        return {
            "status": "error",
            "details": {
                "reason":
                "connection error to Nessus instance (bad credz? not available ?)"
            }
        }
def _loadconfig():
    conf_file = BASE_DIR + '/nessus.json'
    if os.path.exists(conf_file):
        json_data = open(conf_file)
        this.scanner = json.load(json_data)
        os.environ['NO_PROXY'] = this.scanner["server_host"]
    else:
        print("Error: config file '{}' not found".format(conf_file))
        return {"status": "error", "reason": "config file not found"}

    try:
        this.nessscan = ness6rest.Scanner(
            url="https://{}:{}".format(this.scanner['server_host'],
                                       this.scanner['server_port']),
            login=this.scanner['server_username'],
            password=this.scanner['server_password'],
            insecure=True)
        if this.nessscan.res['scanners'][0]['status'] == "on":
            return {"status": "success"}
        else:
            return {
                "status":
                "error",
                "reason":
                "connection error to Nessus instance (bad credz? not available ?)"
            }
    except:
        return {
            "status":
            "error",
            "reason":
            "connection error to Nessus instance (bad credz? not available ?)"
        }
Exemple #4
0
def download_nessus_report(args, keys):
    nessus_url = "https://" + args.nessusserver + ":" + str(args.nessusport)
    scanner = None
    scanner = ness6rest.Scanner(url=nessus_url, api_akey=keys['accessKey'], api_skey=keys['secretKey'], insecure=args.nessusinsecure)
    if scanner:
        print "API login succeeded"
        scanner.action(action='scans', method='get')
        if not len( scanner.res['scans']) > 0:
            print "Did not find any available scans!"
            sys.exit(1)
        scans = scanner.res['scans']
        folders = scanner.res['folders']
        #we dont want scans from trash folder
        for f in folders:
            if f['type'] == 'trash':
                trash_id=f['id']

        #iterate through scans, drop crap from the trash folder
        found_scan = False
        for s in scans:
            if s['folder_id'] != trash_id:
                scanner.scan_name = s['name']
                scanner.scan_id = s['id']

                #only export if the scan is completed and if it's the correct scan
                if (s['status'] == 'completed') and (scanner.scan_name == args.nessusscanname):
                    found_scan = True
                    with io.open(args.nessustmp + '/' + args.nessusscanname, 'wb') as fp:
                        print "Found valid scan, Writing output file to tmp directory"
                        fp.write(scanner.download_scan(export_format='nessus'))
                        fp.close()

        if not found_scan:
            print "Did not find any scan to export. Maybe it wasn\'t done yet or be sure to check the scanname or API file and try again."
            sys.exit(1)
 def __init__(self, cfg):
     self._url = cfg.nessusurl
     self._akey = cfg.nessusakey
     self._skey = cfg.nessusskey
     self._enrich = ScanAPIEnrich(cfg.rpm2cve, cfg.exemptplugins)
     insecure = False
     if not cfg.nessusverifycert:
         insecure = True
     self._scanner = ness6rest.Scanner(url=self._url, api_akey=self._akey, api_skey=self._skey,
             insecure=insecure)
Exemple #6
0
 def __init__(self):
     self.anessus = ness6rest.Scanner(url='https://127.0.0.1:8834',
                                      login='******',
                                      password='******',
                                      insecure=True)
     self.policy = False
     self.username = ''
     self.pw = ''
     self.scanning_queue = Queue.Queue()
     self.targets = []
Exemple #7
0
def nessus_intagrator(hosts):

    scan = ness6rest.Scanner(url="https://192.168.25.125:8834",
                             login="******",
                             password="******",
                             insecure=True)

    for h in range(len(hosts)):
        scan.scan_add(targets=hosts[i])
        scan.scan_run()
Exemple #8
0
 def __init__(self, cfg):
     self._url = cfg.nessusurl
     self._akey = cfg.nessusakey
     self._skey = cfg.nessusskey
     self._enrich = ScanAPIEnrich(cfg.rpm2cve, cfg.exemptplugins)
     caoption = ''
     insecure = True
     if cfg.nessuscacert != None:
         caoption = cfg.nessuscacert
         insecure = False
     self._scanner = ness6rest.Scanner(url=self._url,
                                       api_akey=self._akey,
                                       api_skey=self._skey,
                                       insecure=insecure,
                                       ca_bundle=caoption)
def status():
    res = {'page': 'status', "scans": this.scans}

    if len(this.scans) == APP_MAXSCANS:
        this.scanner['status'] = "BUSY"
        res.update({
            "status":
            "BUSY",
            "reason":
            "Max concurrent active scans reached ({})".format(APP_MAXSCANS)
        })
        return jsonify(res)

    # check if the remote service is available
    try:
        scan = ness6rest.Scanner(url="https://{}:{}".format(
            this.scanner['server_host'], this.scanner['server_port']),
                                 login=this.scanner['server_username'],
                                 password=this.scanner['server_password'],
                                 insecure=True)
        if scan.res['scanners'][0]['status'] == "on":
            this.scanner['status'] = "READY"
            res.update({
                'status': 'READY',
                'details': {
                    'server_host': this.scanner['server_host'],
                    'server_port': this.scanner['server_port'],
                    'server_username': this.scanner['server_username'],
                    'engine_version':
                    scan.res['scanners'][0]['engine_version'],
                    'engine_build': scan.res['scanners'][0]['engine_build'],
                    'scan_count': scan.res['scanners'][0]['scan_count']
                }
            })
        else:
            this.scanner['status'] = "ERROR"
            res.update({
                'status': 'ERROR',
                'reason': 'Nessus engine not available'
            })
    except:
        this.scanner['status'] = "ERROR"
        res.update({
            'status': 'ERROR',
            'reason': 'Nessus engine not available'
        })
    return jsonify(res)
Exemple #10
0
def run_nessus_scan(args):
    log.info("Initiating nessus scan using the ips in {}".format(args.input_file))
    targets = []
    with open(args.input_file, 'r') as fp:
        for line in fp:
            line = line.strip(' \t\n\r')
            targets.append(line)
    nessus_targets = ','.join(targets)
    log.debug("Nessus will scan these ips: {}".format(nessus_targets))
    scan = ness6rest.Scanner(
        url=config.NESSUS_URL,
        api_akey=config.NESSUS_ACCESS_KEY,
        api_skey=config.NESSUS_SECRET_KEY,
        insecure=True)
    scan.scan_add(nessus_targets, template='basic', name=args.scan_name)
    res = scan.scan_run()
    log.info(res)
Exemple #11
0
def download_files(profile, dl_id, user_format, dbpasswd=""):
    # Downloader, props to Nessrest :)
    nessus_url = "https://" + profile["url"] + ":" + profile["port"]
    insecure = True
    scanner = ness6rest.Scanner(url=nessus_url,
                                api_akey=profile["akey"],
                                api_skey=profile["skey"],
                                insecure=insecure,
                                ca_bundle=None)
    if scanner:
        scanner.action(action='scans', method='get')
        folders = scanner.res['folders']
        scans = scanner.res['scans']
        folders_id = []
        for i in folders:
            if str(i['id']) == str(dl_id):
                folders_id.append(i)
        for f in folders_id:
            if not os.path.exists(f['name']):
                os.mkdir(f['name'])
        for i in folders_id:
            for s in scans:
                if s['folder_id'] == i['id']:
                    scanner.scan_name = s['name']
                    scanner.scan_id = s['id']
                    folder_name = i['name']
                    folder_type = i['type']
                    if folder_type == 'trash':
                        continue
                    if s['status'] == 'completed':
                        file_name = '%s_%s.%s' % (scanner.scan_name,
                                                  scanner.scan_id, user_format)
                        file_name = file_name.replace('\\', '_')
                        file_name = file_name.replace('/', '_')
                        file_name = file_name.strip()
                        relative_path_name = folder_name + '/' + file_name
                        # PDF not yet supported
                        with io.open(relative_path_name, 'wt') as fp:
                            fp.write(
                                str(
                                    scanner.download_scan(
                                        export_format=user_format,
                                        dbpasswd=dbpasswd)))
Exemple #12
0
    def run(self):
        Analyzer.run(self)

        data = self.get_param('data', None, 'Data is missing')

        if self.data_type != 'fqdn' and self.data_type != 'ip':
            self.error('Invalid data type')

        if self.allowed_networks is not None:
            if self.data_type == 'fqdn':
                address = IPAddress(socket.gethostbyname(data))
            else:
                try:
                    address = IPAddress(data)
                except Exception as e:
                    self.error("{}".format(e))
            if not any(address in IPNetwork(network)
                       for network in self.allowed_networks):
                self.error('Invalid target: not in any allowed network')

        scanner_args = {
            'url': self.url,
            'login': self.login,
            'password': self.password
        }
        if self.ca_bundle is not None:
            scanner_args.update({'ca_bundle': self.ca_bundle})
        else:
            scanner_args.update({'insecure': True})

        try:
            scanner = ness6rest.Scanner(**scanner_args)
            scanner.policy_set(name=self.policy)
            scanner.scan_add(targets=data, name="cortex scan for " + data)

            self._run_scan(scanner)
            results = self._get_scan_results(scanner)
            self._delete_scan(scanner)
        except Exception as ex:
            self.error('Scanner error: %s' % ex)

        self.report(results)
Exemple #13
0
def startscan(args):
    scan = ness6rest.Scanner(url=args['hosturl'],
                             login=args['user'],
                             password=args['password'],
                             insecure=True)
    targets = parse_nmapxml(args['filename'])
    scan.upload(args['filename'])
    filename = scan.res[u'fileuploaded']
    scan.policy_exists(args['policy'])
    scan.policy_set(args['policy'])
    settings = {"settings": {}}
    settings["settings"].update({"import_nmap_xml": "yes"})
    settings["settings"].update({"import_nmap_xml_file": filename})
    scan.action(action="policies/" + str(scan.policy_id),
                method="put",
                extra=settings)
    scan.policy_set(args['policy'])
    t = ','
    targets = t.join(parse_nmapxml(args['filename']))
    print targets
    scan.scan_add(targets=targets, name=args['scanname'])
    scan.scan_run()
Exemple #14
0
def main():
    """ main function """

    with RedirectOutput():
        scanner = ness6rest.Scanner(url=NESSUS_URL,
                                    login=NESSUS_USERNAME,
                                    password=NESSUS_PASSWORD,
                                    insecure=True)

        scantemplate = os.getenv("NESSUS_SCANTEMPLATE", "basic")
        scanner.scan_add(targets=NESSUS_SCANTARGET,
                         template=scantemplate,
                         name="Faraday Agent Scan")
        print("Starting scan")
        scanner.scan_run()

        #This blocks execution until the scan stops running
        scanner._scan_status()

        plugin = PluginsManager().get_plugin("nessus")
        plugin.parseOutputString(scanner.download_scan(export_format="nessus"))

    print(plugin.get_json())
# The purpose of this script is to take a set of text files
# Read each one, pull out all of the ip addresses, store them in a variable and start a scan for that specific text file IP addresses

from nessrest import ness6rest

batch_start_number = 0
batch_end_number = 80
nessus_policy_name = "Device Discovery Test"

while batch_start_number <= batch_end_number:
    o = open("Batch Number {0}.txt".format(batch_start_number), 'r')
    targets_list = o.read()
    print ("Processing Batch Number" , '%s' % batch_start_number)
    o.close()
    # connect to Nessus
    # scan = ness6rest.Scanner(url="https://localhost:8834", login="******", password="******", insecure=True)
    scan = ness6rest.Scanner(url="https://52.36.138.116:8834", login="******", password="******", insecure=True)
    # Specify a scan
    scan.policy_set(name=nessus_policy_name)
    scan.scan_add(targets=targets_list)
    scan.scan_run()
    batch_start_number +=1
Exemple #16
0
                                                      4] == '127.' or args.server == '::1'

# allow localhost connections to proceed without warning, but warn otherwise if CA not set
if not args.capath:
    if localhost:
        insecure = True
    elif not insecure:
        # warn if user hasn't supplied a CA Path, but might expect security or bump into TLS errors later
        print('WARNING:  No CA path explicitly set. Connection to ' +
              nessus_url + ' could fail due to TLS/SSL server authentication')

scanner = None
if keys:
    scanner = ness6rest.Scanner(url=nessus_url,
                                api_akey=keys['accessKey'],
                                api_skey=keys['secretKey'],
                                insecure=insecure,
                                ca_bundle=args.capath)
elif password:
    scanner = ness6rest.Scanner(url=nessus_url,
                                login=args.user,
                                password=password,
                                insecure=insecure,
                                ca_bundle=args.capath)
else:
    print_err(
        'Failed to understand API key or password (this is probably a script BUG)',
        True)

# Get all reports
if scanner:
Exemple #17
0
from nessrest import ness6rest

# connect to Nessus
scan = ness6rest.Scanner(url="https://localhost:8834",
                         login="******",
                         password="******",
                         insecure=True)
# Specify a scan
scan.policy_set(name="sample_template")
scan.scan_add(targets="190.249.221.139, ")
scan.scan_run()
#!/usr/bin/python
import sys
sys.path.append('../')
from nessrest import ness6rest

import getpass
user = getpass._raw_input('User: '******'scans']:
  scan.scan_name = s['name']
  scan.scan_id = s['id']
  xml_nessus = scan.download_scan(export_format='nessus')
  fp = open('%s_%s.nessus'%(scan.scan_name,scan.scan_id),"w")
  fp.write(xml_nessus)
  fp.close()

Exemple #19
0
import os
from nessrest import ness6rest

scan = ness6rest.Scanner(url="https://ohcinnessusscan:8834", login=os.environ['username'], password=os.environ['password'], insecure=True)
def main():
    try:
        args = parse_args()

        logging.addLevelName(RESULT, "RESULT")
        logging.basicConfig(format="%(levelname)-8s %(message)s",
                            handlers=[logging.StreamHandler(sys.stdout)],
                            level=args.loglevel)
        # disable the logging for the 'urllib3' lib
        logging.getLogger("urllib3").setLevel(logging.CRITICAL)

        # help required to:
        # tidy-up this piece of code
        if args.subcommand == "nessus":
            if args.output_file and not args.list:
                output_file = "{}.xlsx".format(args.output_file)
            elif not args.output_file and not args.list:
                output_file = "nessus-results_{}".format(
                    time.strftime("%Y%m%d-%H%M%S"))
            else:
                output_file = "N/A"
        elif args.subcommand == "nmap":
            if args.output_file:
                output_file = "{}".format(args.output_file)
            else:
                output_file = "nmap-results_{}".format(
                    time.strftime("%Y%m%d-%H%M%S"))

        if args.subcommand == "nessus":
            # variables summary
            logging.info("Nessus login: {}".format(args.login))
            logging.info("Nessus password: {}".format(args.password))
            if args.folders:
                logging.info("Nessus folder(s): {}".format(";".join(
                    sorted(args.folders))))
            if args.scans:
                logging.info("Nessus scan(s): {}".format(";".join(
                    sorted(args.scans))))
            logging.info("Nessus URL: https://{}:{}".format(
                args.host, args.port))
            if args.config_file:
                logging.info(
                    "Configuration file for Nessus vulnerabilities: {}".format(
                        args.config_file.name))
            logging.info(
                "XLSX results output_file: {}.xlsx".format(output_file))

            scanner = ness6rest.Scanner(insecure=True,
                                        login=args.login,
                                        password=args.password,
                                        url="https://{}:{}".format(
                                            args.host, args.port))

            if args.list:
                if args.list == "folders":
                    if args.folders:
                        results = nessus.get_folders(scanner, args.folders)
                    else:
                        results = nessus.get_all_folders(scanner)
                elif args.list == "scans":
                    if args.folders:
                        results = nessus.fetch_scans(scanner, args.folders)
                    elif args.scans:
                        results = nessus.get_scans(scanner, args.scans)
                    else:
                        results = nessus.get_all_scans(scanner)

                for result in results:
                    logging.log(RESULT, "{}".format(result["name"]))
            elif args.folders or args.scans:
                if args.folders:
                    scans = nessus.fetch_scans(scanner, args.folders)
                elif args.scans:
                    scans = nessus.get_scans(scanner, args.scans)

                if scans:
                    workbook = xlsxwriter.Workbook(
                        "{}.xlsx".format(output_file))

                    logging.log(
                        RESULT,
                        "generating 'Host vs Vulnerabilities' worksheet...")
                    parse_ness_host_vulns(workbook,
                                          scanner,
                                          scans,
                                          config_file=args.config_file)

                    logging.log(
                        RESULT,
                        "generating 'Vulnerability vs Hosts' worksheet...")
                    parse_ness_vuln_hosts(workbook,
                                          scanner,
                                          scans,
                                          config_file=args.config_file)

                    logging.log(RESULT,
                                "generating 'Host vs OSs' worksheet...")
                    parse_ness_host_oss(workbook, scanner, scans)
                    logging.log(RESULT,
                                "generating 'OS vs Hosts' worksheet...")
                    parse_ness_os_hosts(workbook, scanner, scans)

                    workbook.close()

        elif args.subcommand == "nmap":
            # variables summary
            # help required to:
            # add regex support
            input_files = []
            for input_file in args.input_files:
                input_files.append(input_file.name)
            logging.info("Nmap XML results file(s): {}".format(";".join(
                sorted(input_files))))
            logging.info("XLSX results file: {}.xlsx".format(output_file))

            workbook = xlsxwriter.Workbook("{}.xlsx".format(output_file))
            logging.log(RESULT, "generating 'Host vs Services' worksheet...")
            parse_nmap_host_services(workbook, input_files)
            logging.log(RESULT, "generating 'Host vs OSs' worksheet...")
            parse_nmap_host_oss(workbook, input_files)
            logging.log(RESULT, "generating 'OS vs Hosts' worksheet...")
            parse_nmap_os_hosts(workbook, input_files)

            workbook.close()
    except KeyboardInterrupt:
        logging.exception("'CTRL+C' pressed, exiting...")
Exemple #21
0
# scan

# Scan Settings
# nessus_url = "https://nessus.example.com:8834"
nessus_url = "https://192.168.111.10:8834"
scan_policy = "Basic Network Scan"
scan_name = "My Scan"

# Scanner Credentials
user = getpass._raw_input('User: '******','.join(temp_hosts)
# Set target and scan name
scan.scan_add(targets=hosts, name=scan_name)
# scan.scan_exists(targets=hosts, name=scan_name)

# Run Scan
scan.scan_run()

# Download results
#!/usr/bin/env python

from nessrest import ness6rest
import os, sys, io
from pprint import pprint as pp
import csv
import time

username = os.environ.get('nessus_user')
password = os.environ.get('nessus_pass')

scanner = ness6rest.Scanner(url="https://nessus-manager.prod.sec.msap.io:8834",
                            login=username,
                            password=password)

target_scan = sys.argv[1]
target_scan = 'manual dynamic - devx'
print target_scan

spin_hosts = open('spin-hosts.list').read().rstrip().split("\n")

plugins_ignore = ['Network daemons not managed by the package system']
agents = {}
plugins = {}


def get_agents():
    scanner.action('agents', method='get')

    for agent in scanner.res['agents']:
        agent_uuid = agent['uuid']
Exemple #23
0
def doScanByNessus(login,
                   password,
                   targets,
                   customPolicy,
                   policy="",
                   customScanName="",
                   url="https://127.0.0.1:8834",
                   plugins="",
                   insecure=True):
    """
    Scan by nessus API given results

    :param login: (string)
    :param password: (string)
    :param targets: (string) targets separate by ','
    :param customPolicy: (string) name of policies to use, if don't exist, will be created with this name
    :param policy: (string) if customPolicy don't exist, it will create using this template (discovery, basic or advanced)
    :param customScanName: (string) you can specify a custom scan name, else it will be same that customPolicy
    :param url: (string)
    :param plugins: (string) plugins to use in "advanced" scans
    :param insecure: (boolean) true to disable ssl
    :return: None
    """
    scan = ness6rest.Scanner(url=url,
                             login=login,
                             password=password,
                             insecure=insecure)

    scan.action(action="policies/110", method="GET")

    if not customPolicy or not scan.policy_exists(customPolicy):
        print("Custom policy don't found, try to create new one")

        if policy == "discovery" or policy == "basic" or (policy == "advanced"
                                                          and plugins):
            try:
                scan.action(action="editor/policy/templates", method="GET")
                template_uuid = ""
                for template in scan.res["templates"]:
                    if template["name"] == policy:
                        template_uuid = template["uuid"]
                        break
                if not template_uuid:
                    print("Policy template {} not found".format(policy))
                    return

                configuration = {"settings": {}}
                configuration.update({"uuid": template_uuid})
                configuration["settings"].update({"name": customPolicy})
                configuration["settings"].update({"safe_checks": "yes"})
                configuration["settings"].update({"scan_webapps": "no"})
                configuration["settings"].update({"report_paranoia": "Normal"})
                configuration["settings"].update({"provided_creds_only": "no"})
                configuration["settings"].update({"thorough_tests": "no"})
                configuration["settings"].update(
                    {"report_verbosity": "Normal"})
                configuration["settings"].update(
                    {"silent_dependencies": "yes"})
                configuration["settings"].update({"cisco_offline_configs": ""})
                configuration["settings"].update(
                    {"network_receive_timeout": "5"})
                configuration["settings"].update({"max_checks_per_host": "5"})

                if policy == "discovery":
                    configuration["settings"].update(
                        {"discovery_mode": "Host enumeration"})

                if policy == "basic":
                    configuration["settings"].update(
                        {"discovery_mode": "Port scan (all ports)"})

                scan.action(action="policies",
                            method="POST",
                            extra=configuration)

                scan.policy_id = scan.res["policy_id"]

                if policy == "advanced":
                    scan.plugins_info(plugins)
                    scan._enable_plugins()

            except KeyError:
                print("policy id was not returned")
            except requests.exceptions.ConnectionError:
                raise Exception(
                    "Problem during connection with Nessus: {}".format(url))
            except:
                print("Unexpected error: {}".format(sys.exc_info()[1]))
        else:
            print(
                "Policy template not available, please choose between discovery, basic and advanced"
            )
            print("If you choose advanced, please specify plugins to use")

    else:
        scan.policy_set(customPolicy)

    scan.scan_add(targets, name=customScanName)

    scan.scan_run()
    scan.scan_results()
    kbs = scan.download_kbs()

    for hostname in kbs.keys():
        f = open(hostname, "w")
        f.write(kbs[hostname])
        f.close()
Exemple #24
0
# The purpose of this script is to download all of the Nessus CSV files to the local disk.
# Later, this script will be extended to parse the files into the database
# The acceptable file outputs for this script are CSV, DB, HTML, and XML (Nessus)

import nessrest
from nessrest import ness6rest
import sys

sys.path.append('../')
import getpass
user = "******"
password = "******"

scan = ness6rest.Scanner(url="https://52.36.138.116:8834",
                         login=user,
                         password=password,
                         insecure=True)
scan.action(action="scans", method="get")

scan_number = 0

for s in scan.res['scans']:
    scan.scan_name = s['name']
    scan.scan_id = s['id']
    csv_nessus = scan.download_scan(export_format='csv')
    fp = open('Results_set_%s.csv' % (scan_number), "w")
    fp.write(csv_nessus)
    fp.close()
    scan_number += 1