dreadngel

scheduler

Jul 24th, 2019
263
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
Python 4.76 KB | None | 0 0
  1. """A job to send a HTTP (GET or DELETE) periodically."""
  2.  
  3. import logging
  4. import requests
  5. import os
  6. import json
  7. import urllib3
  8.  
  9. from ndscheduler import job
  10.  
  11. logger = logging.getLogger(__name__)
  12.  
  13.  
  14. logger = logging.getLogger(__name__)
  15.  
  16. class SSLException(Exception):
  17.     pass
  18.  
  19.  
  20. class Scanner(object):
  21.     '''
  22.    Scanner object
  23.    '''
  24.     #fields
  25.     url = ""
  26.     api_keys = ""
  27.  
  28.     def __init__(self, url, api_keys='',
  29.                  insecure = True, auto_logout = True, debug = True):
  30.         self.debug = debug
  31.         self.url = url
  32.         self.api_keys = api_keys
  33.         if debug:
  34.             logger.setLevel(logging.INFO)
  35.  
  36.         if insecure:
  37.             urllib3.disable_warnings(urllib3.exceptions.InsecureRequestWarning)
  38.  
  39.         logger.info("Patrowl wrapper initiated")
  40.  
  41.     ################################################################################
  42.     def action(self, action, method, extra={}, files={}, json_req=True, download=False, private=False, retry=True):
  43.  
  44.         payload = {}
  45.         payload.update(extra)
  46.        
  47.         headers = {
  48.                     # will alwaus use API
  49.                     "Cookie": self.api_keys,
  50.                     #token - no details TODO@ verify if it's refreshed
  51.                     # "X-API-Token" : "740A19ED-68A7-418A-9D74-D4C2F7AA9D00",
  52.                     # "Content-type": "application/json",
  53.                     # "Accept": "text/plain"
  54.                     }
  55.         payload = json.dumps(payload)
  56.         url = "{}/{}".format(self.url, action)
  57.  
  58.         verify = False
  59.  
  60.         try:
  61.             req = requests.request(method, url, data=payload, files=files,
  62.                                    verify=verify, headers=headers)
  63.             logger.info("Patrowl wrapper call action({}/{}) returned with status {}".format(method, url, str(req.status_code)))
  64.             return {
  65.                 "status":   str(req.status_code),
  66.                 "body" :    req.json() if req.text else {}
  67.                 }
  68.         except requests.exceptions.SSLError as ssl_error:
  69.             raise SSLException('%s for %s.' % (ssl_error, url))
  70.         except requests.exceptions.ConnectionError:
  71.             raise Exception("Could not connect to %s.\nExiting!\n" % url)
  72.  
  73.    
  74.     ################################################################################
  75.     def start_scan(self, scan_id=0):
  76.  
  77.         action_url = "/scans/api/v1/defs/run/{}".format(scan_id)
  78.         try:
  79.             create_scan_result = self.action(action=action_url,
  80.                         method="GET",
  81.                         private=True,
  82.                         retry=False)
  83.             if create_scan_result["status"] == "200":
  84.                 logger.info("Patrowl scan(id={}) successfully started".format(scan_id))
  85.                 return {"data" : create_scan_result["body"]}
  86.             else:
  87.                 logger.error("Patrowl scan(id={}) failed to start: action returned non-200 status response".format(scan_id))
  88.                
  89.                 return  {"error": "Error on start_scan",
  90.                         "description": "Nessus request returned a non-200 status response",
  91.                         "data" : create_scan_result["body"]
  92.                         }
  93.         except Exception as ex:
  94.             logger.error("Error on start_scan")
  95.             logger.exception(ex)
  96.             return {"error": "Error on start_scan",
  97.                     "description": "Exception",
  98.                     "data" : str(ex)}
  99.  
  100.  
  101.     ################################################################################
  102.     def objdump(self):
  103.         '''
  104.        debugging function to dump all of the set values
  105.        '''
  106.         for attr in dir(self):
  107.             print("obj.%s = %s" % (attr, getattr(self, attr)))
  108.  
  109.  
  110. class CreateScanSchedulerJob(job.JobBase):
  111.     TIMEOUT = 10
  112.  
  113.     @classmethod
  114.     def meta_info(cls):
  115.         return {
  116.             'job_class_string': '%s.%s' % (cls.__module__, cls.__name__),
  117.             'notes': 'Start\'s a Patrowl preconfigured scan',
  118.             'arguments': [
  119.                 # Scan Id
  120.                 {'type': 'int', 'description': 'Patrowl Scan ID'},
  121.                 # API key
  122.                 {'type': 'string', 'description': 'Patrowl API keys'},
  123.                 # Server url
  124.                 {'type': 'string', 'description': 'Patrowl server url'}
  125.             ],
  126.             'example_arguments': ('["10", "http://patrowl.manager.local", "sessionid=123456789012345678901234567890AB"]')
  127.         }
  128.  
  129.     def run(self, scan_id, key, url, *args, **kwargs):
  130.         wrapper = Scanner(url = url, api_keys = key)
  131.        
  132.         return wrapper.start_scan(scan_id)
  133.  
  134. if __name__ == "__main__":
  135.     job = CreateScanSchedulerJob.create_test_instance()
  136.     job.run(0, "", "0.0.0.0:1111")
Advertisement
Add Comment
Please, Sign In to add comment