def create_dashboard(question_names, name):
    """Creates dashboard with the provided name and question

                 Args:
                     question_names: List of question names that will be put in dashboard
                     name: Name of the dashboard that is being made

                 Returns:
                    creates a dashboard
                 """
    handler_args = dict()
    # Client credentials
    handler_args['username'] = clientcreds[0]
    handler_args['password'] = clientcreds[1]
    handler_args['host'] = clientcreds[2]
    handler_args['port'] = clientcreds[3]  # optional
    # Log level: 0 is only errors and warnings 12 is everything
    handler_args['loglevel'] = 0

    handler_args['debugformat'] = False

    handler_args['record_all_requests'] = True

    # instantiate a handler using all of the arguments in the handler_args dictionary
    handler = pytan.Handler(**handler_args)
    # Take input list of saved questions and creat dashboard from them
    dash_kwargs = dict()
    dash_kwargs['sqs'] = question_names
    handler.create_dashboard(name,
                             text='',
                             group='',
                             public_flag=True,
                             **dash_kwargs)
def check_to_see_if_exists(savedlist):
    """Checks to see if questions submitted are already contained in client, outputs list of those that are not

          Args:
              savedlist: list of questions from demo to check against client questions

          Returns:
              newlist: list of all the questions not on client that are on demo
          """

    # create a dictionary of arguments for the pytan handler
    newlist = savedlist[:]
    handler_args = dict()
    # Client credentials
    handler_args['username'] = clientcreds[0]
    handler_args['password'] = clientcreds[1]
    handler_args['host'] = clientcreds[2]
    handler_args['port'] = clientcreds[3]  # optional

    handler_args['loglevel'] = 0

    handler_args['debugformat'] = False

    handler_args['record_all_requests'] = True

    # instantiate a handler using all of the arguments in the handler_args dictionary
    handler = pytan.Handler(**handler_args)

    # setup the arguments for the handler() class
    kwargs = dict()
    kwargs["objtype"] = u'saved_question'

    response = handler.get_all(**kwargs)

    # call the export_obj() method to convert response to JSON and store it in out
    export_kwargs = dict()
    export_kwargs['obj'] = response
    export_kwargs['export_format'] = 'json'

    out = handler.export_obj(**export_kwargs)
    with open('saved_questions_list', 'w') as outfile:
        outfile.write(out)

    with open("saved_questions_list") as fh:
        put = json.loads(fh.read())
    i = 1

    while i <= len(put["saved_question"]):
        q = (i - 1)
        for question in savedlist:
            if question == put["saved_question"][q]["name"]:
                newlist.remove(question)
        i = i + 1

    return newlist
示例#3
0
    def setUpClass(cls):  # noqa
        cls.handler = pytan.Handler(**SERVER_INFO)
        m = "{}\n{}: PyTan v'{}' against Tanium v'{}' -- Valid Tests Starting\n".format
        spew(
            m(
                '*' * 100,
                pytan.utils.seconds_from_now(),
                pytan.__version__,
                cls.handler.session.get_server_version(),
            ), 2)

        if not hasattr(cls, 'base_type_objs'):
            # fetch objects for export tests
            kwargs = {
                'name': [
                    "Computer Name",
                    "IP Route Details",
                    "IP Address",
                    'Folder Contents',
                ],
                'objtype':
                'sensor',
            }
            spew(
                "TESTSETUP: Getting sensor objects for export tests of BaseType"
            )
            cls.base_type_objs = cls.handler.get(**kwargs)

        if not hasattr(cls, 'wlus'):
            # create whitelisted_urls for getobject tests
            cls.wlus = ['test1', 'test2', 'test3']
            spew("TESTSETUP: Creating whitelisted URLs for get object tests")
            for wlu in cls.wlus:
                try:
                    cls.handler.create_whitelisted_url(url=wlu)
                except:
                    pass

        if not hasattr(cls, 'result_set_objs'):
            # ask questions for export tests
            kwargs = {
                'qtype':
                'manual',
                'sensors': [
                    "Computer Name",
                    "IP Route Details",
                    "IP Address",
                    'Folder Contents{folderPath=C:\\Program Files}',
                ],
            }
            spew("TESTSETUP: Asking a question for export tests of ResultSet")
            cls.result_set_objs = cls.handler.ask(**kwargs)

        spew('\n' + str(cls.handler))
示例#4
0
def process_handler_args(parser, all_args):
    handler_grp_names = ['Tanium Authentication', 'Handler Options']
    handler_opts = utils.get_grp_opts(parser, handler_grp_names)
    handler_args = {k: all_args[k] for k in handler_opts}

    try:
        h = pytan.Handler(**handler_args)
        print str(h)
    except Exception as e:
        print e
        sys.exit(99)
    return h
示例#5
0
    def init_pytan(self):

        # disable python from generating a .pyc file
        sys.dont_write_bytecode = True

        # change me to the path of pytan if this script is not running from EXAMPLES/PYTAN_API
        pytan_static_path = os.path.join(os.path.expanduser(self.pytan_loc),
                                         'lib')

        # Determine our script name, script dir
        my_file = os.path.abspath(sys.argv[0])
        my_dir = os.path.dirname(my_file)

        # try to automatically determine the pytan lib directory by assuming it is in '../../lib/'
        parent_dir = os.path.dirname(my_dir)
        pytan_root_dir = os.path.dirname(parent_dir)
        lib_dir = os.path.join(pytan_root_dir, 'lib')

        # add pytan_loc and lib_dir to the PYTHONPATH variable
        path_adds = [lib_dir, pytan_static_path]
        [sys.path.append(aa) for aa in path_adds if aa not in sys.path]

        # import pytan
        import pytan

        # create a dictionary of arguments for the pytan handler
        handler_args = {}

        # establish our connection info for the Tanium Server
        handler_args['username'] = self.username
        handler_args['password'] = self.password
        handler_args['host'] = self.host
        handler_args['port'] = self.port

        # optional, level 0 is no output except warnings/errors
        # level 1 through 12 are more and more verbose
        handler_args['loglevel'] = 0

        # optional, use a debug format for the logging output (uses two lines per log entry)
        handler_args['debugformat'] = False

        # optional, this saves all response objects to handler.session.ALL_REQUESTS_RESPONSES
        # very useful for capturing the full exchange of XML requests and responses
        handler_args['record_all_requests'] = False

        # instantiate a handler using all of the arguments in the handler_args dictionary
        #print "...CALLING: pytan.handler() with args: {}".format(handler_args)
        pytan.utils.get_all_pytan_loggers(
        )["pytan.pollers.QuestionPoller"].disabled = True
        handler = pytan.Handler(**handler_args)

        return handler
示例#6
0
def get_handler():
    handler_args = {}

    handler_args['username'] = demisto.params()['credentials']['identifier']
    handler_args['password'] = demisto.params()['credentials']['password']
    handler_args['host'] = demisto.params()['host']
    handler_args['port'] = demisto.params()['port']

    handler_args['loglevel'] = 1
    handler_args['debugformat'] = False
    handler_args['record_all_requests'] = True

    return pytan.Handler(**handler_args)
示例#7
0
def process_handler_args(parser, all_args):
    my_args = dict(all_args)
    handler_grp_names = ['Handler Authentication', 'Handler Options']
    handler_opts = utils.get_grp_opts(parser, handler_grp_names)
    handler_args = {k: my_args.pop(k) for k in handler_opts}
    # handler_args['session_lib'] = 'httplib'
    try:
        h = pytan.Handler(**handler_args)
        print str(h)
    except Exception:
        traceback.print_exc()
        sys.exit(99)
    return h
    def test_invalid_connect(self, value):

        args = value['args']
        exc = eval(value['exception'])
        e = value['error_str']

        mykwargs = copy.copy(SERVER_INFO)
        mykwargs.update(args)

        spew("")
        spew("+++ TESTING EXPECTED FAILURE Handler() with kwargs %s" %
             (mykwargs))
        with self.assertRaisesRegexp(exc, e):
            pytan.Handler(**mykwargs)
示例#9
0
def tanium_trace_destination(address):
    #get the handler working
    handler_args['loglevel'] = 1
    handler_args['debugformat'] = False
    handler_args['record_all_requests'] = True
    print "...CALLING: pytan.handler()"
    handler = pytan.Handler(**handler_args)

    #put the question together - this is filtered and qualified
    #the regex,output,localhost have to be placed manually
    kwargs["export_format"] = u'json'
    #multi sensor
    kwargs["sensors"] = [
        u'Computer Name',
        u'Trace Network Connections{TreatInputAsRegEx=0,OutputYesOrNoFlag=0,IncludeLocalhost=0,AbsoluteTimeRange='
        + tanium_time + u',DestinationIP=' + address + u'}'
    ]
    #Relative time range example
    #kwargs["sensors"] = [u'Computer Name',u'Trace Network Connections{TreatInputAsRegEx=0,OutputYesOrNoFlag=0,IncludeLocalhost=0,TimeRange=unlimited,DestinationIP='+address+u'}']
    #qualified request
    kwargs["question_filters"] = [
        u'Trace Network Connections{TreatInputAsRegEx=0,OutputYesOrNoFlag=0,IncludeLocalhost=0,AbsoluteTimeRange='
        + tanium_time + u',DestinationIP=' + address +
        u'},that contains:Connection attempted.'
    ]
    kwargs["qtype"] = u'manual'

    #make the call and wait
    print "...CALLING: handler.ask with args: {}".format(kwargs)
    response = handler.ask(**kwargs)

    #show the question as it would appear in the console - great for debugging
    print "...OUTPUT: Equivalent Question if it were to be asked in the Tanium Console: "
    print response['question_object'].query_text

    #if the dictionary has a question results convert this out to json
    if response['question_results']:
        # call the export_obj() method to convert response to CSV and store it in out
        export_kwargs = {}
        export_kwargs['obj'] = response['question_results']
        export_kwargs['export_format'] = 'json'
        out = handler.export_obj(**export_kwargs)

    #load out the json
    out_json = json.loads(out)

    #return the json from the function
    return out_json
def ask_for_saved_questions(saved_questions_list):
    """Asks demo for the details of the questions that demo has that client side doesnt

             Args:
                 saved_questions_list: list of questions not on client to ask demo for details about

             Returns:
                 Writes json results to 'saved_questions_list.json'
             """
    # Asks the demo enviroment for the saved questions and their details that the client side is missing
    if len(saved_questions_list) == 0:
        return 0
    print "Questions to Make"
    print saved_questions_list
    handler_args = dict()
    # establish our connection info for the Tanium Server
    # Demo credentials
    handler_args['username'] = democreds[0]
    handler_args['password'] = democreds[1]
    handler_args['host'] = democreds[2]
    handler_args['port'] = democreds[3]  # optional

    handler_args['loglevel'] = 0

    handler_args['debugformat'] = False

    handler_args['record_all_requests'] = True

    # instantiate a handler using all of the arguments in the handler_args dictionary
    handler = pytan.Handler(**handler_args)

    # setup the arguments for the handler() class
    kwargs = dict()
    kwargs["objtype"] = u'saved_question'
    kwargs["name"] = saved_questions_list

    response = handler.get(**kwargs)

    # call the export_obj() method to convert response to JSON and store it in out
    export_kwargs = dict()
    export_kwargs['obj'] = response
    export_kwargs['export_format'] = 'json'

    out = handler.export_obj(**export_kwargs)
    with open('saved_questions_list.json', 'w') as outfile:
        outfile.write(out)
    return 1
示例#11
0
def Tanium_Connect(user, passw):
    if debug: print("\nFUNCTION Tanium_Connect")

    #Retrieve Tanium Environment configuration and setup handler
    #try:
    handler = pytan.Handler(
        username=user,
        password=passw,
        host=config.get(environment, 'host'),
        port=config.get(environment, 'port'),
        loglevel=int(config.get(environment, 'log_level')),
        debugformat=config.get(environment, 'debug_format'),
        record_all_requests=config.get(environment, 'record_all_requests'),
        debug=config.getboolean(environment, 'print_debug'))
    #except:
    #if debug: print ("\nTanium_Connect FAILED")

    return (handler)
def tempquestionask(question_name):
    """Asks a question of Demo in order to generate json for creation of question on demo

       Args:
           question_name: Name of the question to ask

       Returns:
           results: Json of the results from asking of one question
       """
    handler_args = dict()
    # establish our connection info for the Tanium Server
    # Demo credentials
    handler_args['username'] = democreds[0]
    handler_args['password'] = democreds[1]
    handler_args['host'] = democreds[2]
    handler_args['port'] = democreds[3]  # optional

    handler_args['loglevel'] = 0

    handler_args['debugformat'] = False

    handler_args['record_all_requests'] = True

    # instantiate a handler using all of the arguments in the handler_args dictionary
    handler = pytan.Handler(**handler_args)

    # setup the arguments for the handler() class
    kwargs = dict()
    kwargs["objtype"] = u'saved_question'
    kwargs["name"] = question_name

    orig_objs = handler.get(**kwargs)

    export_kwargs = dict()
    export_kwargs['obj'] = orig_objs
    export_kwargs['export_format'] = 'json'
    export_kwargs['report_dir'] = tempfile.gettempdir()

    print "...CALLING: handler.export_to_report_file() with args: {}".format(
        export_kwargs)
    json_file, results = handler.export_to_report_file(**export_kwargs)

    return results
def create_saved_questions(number, savedlist):
    """Create any questions that exist on the Demo enviroment but not on the Client side that are in the Demo dashboards
        needed to be created

       Args:
           number: Number of questions needed to be made
           savedlist: Names of the questions needed to be Created

       Returns:
           nothing if number = 0
           Creates the questions needed on client side
       """
    if number == 0:
        return
    handler_args = dict()

    # establish our connection info for the Tanium Server
    # Client credentials
    handler_args['username'] = clientcreds[0]
    handler_args['password'] = clientcreds[1]
    handler_args['host'] = clientcreds[2]
    handler_args['port'] = clientcreds[3]  # optional

    handler_args['loglevel'] = 0

    handler_args['debugformat'] = False

    handler_args['record_all_requests'] = False

    # Instantiate a handler using all of the arguments in the handler_args dictionary
    print savedlist
    handler = pytan.Handler(**handler_args)
    # Move through each saved question to make and make a json of it to send to client to make saved question
    for saved_question in savedlist:
        # setup the arguments for the handler.get() method
        question_results = tempquestionask(saved_question)
        with open('Result.json', 'w') as outfile:
            outfile.write(question_results)
        # create the object from the exported JSON file
        create_kwargs = dict()
        create_kwargs['objtype'] = u'saved_question'
        create_kwargs['json_file'] = "Result.json"
        handler.create_from_json(**create_kwargs)
示例#14
0
def tanium_md5s(tanium_time):
    #get the handler working
    handler_args['loglevel'] = 1
    handler_args['debugformat'] = False
    handler_args['record_all_requests'] = True
    print "...CALLING: pytan.handler()"
    handler = pytan.Handler(**handler_args)

    #put the question together - this is filtered and qualified
    #the regex,output,localhost have to be placed manually
    kwargs["export_format"] = u'json'
    #multi sensor
    kwargs["sensors"] = [
        u'Trace Executed Process Hashes{TimeRange=absolute time range,AbsoluteTimeRange='
        + tanium_time + u',MaxResultsPerHost=1000}'
    ]
    #qualified request
    kwargs["qtype"] = u'manual'

    #make the call and wait
    print "...CALLING: handler.ask with args: {}".format(kwargs)
    response = handler.ask(**kwargs)

    #show the question as it would appear in the console - great for debugging
    print "...OUTPUT: Equivalent Question if it were to be asked in the Tanium Console: "
    print response['question_object'].query_text

    #if the dictionary has a question results convert this out to json
    if response['question_results']:
        # call the export_obj() method to convert response to CSV and store it in out
        export_kwargs = {}
        export_kwargs['obj'] = response['question_results']
        export_kwargs['export_format'] = 'json'
        out = handler.export_obj(**export_kwargs)

    #load out the json
    out_json = json.loads(out)

    #return the json from the function
    return out_json
示例#15
0
# get the form submission
form = cgi.FieldStorage()

formdict = common.formtodict(form)

action_id = formdict.get('action_id', None)
computer_id = formdict.get('computer_id', None)

if not action_id or not computer_id:
    status = "ERROR: Missing action_id or computer_id!"
else:
    # connect to Tanium
    handler = pytan.Handler(
        username=config['tanium_username'],
        password=config['tanium_password'],
        host=config['tanium_host'],
    )

    # this logic assumes only one system should be being deployed to,
    # more servers is more complicated
    action_obj = handler.get('action', id=action_id)[0]
    rd = handler.get_result_data(action_obj, True)
    if not rd.rows:
        status = "Waiting to download."
    else:
        status = rd.rows[0]['Action Statuses'][0].split(':')[1]

status = json.dumps({'status': status})

common.print_html(status)
示例#16
0
def main(ret):
    # get the form submission
    form = cgi.FieldStorage()

    formdict = common.formtodict(form)

    # BOOTSTRAP TESTS
    # formdict['computer_id'] = '1987595770'
    # formdict['substep'] = "11"
    # formdict['jobs'] = ["18372"]

    computer_id = formdict.get('computer_id', "")
    substep = int(formdict.get('substep', 0))

    ret['substep'] = substep
    ret['computer_id'] = computer_id

    if not computer_id:
        die(ret, "Missing computer_id!")

    try:
        # connect to Tanium
        handler = pytan.Handler(
            username=config['tanium_username'],
            password=config['tanium_password'],
            host=config['tanium_host'],
        )
    except Exception as e:
        jobs = get_jobs(ret, formdict)
        ret = add_job(ret, jobs)
        die(ret, "Unable to connect to Tanium: {}!".format(e), False)

    if substep == 1:
        '''
        Ask the question Get Computer Name for this computer_id
        '''
        ret = ask_question(handler, computer_id, formdict, ret, 'Computer Name')
    elif substep == 2:
        '''
        Get the results of previous question, if data ready add computer name to return dict
        for consumption by calling javascript
        '''
        jobs = get_jobs(ret, formdict)
        job = jobs[0]
        ret = add_job(ret, job)

        ret = check_question(handler, computer_id, formdict, ret, job)
        if ret['data_ready'] and ret['results']:
            ret['computer_name'] = ret['results'][0]['Computer Name']
            m = "Found computer name {} for computer ID {}".format
            ret = add_status(ret, m(ret['computer_name'], computer_id), next=True)
            # ret['substep'] = 10  # BOOTSTRAP

    elif substep == 3:
        '''
        Deploy the action "Distribute Patch Tools"
        '''
        ret = deploy_action(handler, computer_id, "Distribute Patch Tools", ret)
    elif substep == 4:
        '''
        Check if previous action done, go to next step if so
        '''
        jobs = get_jobs(ret, formdict)
        job = jobs[0]

        ret = add_job(ret, job)
        ret = check_action(handler, formdict, ret, job)
        if ret['action_done']:
            ret['substep'] += 1
    elif substep == 5:
        '''
        Check that sync scan pkg exists, create if not
        '''
        ret, pkg = create_get_pkg(handler, ret, config['sync_scan_name'], config['sync_scan_opts'])
        ret['substep'] += 1
    elif substep == 6:
        '''
        Deploy the action "Run Patch Scan Synchronously"
        '''
        ret = deploy_action(handler, computer_id, config['sync_scan_name'], ret)
    elif substep == 7:
        '''
        Check if previous action done, go to next step if so
        '''
        jobs = get_jobs(ret, formdict)
        job = jobs[0]
        ret = add_job(ret, job)

        ret = check_action(handler, formdict, ret, job)
        if ret['action_done']:
            ret['substep'] += 1
    elif substep == 8:
        '''
        Ask the question Get Tanium Action Log for previous action for this computer_id
        '''
        jobs = get_jobs(ret, formdict)
        job = jobs[0]

        sensors = 'Tanium Action Log{{actionNumber={}}}'.format(job),
        ret = ask_question(handler, computer_id, formdict, ret, sensors)
    elif substep == 9:
        '''
        Get the results of previous question, if data ready and patch scan finished, go to next step
        '''
        jobs = get_jobs(ret, formdict)
        job = jobs[0]
        ret = add_job(ret, job)

        ret = check_question(handler, computer_id, formdict, ret, job)
        if ret['data_ready'] and ret['results']:
            lines = sorted([x.values()[0] for x in ret['results']])
            log_output = '\n'.join(lines)
            m = "VERBOSE: Tanium Action Log contents finish:\n{}".format
            ret = add_status(ret, m(log_output))

            did_not_run = "patch scan currently running"
            scan_done = "finished running patch scan"
            max_lines = "max number of lines reached"

            if did_not_run in log_output.lower():
                m = 'Re-running patch scan, one already running'
                ret = add_status(ret, m)
                ret['substep'] = 6
            elif scan_done in log_output.lower() or max_lines in log_output.lower():
                m = 'Patch scan finished, getting available patches'
                ret = add_status(ret, m, next=True)
    elif substep == 10:
        '''
        Ask the question Get Available Patches for this computer_id
        '''
        ret = ask_question(handler, computer_id, formdict, ret, 'Available Patches')
    elif substep == 11:
        '''
        Get the results of previous question,
        if data ready and no available patches, go to step 14
        if data ready and available patches, create pkgs for each patch and go to next step
        if data ready and current results unavailable (??) re-ask the question
        '''
        jobs = get_jobs(ret, formdict)
        job = jobs[0]
        ret = add_job(ret, job)

        ret = check_question(handler, computer_id, formdict, ret, job)
        if ret['data_ready']:
            ret['results'] = common.remove_noresults(ret['results'])
            if ret['results']:
                title = ret['results'][0]['Title']
                # TODO: DO THIS BETTER
                if 'current results unavailable' in title.lower():
                    m = "Re-asking due to {}".format
                    ret = add_status(ret, m(title))
                    ret['substep'] = 10
                elif 'all available patches queued for installation' in title.lower():
                    ret = add_status(ret, title, next=True)
                    ret['substep'] = 14
                else:
                    m = "Retrieved {} available patches".format
                    ret = add_status(ret, m(len(ret['results'])), next=True)
                    for rd_row in ret['results']:
                        ret, pkg = create_get_patch_pkg(handler, ret, rd_row)
            else:
                m = "No available patches to deploy"
                ret = add_status(ret, m)
                ret['substep'] = 14
    elif substep == 12:
        '''
        Get the results of previous question,
        if data ready and available patches, deploy pkgs for each patch
        '''
        jobs = get_jobs(ret, formdict)
        job = jobs[0]

        ret = check_question(handler, computer_id, formdict, ret, job)
        if ret['data_ready']:
            if ret['results']:
                for rd_row in ret['results']:
                    ret = deploy_patch_pkg(handler, computer_id, ret, rd_row)
                ret['substep'] += 1
    elif substep == 13:
        '''
        Get the results of each previous deploy patch pkg,
        if all actions finished, go to next step
        '''
        jobs = get_jobs(ret, formdict)
        ret = add_job(ret, jobs)
        done_list = []

        for job in jobs:
            ret = check_action(handler, formdict, ret, job)
            done_list.append(ret['action_done'])

        if all(done_list):
            m = "All {} patch packages have finished deploying".format
            ret = add_status(ret, m(len(done_list)), True)
        else:
            m = "VERBOSE: {} patch packages have finished deploying out of {}".format
            ret = add_status(ret, m(len([x for x in done_list if x]), len(jobs)))
    elif substep == 14:
        ret = ask_question(handler, computer_id, formdict, ret, 'Has Patch Files')
    elif substep == 15:
        jobs = get_jobs(ret, formdict)
        job = jobs[0]
        ret = add_job(ret, job)

        ret = check_question(handler, computer_id, formdict, ret, job)
        ret['results'] = common.remove_noresults(ret['results'])
        if ret['data_ready'] and ret['results']:
            has_patch_files = ret['results'][0]['Has Patch Files']
            if 'yes' in has_patch_files.lower():
                m = "Patch files exist that need to be deployed".format
                ret = add_status(ret, m(), next=True)
            else:
                m = "No patch files exist that need to be deployed, patch process finished".format
                ret = add_status(ret, m())
                ret['finished'] = True

    elif substep == 16:
        ret = deploy_action(handler, computer_id, "Install Deployed Patches", ret)
    elif substep == 17:
        jobs = get_jobs(ret, formdict)
        job = jobs[0]
        ret = add_job(ret, job)

        ret = check_action(handler, formdict, ret, job)
        if ret['action_done']:
            ret['substep'] += 1
    elif substep == 18:
        ret = ask_question(handler, computer_id, formdict, ret, 'Has Patch Files')
    elif substep == 19:
        jobs = get_jobs(ret, formdict)
        job = jobs[0]
        ret = add_job(ret, job)

        ret = check_question(handler, computer_id, formdict, ret, job)
        ret['results'] = common.remove_noresults(ret['results'])
        if ret['data_ready'] and ret['results']:
            has_patch_files = ret['results'][0]['Has Patch Files']
            if 'yes' in has_patch_files.lower():
                m = "Patch files still exist, Install Deployed Patches must still be running"
                ret = add_status(ret, m)
                ret['substep'] = 18
            else:
                m = "No patch files exist, Install Deployed Patches must be finished"
                ret = add_status(ret, m, next=True)
    # elif substep == 20:
    #     ret = deploy_action(handler, computer_id, "Reboot Windows Machine", ret)
    # elif substep == 21:
    #     jobs = get_jobs(ret, formdict)
    #     job = jobs[0]
    #     ret = add_job(ret, job)

    #     ret = check_action(handler, formdict, ret, job)
    #     if ret['action_done']:
    #         ret['substep'] += 1

        '''
        How to determine Install Deployed Patches == Finished (Just Has Patch Files == No?)
        How to determine reboot is done?
1) best way to see if Installed Deployed Patches is finished is if the "Patches deployed by Tanium" sensor returns what you tried to deploy

greg_smith [9:37 AM]
or if Installed patches returns what you deployed

greg_smith [9:38 AM]
I would pick those, as you definitely know it finished and was a success in those cases

greg_smith [9:38 AM]
2)  You can use boot time (its something like that, maybe last reboot time, not sure)

greg_smith [9:38 AM]9:38
when it changes to 5 minutes ago, you know the machine rebooted and is back online
        go back to 6
        '''
    else:
        die(ret, "Invalid substep {}!".format(substep))

    json_print_end(ret)
    return
def demo_dashboard_loading(cs):
    """Get all the dashboards from the client and compare them to those from the Demo csv any dashboards in demo not
    in the client get added to a list.

    Args:
        cs: Path to the csv file containing all of the Demo Dashboards and questions

    Returns:
        dash_boards_on_demo: List of dashboards that need to be made on the Client side
        num: number of dashboards needed (used as a check to see if the program has to go further)
    """
    handler_args = dict()
    # Client Credentials
    handler_args['username'] = clientcreds[0]
    handler_args['password'] = clientcreds[1]
    handler_args['host'] = clientcreds[2]
    handler_args['port'] = clientcreds[3]  # optional

    handler_args['loglevel'] = 0

    handler_args['debugformat'] = False

    handler_args['record_all_requests'] = True

    # instantiate a handler using all of the arguments in the handler_args dictionary
    handler = pytan.Handler(**handler_args)
    dash_kwargs = dict()
    dash_kwargs['sqs'] = saved_question_list
    # DELETE ONCE PYTAN IS FIXED
    # This is a temporary dashboard necessary to circumvent the bug
    handler.create_dashboard("Oh no isa bug",
                             text='',
                             group='',
                             public_flag=True,
                             **dash_kwargs)
    handler.delete_dashboard("Oh no isa bug", **dash_kwargs)
    obj, results = handler.get_dashboards()
    dash_boards_on_demo = {}
    with open(cs) as csvfile:
        reader = csv.DictReader(csvfile)
        for row in reader:
            dashboard, question = row['name'], row['questionname']
            if dashboard not in dash_boards_on_demo:
                dash_boards_on_demo[dashboard] = [question]
            else:
                dash_boards_on_demo[dashboard].append(question)
    key = dash_boards_on_demo.keys()
    dashboards_not_to_make = []
    i = 1
    while i <= len(results):
        q = (i - 1)
        for item in key:
            if item == (results[q]["name"]):
                dashboards_not_to_make.append(item)
        i = i + 1
    for dashs in dashboards_not_to_make:
        dash_boards_on_demo.pop(dashs, None)
    if len(dash_boards_on_demo) == 0:
        num = 0
    else:
        num = 1
    # Returns 1 if there are dashboards to make, Return 0 if not
    return dash_boards_on_demo, num
示例#18
0
handler_args['port'] = "443"  # optional

# optional, level 0 is no output except warnings/errors
# level 1 through 12 are more and more verbose
handler_args['loglevel'] = 1

# optional, use a debug format for the logging output (uses two lines per log entry)
handler_args['debugformat'] = False

# optional, this saves all response objects to handler.session.ALL_REQUESTS_RESPONSES
# very useful for capturing the full exchange of XML requests and responses
handler_args['record_all_requests'] = True

# instantiate a handler using all of the arguments in the handler_args dictionary
print "...CALLING: pytan.handler() with args: {}".format(handler_args)
handler = pytan.Handler(**handler_args)

# print out the handler string
print "...OUTPUT: handler string: {}".format(handler)

# setup the arguments for the handler.delete() method
delete_kwargs = {}
delete_kwargs["objtype"] = u'user'
delete_kwargs["name"] = u'API Test User'

# setup the arguments for the handler() class
kwargs = {}
kwargs["rolename"] = u'Administrator'
kwargs["name"] = u'API Test User'
kwargs["properties"] = [[u'property1', u'value1']]
示例#19
0
humantime = pytan.utils.human_time(now, timeformat)

if __name__ == "__main__":
    TEST_OUT = os.path.join(tempfile.gettempdir(), 'VALIDATION_TEST_OUT')

    if not os.path.isdir(TEST_OUT):
        os.mkdir(TEST_OUT)

    api_info = test_pytan_valid_server_tests.SERVER_INFO
    # override 6.5 host
    api_info['host'] = "10.0.1.240"

    # override 6.2 host
    # api_info['host'] = "172.16.31.128"

    handler = pytan.Handler(**api_info)
    platform_version = handler.get_server_version()
    print "Determined platform version: {}".format(platform_version)
    print "Determined OS version: {}".format(os_version)
    print "Determined Python version: {}".format(python_version_full)

    buildsupport.clean_up(TEST_OUT, '*')

    loader = unittest.TestLoader()
    suite = loader.loadTestsFromModule(test_pytan_valid_server_tests)

    print "Capturing stderr and stdout and launching unittests for test_pytan_valid_server_tests"

    val_stdout = StringIO.StringIO()
    val_stderr = StringIO.StringIO()