idx
int64
0
63k
question
stringlengths
53
5.28k
target
stringlengths
5
805
27,700
def error_codes ( self ) : if self . _error_codes is None : from . tcex_error_codes import TcExErrorCodes self . _error_codes = TcExErrorCodes ( ) return self . _error_codes
ThreatConnect error codes .
27,701
def exit ( self , code = None , msg = None ) : if msg is not None : if code in [ 0 , 3 ] or ( code is None and self . exit_code in [ 0 , 3 ] ) : self . log . info ( msg ) else : self . log . error ( msg ) self . message_tc ( msg ) if code is None : code = self . exit_code elif code in [ 0 , 1 , 3 ] : pass else : self ....
Application exit method with proper exit code
27,702
def exit_code ( self , code ) : if code is not None and code in [ 0 , 1 , 3 ] : self . _exit_code = code else : self . log . warning ( u'Invalid exit code' )
Set the App exit code .
27,703
def get_type_from_api_entity ( self , api_entity ) : merged = self . group_types_data . copy ( ) merged . update ( self . indicator_types_data ) print ( merged ) for ( key , value ) in merged . items ( ) : if value . get ( 'apiEntity' ) == api_entity : return key return None
Returns the object type as a string given a api entity .
27,704
def install_json ( self ) : if self . _install_json is None : try : install_json_filename = os . path . join ( os . getcwd ( ) , 'install.json' ) with open ( install_json_filename , 'r' ) as fh : self . _install_json = json . load ( fh ) except IOError : self . log . warning ( u'Could not retrieve App Data.' ) self . _...
Return contents of install . json configuration file loading from disk if required .
27,705
def install_json_params ( self ) : if not self . _install_json_params : for param in self . install_json . get ( 'params' ) or [ ] : self . _install_json_params [ param . get ( 'name' ) ] = param return self . _install_json_params
Parse params from install . json into a dict by name .
27,706
def metric ( self , name , description , data_type , interval , keyed = False ) : from . tcex_metrics_v2 import TcExMetricsV2 return TcExMetricsV2 ( self , name , description , data_type , interval , keyed )
Get instance of the Metrics module .
27,707
def message_tc ( self , message , max_length = 255 ) : if os . access ( self . default_args . tc_out_path , os . W_OK ) : message_file = '{}/message.tc' . format ( self . default_args . tc_out_path ) else : message_file = 'message.tc' message = '{}\n' . format ( message ) if max_length - len ( message ) > 0 : with open...
Write data to message_tc file in TcEX specified directory .
27,708
def playbook ( self ) : if self . _playbook is None : from . tcex_playbook import TcExPlaybook self . _playbook = TcExPlaybook ( self ) return self . _playbook
Include the Playbook Module .
27,709
def proxies ( self ) : proxies = { } if ( self . default_args . tc_proxy_host is not None and self . default_args . tc_proxy_port is not None ) : if ( self . default_args . tc_proxy_username is not None and self . default_args . tc_proxy_password is not None ) : tc_proxy_username = quote ( self . default_args . tc_prox...
Formats proxy configuration into required format for Python Requests module .
27,710
def request ( self , session = None ) : try : from . tcex_request import TcExRequest r = TcExRequest ( self , session ) if session is None and self . default_args . tc_proxy_external : self . log . info ( 'Using proxy server for external request {}:{}.' . format ( self . default_args . tc_proxy_host , self . default_ar...
Return an instance of the Request Class .
27,711
def resource ( self , resource_type ) : try : resource = getattr ( self . resources , self . safe_rt ( resource_type ) ) ( self ) except AttributeError : self . _resources ( True ) resource = getattr ( self . resources , self . safe_rt ( resource_type ) ) ( self ) return resource
Get instance of Resource Class with dynamic type .
27,712
def results_tc ( self , key , value ) : if os . access ( self . default_args . tc_out_path , os . W_OK ) : results_file = '{}/results.tc' . format ( self . default_args . tc_out_path ) else : results_file = 'results.tc' new = True open ( results_file , 'a' ) . close ( ) with open ( results_file , 'r+' ) as fh : results...
Write data to results_tc file in TcEX specified directory .
27,713
def safe_indicator ( self , indicator , errors = 'strict' ) : if indicator is not None : try : indicator = quote ( self . s ( str ( indicator ) , errors = errors ) , safe = '~' ) except KeyError : indicator = quote ( bytes ( indicator ) , safe = '~' ) return indicator
Indicator encode value for safe HTTP request .
27,714
def safe_rt ( resource_type , lower = False ) : if resource_type is not None : resource_type = resource_type . replace ( ' ' , '_' ) if lower : resource_type = resource_type . lower ( ) return resource_type
Format the Resource Type .
27,715
def safe_group_name ( group_name , group_max_length = 100 , ellipsis = True ) : ellipsis_value = '' if ellipsis : ellipsis_value = ' ...' if group_name is not None and len ( group_name ) > group_max_length : group_name_array = group_name . split ( ' ' ) group_name = '' for word in group_name_array : word = u'{}' . form...
Truncate group name to match limit breaking on space and optionally add an ellipsis .
27,716
def safe_url ( self , url , errors = 'strict' ) : if url is not None : url = quote ( self . s ( url , errors = errors ) , safe = '~' ) return url
URL encode value for safe HTTP request .
27,717
def session ( self ) : if self . _session is None : from . tcex_session import TcExSession self . _session = TcExSession ( self ) return self . _session
Return an instance of Requests Session configured for the ThreatConnect API .
27,718
def ti ( self ) : if self . _ti is None : from . tcex_ti import TcExTi self . _ti = TcExTi ( self ) return self . _ti
Include the Threat Intel Module .
27,719
def assignees ( self ) : if not self . can_update ( ) : self . _tcex . handle_error ( 910 , [ self . type ] ) for a in self . tc_requests . assignees ( self . api_type , self . api_sub_type , self . unique_id ) : yield a
Gets the task assignees
27,720
def escalatees ( self ) : if not self . can_update ( ) : self . _tcex . handle_error ( 910 , [ self . type ] ) for e in self . tc_requests . escalatees ( self . api_type , self . api_sub_type , self . unique_id ) : yield e
Gets the task escalatees
27,721
def read ( self , key ) : key = quote ( key , safe = '~' ) url = '/internal/playbooks/keyValue/{}' . format ( key ) r = self . tcex . session . get ( url ) data = r . content if data is not None and not isinstance ( data , str ) : data = str ( r . content , 'utf-8' ) return data
Read data from remote KV store for the provided key .
27,722
def can_create ( self ) : if ( self . data . get ( 'key_name' ) and self . data . get ( 'value_name' ) and self . data . get ( 'value_type' ) ) : return True return False
If the key_name value_name and value_type has been provided returns that the Registry Key can be created otherwise returns that the Registry Key cannot be created .
27,723
def metric_create ( self ) : body = { 'dataType' : self . _metric_data_type , 'description' : self . _metric_description , 'interval' : self . _metric_interval , 'name' : self . _metric_name , 'keyedValues' : self . _metric_keyed , } self . tcex . log . debug ( 'metric body: {}' . format ( body ) ) r = self . tcex . se...
Create the defined metric .
27,724
def metric_find ( self ) : params = { 'resultLimit' : 50 , 'resultStart' : 0 } while True : if params . get ( 'resultStart' ) >= params . get ( 'resultLimit' ) : break r = self . tcex . session . get ( '/v2/customMetrics' , params = params ) if not r . ok or 'application/json' not in r . headers . get ( 'content-type' ...
Find the Metric by name .
27,725
def add ( self , value , date = None , return_value = False , key = None ) : data = { } if self . _metric_id is None : self . tcex . handle_error ( 715 , [ self . _metric_name ] ) body = { 'value' : value } if date is not None : body [ 'date' ] = self . tcex . utils . format_datetime ( date , date_format = '%Y-%m-%dT%H...
Add metrics data to collection .
27,726
def add_keyed ( self , value , key , date = None , return_value = False ) : return self . add ( value , date , return_value , key )
Add keyed metrics data to collection .
27,727
def hget ( self , key ) : data = self . r . hget ( self . hash , key ) if data is not None and not isinstance ( data , str ) : data = str ( self . r . hget ( self . hash , key ) , 'utf-8' ) return data
Read data from Redis for the provided key .
27,728
def _load_secure_params ( self ) : self . tcex . log . info ( 'Loading secure params.' ) r = self . tcex . session . get ( '/internal/job/execution/parameters' ) if not r . ok or r . headers . get ( 'content-type' ) != 'application/json' : err = r . text or r . reason self . tcex . exit ( 1 , 'Error retrieving secure p...
Load secure params from the API .
27,729
def _results_tc_args ( self ) : results = [ ] if os . access ( self . default_args . tc_out_path , os . W_OK ) : result_file = '{}/results.tc' . format ( self . default_args . tc_out_path ) else : result_file = 'results.tc' if os . path . isfile ( result_file ) : with open ( result_file , 'r' ) as rh : results = rh . r...
Read data from results_tc file from previous run of app .
27,730
def _unknown_args ( self , args ) : for u in args : self . tcex . log . warning ( u'Unsupported arg found ({}).' . format ( u ) )
Log argparser unknown arguments .
27,731
def args_update ( self ) : for key , value in self . _config_data . items ( ) : setattr ( self . _default_args , key , value )
Update the argparser namespace with any data from configuration file .
27,732
def config_file ( self , filename ) : if os . path . isfile ( filename ) : with open ( filename , 'r' ) as fh : self . _config_data = json . load ( fh ) else : self . tcex . log . error ( 'Could not load configuration file "{}".' . format ( filename ) )
Load configuration data from provided file and inject values into sys . argv .
27,733
def default_args ( self ) : if self . _default_args is None : self . _default_args , unknown = self . parser . parse_known_args ( ) self . tcex . _logger ( ) if self . _default_args . tc_aot_enabled : params = self . tcex . playbook . aot_blpop ( ) self . inject_params ( params ) elif self . _default_args . tc_secure_p...
Parse args and return default args .
27,734
def inject_params ( self , params ) : for arg , value in params . items ( ) : cli_arg = '--{}' . format ( arg ) if cli_arg in sys . argv : self . tcex . log . debug ( 'skipping existing arg: {}' . format ( cli_arg ) ) continue param_data = self . tcex . install_json_params . get ( arg ) or { } if param_data . get ( 'ty...
Inject params into sys . argv from secureParams API AOT or user provided .
27,735
def many ( self ) : for i in self . tc_requests . many ( self . api_type , None , self . api_entity ) : yield i
Gets all of the owners available .
27,736
def dns_resolution ( self ) : if not self . can_update ( ) : self . _tcex . handle_error ( 910 , [ self . type ] ) return self . tc_requests . dns_resolution ( self . api_type , self . api_sub_type , self . unique_id , owner = self . owner )
Updates the Host DNS resolution
27,737
def _create_tcex_dirs ( ) : dirs = [ 'tcex.d' , 'tcex.d/data' , 'tcex.d/profiles' ] for d in dirs : if not os . path . isdir ( d ) : os . makedirs ( d )
Create tcex . d directory and sub directories .
27,738
def expand_valid_values ( valid_values ) : if '${GROUP_TYPES}' in valid_values : valid_values . remove ( '${GROUP_TYPES}' ) valid_values . extend ( [ 'Adversary' , 'Campaign' , 'Document' , 'Email' , 'Event' , 'Incident' , 'Intrusion Set' , 'Signature' , 'Task' , 'Threat' , ] ) elif '${OWNERS}' in valid_values : valid_...
Expand supported playbook variables to their full list .
27,739
def gen_permutations ( self , index = 0 , args = None ) : if args is None : args = [ ] try : name = self . layout_json_names [ index ] display = self . layout_json_params . get ( name , { } ) . get ( 'display' ) input_type = self . install_json_params ( ) . get ( name , { } ) . get ( 'type' ) if self . validate_layout_...
Iterate recursively over layout . json parameter names .
27,740
def load_profiles ( self ) : if not os . path . isfile ( 'tcex.json' ) : msg = 'The tcex.json config file is required.' sys . exit ( msg ) self . _create_tcex_dirs ( ) with open ( 'tcex.json' , 'r+' ) as fh : data = json . load ( fh ) if data . get ( 'profiles' ) is not None : print ( '{}{}Migrating profiles from tcex....
Return configuration data .
27,741
def load_profiles_from_file ( self , fqfn ) : if self . args . verbose : print ( 'Loading profiles from File: {}{}{}' . format ( c . Style . BRIGHT , c . Fore . MAGENTA , fqfn ) ) with open ( fqfn , 'r+' ) as fh : data = json . load ( fh ) for profile in data : self . profile_update ( profile ) if self . args . action ...
Load profiles from file .
27,742
def print_permutations ( self ) : index = 0 permutations = [ ] for p in self . _input_permutations : permutations . append ( { 'index' : index , 'args' : p } ) index += 1 with open ( 'permutations.json' , 'w' ) as fh : json . dump ( permutations , fh , indent = 2 ) print ( 'All permutations written to the "permutations...
Print all valid permutations .
27,743
def profile_create ( self ) : if self . args . profile_name in self . profiles : self . handle_error ( 'Profile "{}" already exists.' . format ( self . args . profile_name ) ) ij = self . load_install_json ( self . args . ij ) print ( 'Building Profile: {}{}{}' . format ( c . Style . BRIGHT , c . Fore . CYAN , self . a...
Create a profile .
27,744
def profile_delete ( self ) : self . validate_profile_exists ( ) profile_data = self . profiles . get ( self . args . profile_name ) fqfn = profile_data . get ( 'fqfn' ) with open ( fqfn , 'r+' ) as fh : data = json . load ( fh ) for profile in data : if profile . get ( 'profile_name' ) == self . args . profile_name : ...
Delete an existing profile .
27,745
def profile_settings_args ( self , ij , required ) : if self . args . permutation_id is not None : if 'sqlite3' not in sys . modules : print ( 'The sqlite3 module needs to be build-in to Python for this feature.' ) sys . exit ( 1 ) profile_args = self . profile_settings_args_layout_json ( required ) else : profile_args...
Return args based on install . json or layout . json params .
27,746
def profile_settings_args_install_json ( self , ij , required ) : profile_args = { } for p in ij . get ( 'params' ) or [ ] : if p . get ( 'required' , False ) != required and required is not None : continue if p . get ( 'type' ) . lower ( ) == 'boolean' : profile_args [ p . get ( 'name' ) ] = self . _to_bool ( p . get ...
Return args based on install . json params .
27,747
def profile_settings_args_layout_json ( self , required ) : profile_args = { } self . db_create_table ( self . input_table , self . install_json_params ( ) . keys ( ) ) self . db_insert_record ( self . input_table , self . install_json_params ( ) . keys ( ) ) self . gen_permutations ( ) try : for pn in self . _input_pe...
Return args based on layout . json and conditional rendering .
27,748
def profile_setting_default_args ( ij ) : profile_default_args = OrderedDict ( ) profile_default_args [ 'api_default_org' ] = '$env.API_DEFAULT_ORG' profile_default_args [ 'api_access_id' ] = '$env.API_ACCESS_ID' profile_default_args [ 'api_secret_key' ] = '$envs.API_SECRET_KEY' profile_default_args [ 'tc_api_path' ] =...
Build the default args for this profile .
27,749
def profile_settings_validations ( self ) : ij = self . load_install_json ( self . args . ij ) validations = { 'rules' : [ ] , 'outputs' : [ ] } job_id = randint ( 1000 , 9999 ) output_variables = ij . get ( 'playbook' , { } ) . get ( 'outputVariables' ) or [ ] if self . args . permutation_id is not None : output_varia...
Create 2 default validations rules for each output variable .
27,750
def profile_update ( self , profile ) : if profile . get ( 'install_json' ) is None : print ( '{}{}Missing install_json parameter for profile {}.' . format ( c . Style . BRIGHT , c . Fore . YELLOW , profile . get ( 'profile_name' ) ) ) self . profile_update_args_v2 ( profile ) self . profile_update_args_v3 ( profile ) ...
Update an existing profile with new parameters or remove deprecated parameters .
27,751
def profile_update_args_v2 ( self , profile ) : ij = self . load_install_json ( profile . get ( 'install_json' , 'install.json' ) ) if ( profile . get ( 'args' , { } ) . get ( 'app' ) is None and profile . get ( 'args' , { } ) . get ( 'default' ) is None ) : _args = profile . pop ( 'args' ) profile [ 'args' ] = { } pro...
Update v1 profile args to v2 schema for args .
27,752
def profile_update_args_v3 ( self , profile ) : ij = self . load_install_json ( profile . get ( 'install_json' , 'install.json' ) ) ijp = self . install_json_params ( ij ) if ( profile . get ( 'args' , { } ) . get ( 'app' , { } ) . get ( 'optional' ) is None and profile . get ( 'args' , { } ) . get ( 'app' , { } ) . ge...
Update v1 profile args to v3 schema for args .
27,753
def profile_update_schema ( profile ) : if profile . get ( 'autoclear' ) is None : print ( '{}{}Profile Update: Adding new "autoclear" parameter.' . format ( c . Style . BRIGHT , c . Fore . YELLOW ) ) profile [ 'autoclear' ] = True for validation in profile . get ( 'validations' ) or [ ] : if validation . get ( 'data_t...
Update profile to latest schema .
27,754
def profile_write ( self , profile , outfile = None ) : if outfile is None : outfile = '{}.json' . format ( profile . get ( 'profile_name' ) . replace ( ' ' , '_' ) . lower ( ) ) fqpn = os . path . join ( self . profile_dir , outfile ) if os . path . isfile ( fqpn ) : print ( 'Append to File: {}{}{}' . format ( c . Sty...
Write the profile to the output directory .
27,755
def replace_validation ( self ) : self . validate_profile_exists ( ) profile_data = self . profiles . get ( self . args . profile_name ) redis_hash = profile_data . get ( 'data' , { } ) . get ( 'args' , { } ) . get ( 'tc_playbook_db_context' ) if redis_hash is None : self . handle_error ( 'Could not find redis hash (db...
Replace the validation configuration in the selected profile .
27,756
def validate ( self , profile ) : ij = self . load_install_json ( profile . get ( 'install_json' ) ) print ( '{}{}Profile: "{}".' . format ( c . Style . BRIGHT , c . Fore . BLUE , profile . get ( 'profile_name' ) ) ) for arg in self . profile_settings_args_install_json ( ij , None ) : if profile . get ( 'args' , { } ) ...
Check to see if any args are missing from profile .
27,757
def validate_layout_display ( self , table , display_condition ) : display = False if display_condition is None : display = True else : display_query = 'select count(*) from {} where {}' . format ( table , display_condition ) try : cur = self . db_conn . cursor ( ) cur . execute ( display_query . replace ( '"' , '' ) )...
Check to see if the display condition passes .
27,758
def validate_profile_exists ( self ) : if self . args . profile_name not in self . profiles : self . handle_error ( 'Could not find profile "{}"' . format ( self . args . profile_name ) )
Validate the provided profiles name exists .
27,759
def _build_indexes ( self ) : if isinstance ( self . _data , list ) : for d in self . _data : if not isinstance ( d , dict ) : err = u'Cannot build index for non Dict type.' self . _tcex . log . error ( err ) raise RuntimeError ( err ) data_obj = DataObj ( d ) self . _master_index . setdefault ( id ( data_obj ) , data_...
Build indexes from data for fast filtering of data .
27,760
def _starts_with ( field , filter_value ) : valid = False if field . startswith ( filter_value ) : valid = True return valid
Validate field starts with provided value .
27,761
def filter_data ( self , field , filter_value , filter_operator , field_converter = None ) : data = [ ] if self . _indexes . get ( field ) is not None : data = self . _index_filter ( self . _indexes . get ( field ) , filter_value , filter_operator , field_converter ) return set ( data )
Filter the data given the provided .
27,762
def operator ( self ) : return { 'EQ' : operator . eq , 'NE' : operator . ne , 'GT' : operator . gt , 'GE' : operator . ge , 'LT' : operator . lt , 'LE' : operator . le , 'SW' : self . _starts_with , 'IN' : self . _in , 'NI' : self . _ni , }
Supported Filter Operators
27,763
def groups ( self , group_type = None , filters = None , params = None ) : group = self . _tcex . ti . group ( group_type ) for g in self . tc_requests . groups_from_tag ( group , self . name , filters = filters , params = params ) : yield g
Gets all groups from a tag .
27,764
def indicators ( self , indicator_type = None , filters = None , params = None ) : indicator = self . _tcex . ti . indicator ( indicator_type ) for i in self . tc_requests . indicators_from_tag ( indicator , self . name , filters = filters , params = params ) : yield i
Gets all indicators from a tag .
27,765
def victims ( self , filters = None , params = None ) : victim = self . _tcex . ti . victim ( None ) for v in self . tc_requests . victims_from_tag ( victim , self . name , filters = filters , params = params ) : yield v
Gets all victims from a tag .
27,766
def _logger ( ) : logger = logging . getLogger ( __name__ ) logger . setLevel ( logging . DEBUG ) ch = logging . StreamHandler ( sys . stdout ) ch . setLevel ( logging . DEBUG ) logger . addHandler ( ch ) return logger
Initialize basic stream logger .
27,767
def _renew_token ( self , retry = True ) : self . renewing = True self . log . info ( 'Renewing ThreatConnect Token' ) self . log . info ( 'Current Token Expiration: {}' . format ( self . _token_expiration ) ) try : params = { 'expiredToken' : self . _token } url = '{}/appAuth' . format ( self . _token_url ) r = get ( ...
Renew expired ThreatConnect Token .
27,768
def _api_arguments ( self ) : self . add_argument ( '--tc_token' , default = None , help = 'ThreatConnect API Token' ) self . add_argument ( '--tc_token_expires' , default = None , help = 'ThreatConnect API Token Expiration Time' , type = int , ) self . add_argument ( '--api_access_id' , default = None , help = 'Threat...
Argument specific to working with TC API .
27,769
def _batch_arguments ( self ) : self . add_argument ( '--batch_action' , choices = [ 'Create' , 'Delete' ] , default = self . _batch_action , help = 'Action for the batch job' , ) self . add_argument ( '--batch_chunk' , default = self . _batch_chunk , help = 'Max number of indicators per batch' , type = int , ) self . ...
Arguments specific to Batch API writes .
27,770
def _playbook_arguments ( self ) : self . add_argument ( '--tc_playbook_db_type' , default = self . _tc_playbook_db_type , help = 'Playbook DB type' ) self . add_argument ( '--tc_playbook_db_context' , default = self . _tc_playbook_db_context , help = 'Playbook DB Context' , ) self . add_argument ( '--tc_playbook_db_pa...
Argument specific to playbook apps .
27,771
def _standard_arguments ( self ) : self . add_argument ( '--api_default_org' , default = None , help = 'ThreatConnect api default Org' ) self . add_argument ( '--tc_action_channel' , default = None , help = 'ThreatConnect AOT action channel' ) self . add_argument ( '--tc_aot_enabled' , action = 'store_true' , help = 'T...
These are the standard args passed to every TcEx App .
27,772
def run ( self ) : self . batch = self . tcex . batch ( self . args . tc_owner ) request = self . tcex . request ( ) with request . session as s : r = s . get ( self . url ) if r . ok : decoded_content = r . content . decode ( 'utf-8' ) . splitlines ( ) reader = csv . reader ( decoded_content , delimiter = ',' , quotec...
Run main App logic .
27,773
def get ( self , url_path ) : request_url = "%s%s" % ( self . _url , quote ( url_path . encode ( "utf_8" ) ) ) response = self . session . get ( request_url ) if response . status_code == 200 and self . verbose : print "GET %s: Success." % request_url elif response . status_code >= 400 : error_handler ( JSSGetError , r...
GET a url handle errors and return an etree .
27,774
def post ( self , obj_class , url_path , data ) : request_url = "%s%s" % ( self . _url , url_path ) data = ElementTree . tostring ( data ) response = self . session . post ( request_url , data = data ) if response . status_code == 201 and self . verbose : print "POST %s: Success" % request_url elif response . status_co...
POST an object to the JSS . For creating new objects only .
27,775
def put ( self , url_path , data ) : request_url = "%s%s" % ( self . _url , url_path ) data = ElementTree . tostring ( data ) response = self . session . put ( request_url , data ) if response . status_code == 201 and self . verbose : print "PUT %s: Success." % request_url elif response . status_code >= 400 : error_han...
Update an existing object on the JSS .
27,776
def delete ( self , url_path , data = None ) : request_url = "%s%s" % ( self . _url , url_path ) if data : response = self . session . delete ( request_url , data = data ) else : response = self . session . delete ( request_url ) if response . status_code == 200 and self . verbose : print "DEL %s: Success." % request_u...
Delete an object from the JSS .
27,777
def _docstring_parameter ( obj_type , subset = False ) : docstring = ( "Flexibly search the JSS for objects of type {}.\n\n\tArgs:\n\t\t" "Data: Allows different types to conduct different types of " "searches. Argument of type:\n\t\t\tNone (or Provide no argument) " "to search for all objects.\n\t\t\tInt to search for...
Decorator for adding _docstring to repetitive methods .
27,778
def pickle_all ( self , path ) : all_search_methods = [ ( name , self . __getattribute__ ( name ) ) for name in dir ( self ) if name [ 0 ] . isupper ( ) ] all_objects = { } for method in all_search_methods : result = method [ 1 ] ( ) if isinstance ( result , JSSFlatObject ) : all_objects [ method [ 0 ] ] = result else ...
Back up entire JSS to a Python Pickle .
27,779
def from_pickle ( cls , path ) : with open ( os . path . expanduser ( path ) , "rb" ) as pickle : return cPickle . Unpickler ( pickle ) . load ( )
Load all objects from pickle file and return as dict .
27,780
def write_all ( self , path ) : all_search_methods = [ ( name , self . __getattribute__ ( name ) ) for name in dir ( self ) if name [ 0 ] . isupper ( ) ] all_objects = { } for method in all_search_methods : result = method [ 1 ] ( ) if isinstance ( result , JSSFlatObject ) : all_objects [ method [ 0 ] ] = result else :...
Back up entire JSS to XML file .
27,781
def load_from_xml ( self , path ) : with open ( os . path . expanduser ( path ) , "r" ) as ifile : et = ElementTree . parse ( ifile ) root = et . getroot ( ) all_objects = { } for child in root : obj_type = self . __getattribute__ ( child . tag ) objects = [ obj_type ( obj ) for obj in child ] all_objects [ child . tag...
Load all objects from XML file and return as dict .
27,782
def get_object ( self , obj_class , data = None , subset = None ) : if subset : if not isinstance ( subset , list ) : if isinstance ( subset , basestring ) : subset = subset . split ( "&" ) else : raise TypeError if data is None : return self . get_list ( obj_class , data , subset ) elif isinstance ( data , ( basestrin...
Return a subclassed JSSObject instance by querying for existing objects or posting a new object .
27,783
def get_list ( self , obj_class , data , subset ) : url = obj_class . get_url ( data ) if obj_class . can_list and obj_class . can_get : if ( subset and len ( subset ) == 1 and subset [ 0 ] . upper ( ) == "BASIC" ) and obj_class is jssobjects . Computer : url += "/subset/basic" result = self . jss . get ( url ) if obj_...
Get a list of objects as JSSObjectList .
27,784
def get_individual_object ( self , obj_class , data , subset ) : if obj_class . can_get : url = obj_class . get_url ( data ) if subset : if not "general" in subset : subset . append ( "general" ) url += "/subset/%s" % "&" . join ( subset ) xmldata = self . jss . get ( url ) if xmldata . find ( "size" ) is not None : re...
Return a JSSObject of type obj_class searched for by data .
27,785
def _build_jss_object_list ( self , response , obj_class ) : response_objects = [ item for item in response if item is not None and item . tag != "size" ] objects = [ JSSListData ( obj_class , { i . tag : i . text for i in response_object } , self ) for response_object in response_objects ] return JSSObjectList ( self ...
Build a JSSListData object from response .
27,786
def convert_response_to_text ( response ) : errorlines = response . text . encode ( "utf-8" ) . split ( "\n" ) error = [ ] pattern = re . compile ( r"<p.*>(.*)</p>" ) for line in errorlines : content_line = re . search ( pattern , line ) if content_line : error . append ( content_line . group ( 1 ) ) return ". " . join...
Convert a JSS HTML response to plaintext .
27,787
def error_handler ( exception_cls , response ) : error = convert_response_to_text ( response ) exception = exception_cls ( "Response Code: %s\tResponse: %s" % ( response . status_code , error ) ) exception . status_code = response . status_code raise exception
Handle HTTP errors by formatting into strings .
27,788
def loop_until_valid_response ( prompt ) : responses = { "Y" : True , "YES" : True , "TRUE" : True , "N" : False , "NO" : False , "FALSE" : False } response = "" while response . upper ( ) not in responses : response = raw_input ( prompt ) return responses [ response . upper ( ) ]
Loop over entering input until it is a valid bool - ish response .
27,789
def indent_xml ( elem , level = 0 , more_sibs = False ) : i = "\n" pad = " " if level : i += ( level - 1 ) * pad num_kids = len ( elem ) if num_kids : if not elem . text or not elem . text . strip ( ) : elem . text = i + pad if level : elem . text += pad count = 0 for kid in elem : if kid . tag == "data" : kid . tex...
Indent an xml element object to prepare for pretty printing .
27,790
def element_repr ( self ) : pretty_data = copy . deepcopy ( self ) indent_xml ( pretty_data ) return ElementTree . tostring ( pretty_data ) . encode ( "utf-8" )
Return a string with indented XML data .
27,791
def sort ( self ) : super ( JSSObjectList , self ) . sort ( key = lambda k : k . id )
Sort list elements by ID .
27,792
def sort_by_name ( self ) : super ( JSSObjectList , self ) . sort ( key = lambda k : k . name )
Sort list elements by name .
27,793
def retrieve_by_id ( self , id_ ) : items_with_id = [ item for item in self if item . id == int ( id_ ) ] if len ( items_with_id ) == 1 : return items_with_id [ 0 ] . retrieve ( )
Return a JSSObject for the element with ID id_
27,794
def retrieve_all ( self , subset = None ) : get_object = self . factory . get_object obj_class = self . obj_class full_objects = [ get_object ( obj_class , list_obj . id , subset ) for list_obj in self ] return JSSObjectList ( self . factory , obj_class , full_objects )
Return a list of all JSSListData elements as full JSSObjects .
27,795
def pickle ( self , path ) : with open ( os . path . expanduser ( path ) , "wb" ) as pickle : cPickle . Pickler ( pickle , cPickle . HIGHEST_PROTOCOL ) . dump ( self )
Write objects to python pickle .
27,796
def readPlistFromString ( data ) : try : plistData = buffer ( data ) except TypeError , err : raise NSPropertyListSerializationException ( err ) dataObject , dummy_plistFormat , error = ( NSPropertyListSerialization . propertyListFromData_mutabilityOption_format_errorDescription_ ( plistData , NSPropertyListMutableCont...
Read a plist data from a string . Return the root object .
27,797
def writePlist ( dataObject , filepath ) : plistData , error = ( NSPropertyListSerialization . dataFromPropertyList_format_errorDescription_ ( dataObject , NSPropertyListXMLFormat_v1_0 , None ) ) if plistData is None : if error : error = error . encode ( 'ascii' , 'ignore' ) else : error = "Unknown error" raise NSPrope...
Write rootObject as a plist to filepath .
27,798
def writePlistToString ( rootObject ) : plistData , error = ( NSPropertyListSerialization . dataFromPropertyList_format_errorDescription_ ( rootObject , NSPropertyListXMLFormat_v1_0 , None ) ) if plistData is None : if error : error = error . encode ( 'ascii' , 'ignore' ) else : error = "Unknown error" raise NSProperty...
Return rootObject as a plist - formatted string .
27,799
def _new ( self , name , ** kwargs ) : if self . _name_path : parent = self for path_element in self . _name_path . split ( "/" ) : self . _set_xml_from_keys ( parent , ( path_element , None ) ) parent = parent . find ( path_element ) parent . text = name else : ElementTree . SubElement ( self , "name" ) . text = name ...
Create a new JSSObject with name and keys .