code
stringlengths
1
18.2k
def get(request, obj_id): """Returns a serialized object :param obj_id: ID of comment object :type obj_id: int :returns: json """ res = Result() c = Comment.objects.get(pk=obj_id) res.append(commentToJson(c)) return JsonResponse(res.asDict())
def post(request): """Returns a serialized object""" data = request.POST or json.loads(request.body)['body'] guid = data.get('guid', None) res = Result() if guid: obj = getObjectsFromGuids([guid,])[0] comment = Comment() comment.comment = data.get('comment', 'No comment') comment.user = request.user comment.user_name =...
def put(request, obj_id): """Updates the content of a comment :param obj_id: ID of comment object :type obj_id: int :returns: json """ res = Result() c = Comment.objects.get(pk=obj_id) data = request.PUT or json.loads(request.body)['body'] content = data.get('comment', None) if content: c.comment = content c.save() res...
def commentList(request): """Returns a rendered list of comments :returns: html """ if request.method == 'POST': return post(request) comments = [] guid = request.GET.get('guid', None) if guid: obj = getObjectsFromGuids([guid])[0] if obj.AssetType == 1: model = 'image' else: model = 'video' contenttype = ContentType.ob...
def emailComment(comment, obj, request): """Send an email to the author about a new comment""" if not obj.author.frog_prefs.get().json()['emailComments']: return if obj.author == request.user: return html = render_to_string('frog/comment_email.html', { 'user': comment.user, 'comment': comment.comment, 'object': obj, 'a...
def cluster_nodes(self): """Each node in a Redis Cluster has its view of the current cluster configuration, given by the set of known nodes, the state of the connection we have with such nodes, their flags, properties and assigned slots, and so forth. ``CLUSTER NODES`` provides all this information, that is, the curren...
more information, should be used for administrative tasks, debugging, and configuration inspections. It is also used by ``redis-trib`` in order to manage a cluster. .. versionadded:: 0.7.0 :rtype: list(:class:`~tredis.cluster.ClusterNode`) :raises: :exc:`~tredis.exceptions.RedisError` """ def format_response(result): v...
def sadd(self, key, *members): """Add the specified members to the set stored at key. Specified members that are already a member of this set are ignored. If key does not exist, a new set is created before adding the specified members. An error is returned when the value stored at key is not a set. Returns :data:`True`...
of items added to the set :rtype: bool, int """ return self._execute([b'SADD', key] + list(members), len(members))
def sdiffstore(self, destination, *keys): """This command is equal to :meth:`~tredis.RedisClient.sdiff`, but instead of returning the resulting set, it is stored in destination. If destination already exists, it is overwritten. .. note:: **Time complexity**: ``O(N)`` where ``N`` is the total number of elements in all g...
def sinterstore(self, destination, *keys): """This command is equal to :meth:`~tredis.RedisClient.sinter`, but instead of returning the resulting set, it is stored in destination. If destination already exists, it is overwritten. .. note:: **Time complexity**: ``O(N*M)`` worst case where ``N`` is the cardinality of the...
def smove(self, source, destination, member): """Move member from the set at source to the set at destination. This operation is atomic. In every given moment the element will appear to be a member of source or destination for other clients. If the source set does not exist or does not contain the specified element, no...
set key :type destination: :class:`str`, :class:`bytes` :param member: The member value to move :type member: :class:`str`, :class:`bytes` :rtype: bool :raises: :exc:`~tredis.exceptions.RedisError` """ return self._execute([b'SMOVE', source, destination, member], 1)
def spop(self, key, count=None): """Removes and returns one or more random elements from the set value store at key. This operation is similar to :meth:`~tredis.RedisClient.srandmember`, that returns one or more random elements from a set but does not remove it. The count argument will be available in a later version a...
key: :class:`str`, :class:`bytes` :param int count: The number of members to return :rtype: bytes, list :raises: :exc:`~tredis.exceptions.RedisError` """ command = [b'SPOP', key] if count: # pragma: nocover command.append(ascii(count).encode('ascii')) return self._execute(command)
def srandmember(self, key, count=None): """When called with just the key argument, return a random element from the set value stored at key. Starting from Redis version 2.6, when called with the additional count argument, return an array of count distinct elements if count is positive. If called with a negative count t...
count argument ``O(1)``, otherwise ``O(N)`` where ``N`` is the absolute value of the passed count. :param key: The key to get one or more random members from :type key: :class:`str`, :class:`bytes` :param int count: The number of members to return :rtype: bytes, list :raises: :exc:`~tredis.exceptions.RedisError` """ co...
def srem(self, key, *members): """Remove the specified members from the set stored at key. Specified members that are not a member of this set are ignored. If key does not exist, it is treated as an empty set and this command returns ``0``. An error is returned when the value stored at key is not a set. Returns :data:`...
:exc:`~tredis.exceptions.RedisError` """ return self._execute([b'SREM', key] + list(members), len(members))
def sscan(self, key, cursor=0, pattern=None, count=None): """The :meth:`~tredis.RedisClient.sscan` command and the closely related commands :meth:`~tredis.RedisClient.scan`, :meth:`~tredis.RedisClient.hscan` and :meth:`~tredis.RedisClient.zscan` are used in order to incrementally iterate over a collection of elements. ...
server is ``0``. For more information on :meth:`~tredis.RedisClient.scan`, visit the `Redis docs on scan <http://redis.io/commands/scan>`_. .. note:: **Time complexity**: ``O(1)`` for every call. ``O(N)`` for a complete iteration, including enough command calls for the cursor to return back to ``0``. ``N`` is the numbe...
redis :rtype: tuple(int, list) """ return int(value[0]), value[1] command = [b'SSCAN', key, ascii(cursor).encode('ascii')] if pattern: command += [b'MATCH', pattern] if count: command += [b'COUNT', ascii(count).encode('ascii')] return self._execute(command, format_callback=format_response)
def sunionstore(self, destination, *keys): """This command is equal to :meth:`~tredis.RedisClient.sunion`, but instead of returning the resulting set, it is stored in destination. If destination already exists, it is overwritten. .. note:: **Time complexity**: ``O(N)`` where ``N`` is the total number of elements in all...
def _extract_id(self) -> str: """ Get video_id needed to obtain the real_url of the video. Raises: VideoIdNotMatchedError: If video_id is not matched with regular expression. """ match = re.match(self._VALID_URL, self.url) if match: return match.group('video_id') else: raise VideoIdNotMatchedError
def _process_info(raw_info: VideoInfo) -> VideoInfo: """Process raw information about the video (parse date, etc.).""" raw_date = raw_info.date date = datetime.strptime(raw_date, '%Y-%m-%d %H:%M') # 2018-04-05 17:00 video_info = raw_info._replace(date=date) return video_info
def convert_time_units(t): """ Convert time in seconds into reasonable time units. """ if t == 0: return '0 s' order = log10(t) if -9 < order < -6: time_units = 'ns' factor = 1000000000 elif -6 <= order < -3: time_units = 'us' factor = 1000000 elif -3 <= order < -1: time_units = 'ms' factor = 1000. elif -1 <= order: ti...
def globalize_indentation(src): """ Strip the indentation level so the code runs in the global scope. """ lines = src.splitlines() indent = len(lines[0]) - len(lines[0].strip(' ')) func_src = '' for ii, l in enumerate(src.splitlines()): line = l[indent:] func_src += line + '\n' return func_src
def remove_decorators(src): """ Remove decorators from the source code """ src = src.strip() src_lines = src.splitlines() multi_line = False n_deleted = 0 for n in range(len(src_lines)): line = src_lines[n - n_deleted].strip() if (line.startswith('@') and 'Benchmark' in line) or multi_line: del src_lines[n - n_deleted]...
def walk_tree(start, attr): """ Recursively walk through a tree relationship. This iterates a tree in a top-down approach, fully reaching the end of a lineage before moving onto the next sibling of that generation. """ path = [start] for child in path: yield child idx = path.index(child) for grandchild in reversed(geta...
def validate(self, benchmarks): """ Execute the code once to get it's results (to be used in function validation). Compare the result to the first function in the group. :param benchmarks: list of benchmarks to validate. """ class_code = self.setup_src instance_creation = '\ninstance = {}'.format(self.stmt) for i, benc...
def is_cache_valid(self): ''' Determines if the cache files have expired, or if it is still valid ''' if os.path.isfile(self.cache_path_cache): mod_time = os.path.getmtime(self.cache_path_cache) current_time = time() if (mod_time + self.cache_max_age) > current_time: if os.path.isfile(self.cache_path_index): return Tru...
def read_settings(self, configfile): ''' Reads the settings from the ec2.ini file ''' if six.PY3: config = configparser.ConfigParser() else: config = configparser.SafeConfigParser() config.read(configfile) # is eucalyptus? self.eucalyptus_host = None self.eucalyptus = False if config.has_option('ec2', 'eucalyptus'): se...
= True if config.has_option('ec2', 'elasticache'): self.elasticache_enabled = config.getboolean('ec2', 'elasticache') # Return all EC2 instances? if config.has_option('ec2', 'all_instances'): self.all_instances = config.getboolean('ec2', 'all_instances') else: self.all_instances = False # Instance states to be gathered...
self.all_elasticache_replication_groups = False # Return all ElastiCache clusters? (if ElastiCache is enabled) if (config.has_option('ec2', 'all_elasticache_clusters') and self.elasticache_enabled): self.all_elasticache_clusters = config.getboolean( 'ec2', 'all_elasticache_clusters') else: self.all_elasticache_clusters...
# Replace dash or not in group names if config.has_option('ec2', 'replace_dash_in_groups'): self.replace_dash_in_groups = config.getboolean('ec2', 'replace_dash_in_groups') else: self.replace_dash_in_groups = True # Configure which groups should be created. group_by_options = [ 'group_by_instance_id', 'group_by_region'...
self.pattern_exclude = None # Instance filters (see boto and EC2 API docs). Ignore invalid filters. self.ec2_instance_filters = defaultdict(list) if config.has_option('ec2', 'instance_filters'): for instance_filter in config.get('ec2', 'instance_filters', '').split(','): instance_filter = instance_filter.strip() if not...
def do_api_calls_update_cache(self): ''' Do API calls to each region, and save data in cache files ''' if self.route53_enabled: self.get_route53_records() for region in self.regions: self.get_instances_by_region(region) if self.rds_enabled: self.get_rds_instances_by_region(region) if self.elasticache_enabled: self.get_...
def connect(self, region): ''' create connection to api server''' if self.eucalyptus: conn = boto.connect_euca(host=self.eucalyptus_host) conn.APIVersion = '2010-08-31' else: conn = self.connect_to_aws(ec2, region) return conn
def boto_fix_security_token_in_profile(self, connect_args): ''' monkey patch for boto issue boto/boto#2100 ''' profile = 'profile ' + self.boto_profile if boto.config.has_option(profile, 'aws_security_token'): connect_args['security_token'] = boto.config.get(profile, 'aws_security_token') return connect_args
def get_instances_by_region(self, region): ''' Makes an AWS EC2 API call to the list of instances in a particular region ''' try: conn = self.connect(region) reservations = [] if self.ec2_instance_filters: for filter_key, filter_values in self.ec2_instance_filters.items(): reservations.extend(conn.get_all_instances(fil...
def get_rds_instances_by_region(self, region): ''' Makes an AWS API call to the list of RDS instances in a particular region ''' try: conn = self.connect_to_aws(rds, region) if conn: instances = conn.get_all_dbinstances() for instance in instances: self.add_rds_instance(instance, region) except boto.exception.BotoServe...
def get_elasticache_clusters_by_region(self, region): ''' Makes an AWS API call to the list of ElastiCache clusters (with nodes' info) in a particular region.''' # ElastiCache boto module doesn't provide a get_all_intances method, # that's why we need to call describe directly (it would be called by # the shorthand met...
get_list # method in the AWSQueryConnection. Let's do the work manually clusters = response['DescribeCacheClustersResponse']['DescribeCacheClustersResult']['CacheClusters'] except KeyError as e: error = "ElastiCache query to AWS failed (unexpected format)." self.fail_with_error(error, 'getting ElastiCache clusters') fo...
def get_elasticache_replication_groups_by_region(self, region): ''' Makes an AWS API call to the list of ElastiCache replication groups in a particular region.''' # ElastiCache boto module doesn't provide a get_all_intances method, # that's why we need to call describe directly (it would be called by # the shorthand me...
as e: error = "ElastiCache [Replication Groups] query to AWS failed (unexpected format)." self.fail_with_error(error, 'getting ElastiCache clusters') for replication_group in replication_groups: self.add_elasticache_replication_group(replication_group, region)
def get_auth_error_message(self): ''' create an informative error message if there is an issue authenticating''' errors = ["Authentication error retrieving ec2 inventory."] if None in [os.environ.get('AWS_ACCESS_KEY_ID'), os.environ.get('AWS_SECRET_ACCESS_KEY')]: errors.append(' - No AWS_ACCESS_KEY_ID or AWS_SECRET_ACC...
def fail_with_error(self, err_msg, err_operation=None): '''log an error to std err for ansible-playbook to consume and exit''' if err_operation: err_msg = 'ERROR: "{err_msg}", while: {err_operation}'.format( err_msg=err_msg, err_operation=err_operation) sys.stderr.write(err_msg) sys.exit(1)
def add_instance(self, instance, region): ''' Adds an instance to the inventory and index, as long as it is addressable ''' # Only return instances with desired instance states if instance.state not in self.ec2_instance_states: return # Select the best destination address if instance.subnet_id: dest = getattr(instance,...
index self.index[dest] = [region, instance.id] # Inventory: Group by instance ID (always a group of 1) if self.group_by_instance_id: self.inventory[instance.id] = [dest] if self.nested_groups: self.push_group(self.inventory, 'instances', instance.id) # Inventory: Group by region if self.group_by_region: self.push(self....
# Inventory: Group by VPC if self.group_by_vpc_id and instance.vpc_id: vpc_id_name = self.to_safe('vpc_id_' + instance.vpc_id) self.push(self.inventory, vpc_id_name, dest) if self.nested_groups: self.push_group(self.inventory, 'vpcs', vpc_id_name) # Inventory: Group by security group if self.group_by_security_group: tr...
k), key) # Inventory: Group by Route53 domain names if enabled if self.route53_enabled and self.group_by_route53_names: route53_names = self.get_instance_route53_names(instance) for name in route53_names: self.push(self.inventory, name, dest) if self.nested_groups: self.push_group(self.inventory, 'route53', name) # Glo...
def add_rds_instance(self, instance, region): ''' Adds an RDS instance to the inventory and index, as long as it is addressable ''' # Only want available instances unless all_rds_instances is True if not self.all_rds_instances and instance.status != 'available': return # Select the best destination address dest = insta...
Group by instance type if self.group_by_instance_type: type_name = self.to_safe('type_' + instance.instance_class) self.push(self.inventory, type_name, dest) if self.nested_groups: self.push_group(self.inventory, 'types', type_name) # Inventory: Group by VPC if self.group_by_vpc_id and instance.subnet_group and instanc...
self.inventory["_meta"]["hostvars"][dest] = self.get_host_info_dict_from_instance(instance)
def add_elasticache_cluster(self, cluster, region): ''' Adds an ElastiCache cluster to the inventory and index, as long as it's nodes are addressable ''' # Only want available clusters unless all_elasticache_clusters is True if not self.all_elasticache_clusters and cluster['CacheClusterStatus'] != 'available': return #...
self.inventory[cluster['CacheClusterId']] = [dest] if self.nested_groups: self.push_group(self.inventory, 'instances', cluster['CacheClusterId']) # Inventory: Group by region if self.group_by_region and not is_redis: self.push(self.inventory, region, dest) if self.nested_groups: self.push_group(self.inventory, 'regions...
SG # the query can return None here and cause an error. if 'SecurityGroups' in cluster and cluster['SecurityGroups'] is not None: for security_group in cluster['SecurityGroups']: key = self.to_safe("security_group_" + security_group['SecurityGroupId']) self.push(self.inventory, key, dest) if self.nested_groups: self.pu...
def add_elasticache_node(self, node, cluster, region): ''' Adds an ElastiCache node to the inventory and index, as long as it is addressable ''' # Only want available nodes unless all_elasticache_nodes is True if not self.all_elasticache_nodes and node['CacheNodeStatus'] != 'available': return # Select the best destina...
self.push_group(self.inventory, region, cluster['PreferredAvailabilityZone']) self.push_group(self.inventory, 'zones', cluster['PreferredAvailabilityZone']) # Inventory: Group by node type if self.group_by_instance_type: type_name = self.to_safe('type_' + cluster['CacheNodeType']) self.push(self.inventory, type_name, d...
if self.nested_groups: self.push_group(self.inventory, 'elasticache_engines', self.to_safe("elasticache_" + cluster['Engine'])) # Inventory: Group by parameter group (done at cluster level) # Inventory: Group by replication group (done at cluster level) # Inventory: Group by ElastiCache Cluster if self.group_by_elastic...
def add_elasticache_replication_group(self, replication_group, region): ''' Adds an ElastiCache replication group to the inventory and index ''' # Only want available clusters unless all_elasticache_replication_groups is True if not self.all_elasticache_replication_groups and replication_group['Status'] != 'available':...
not available in the current # AWS API version for replication groups # Inventory: Group by security group (doesn't apply to replication groups) # Check this value in cluster level # Inventory: Group by engine (replication groups are always Redis) if self.group_by_elasticache_engine: self.push(self.inventory, 'elastica...
def get_route53_records(self): ''' Get and store the map of resource records to domain names that point to them. ''' r53_conn = route53.Route53Connection() all_zones = r53_conn.get_zones() route53_zones = [ zone for zone in all_zones if zone.name[:-1] not in self.route53_excluded_zones ] self.route53_records = {} for z...
def get_instance_route53_names(self, instance): ''' Check if an instance is referenced in the records we have from Route53. If it is, return the list of domain names pointing to said instance. If nothing points to it, return an empty list. ''' instance_attributes = [ 'public_dns_name', 'private_dns_name', 'ip_address',...
def get_host_info_dict_from_describe_dict(self, describe_dict): ''' Parses the dictionary returned by the API call into a flat list of parameters. This method should be used only when 'describe' is used directly because Boto doesn't provide specific classes. ''' # I really don't agree with prefixing everything with 'ec...
# Target: Redis Replication Groups if key == 'ec2_node_groups' and value: host_info['ec2_endpoint_address'] = value[0]['PrimaryEndpoint']['Address'] host_info['ec2_endpoint_port'] = value[0]['PrimaryEndpoint']['Port'] replica_count = 0 for node in value[0]['NodeGroupMembers']: if node['CurrentRole'] == 'primary': host_...
None: sg_ids = [] for sg in value: sg_ids.append(sg['SecurityGroupId']) host_info["ec2_security_group_ids"] = ','.join([str(i) for i in sg_ids]) # Target: Everything # Preserve booleans and integers elif type(value) in [int, bool]: host_info[key] = value # Target: Everything # Sanitize string values elif isinstance(val...
def get_host(self, host): ''' Get variables about a specific host ''' if len(self.index) == 0: # Need to load index from cache self.load_index_from_cache() if not host in self.index: # try updating the cache self.do_api_calls_update_cache() if not host in self.index: # host might not exist anymore return {} (region, in...
def push(self, my_dict, key, element): ''' Push an element onto an array that may not have been defined in the dict ''' group_info = my_dict.setdefault(key, []) if isinstance(group_info, dict): host_list = group_info.setdefault('hosts', []) host_list.append(element) else: group_info.append(element)
def push_group(self, my_dict, key, element): ''' Push a group as a child of another group. ''' parent_group = my_dict.setdefault(key, {}) if not isinstance(parent_group, dict): parent_group = my_dict[key] = {'hosts': parent_group} child_groups = parent_group.setdefault('children', []) if element not in child_groups: ch...
def load_inventory_from_cache(self): ''' Reads the inventory from the cache file and returns it as a JSON object ''' cache = open(self.cache_path_cache, 'r') json_inventory = cache.read() self.inventory = json.loads(json_inventory)
def load_index_from_cache(self): ''' Reads the index from the cache file sets self.index ''' cache = open(self.cache_path_index, 'r') json_index = cache.read() self.index = json.loads(json_index)
def write_to_cache(self, data, filename): ''' Writes data in JSON format to a file ''' json_data = json.dumps(data, sort_keys=True, indent=2) cache = open(filename, 'w') cache.write(json_data) cache.close()
def to_safe(self, word): ''' Converts 'bad' characters in a string to underscores so they can be used as Ansible groups ''' regex = "[^A-Za-z0-9\_" if not self.replace_dash_in_groups: regex += "\-" return re.sub(regex + "]", "_", word)
def from_keyword_list(self, keyword_list, strictness=2, timeout=3): """ Convert a list of keywords to sentence. The result is sometimes None :param list keyword_list: a list of string :param int | None strictness: None for highest strictness. 2 or 1 for a less strict POS matching :param float timeout: timeout of this f...
[]
def eval(self, script, keys=None, args=None): """:meth:`~tredis.RedisClient.eval` and :meth:`~tredis.RedisClient.evalsha` are used to evaluate scripts using the Lua interpreter built into Redis starting from version 2.6.0. The first argument of EVAL is a Lua 5.1 script. The script does not need to define a Lua function...
args)
def evalsha(self, sha1, keys=None, args=None): """Evaluates a script cached on the server side by its SHA1 digest. Scripts are cached on the server side using the :meth:`~tredis.RedisClient.script_load` command. The command is otherwise identical to :meth:`~tredis.RedisClient.eval`. .. note:: **Time complexity**: Depen...
def valid_kbreak_matchings(start_edges, result_edges): """ A staticmethod check implementation that makes sure that degrees of vertices, that are affected by current :class:`KBreak` By the notion of k-break, it shall keep the degree of vertices in :class:`bg.breakpoint_graph.BreakpointGraph` the same, after its applica...
Counter(vertex for vertex_pair in start_edges for vertex in vertex_pair) result_stats = Counter(vertex for vertex_pair in result_edges for vertex in vertex_pair) return start_stats == result_stats
def render_path(self) -> str: """Render path by filling the path template with video information.""" # TODO: Fix defaults when date is not found (empty string or None) # https://stackoverflow.com/questions/23407295/default-kwarg-values-for-pythons-str-format-method from string import Formatter class UnseenFormatter(For...
def get_lm_response(self, flags, challenge): """ Computes the 24 byte LMHash password hash given the 8 byte server challenge. :param challenge: The 8-byte challenge message generated by the server :return: The 24 byte LMHash """ # If lm compatibility level lower than 3, but the server negotiated NTLM2, generate an # NT...
def get_ntlm_response(self, flags, challenge, target_info=None, channel_binding=None): """ Computes the 24 byte NTLM challenge response given the 8 byte server challenge, along with the session key. If NTLMv2 is used, the TargetInfo structure must be supplied, the updated TargetInfo structure will be returned :param ch...
the LmChallengeResponseLen and LmChallengeResponseMaxLen fields in the # AUTHENTICATE_MESSAGE to zero. # If lm compatibility level is 3 or lower, but the server negotiated NTLM2, generate an # NTLM2 response in preference to the weaker NTLMv1. if flags & NegotiateFlag.NTLMSSP_NTLM2_KEY and self._lm_compatibility < 3: r...
TODO: the client SHOULD provide a MIC. timestamp = target_info[TargetInfo.NTLMSSP_AV_TIME][1] #target_info[TargetInfo.NTLMSSP_AV_FLAGS] = struct.pack('<I', 2) # Calculating channel bindings is poorly documented. It is implemented in winrmlib, and needs to be # moved here # if self._av_channel_bindings is True and chann...
def _expand_des_key(key): """ Expand the key from a 7-byte password key into a 8-byte DES key """ key = key[:7] + b'\0' * (7 - len(key)) byte = struct.unpack_from('BBBBBBB', key) s = struct.pack('B', ((byte[0] >> 1) & 0x7f) << 1) s += struct.pack("B", ((byte[0] & 0x01) << 6 | ((byte[1] >> 2) & 0x3f)) << 1) s += struct....
| ((byte[6] >> 7) & 0x01)) << 1) s += struct.pack("B", (byte[6] & 0x7f) << 1) return s
def get_ntlmv1_response(password, challenge): """ Generate the Unicode MD4 hash for the password associated with these credentials. """ ntlm_hash = PasswordAuthentication.ntowfv1(password.encode('utf-16le')) response = PasswordAuthentication._encrypt_des_block(ntlm_hash[:7], challenge) response += PasswordAuthenticatio...
def get_ntlm2_response(password, server_challenge, client_challenge): """ Generate the Unicode MD4 hash for the password associated with these credentials. """ md5 = hashlib.new('md5') md5.update(server_challenge + client_challenge) ntlm2_session_hash = md5.digest()[:8] ntlm_hash = PasswordAuthentication.ntowfv1(passwo...
def ntowfv2(domain, user, password): """ NTOWFv2() Implementation [MS-NLMP] v20140502 NT LAN Manager (NTLM) Authentication Protocol 3.3.2 NTLM v2 Authentication :param domain: The windows domain name :param user: The windows username :param password: The users password :return: Hash Data """ md4 = hashlib.new('md4') md...
def _compute_response(response_key, server_challenge, client_challenge): """ ComputeResponse() has been refactored slightly to reduce its complexity and improve readability, the 'if' clause which switches between LMv2 and NTLMv2 computation has been removed. Users should not call this method directly, they should rely ...
def get_lmv2_response(domain, username, password, server_challenge, client_challenge): """ Computes an appropriate LMv2 response based on the supplied arguments The algorithm is based on jCIFS. The response is 24 bytes, with the 16 bytes of hash concatenated with the 8 byte client client_challenge """ ntlmv2_hash = Pas...
def get_ntlmv2_response(domain, user, password, server_challenge, client_challenge, timestamp, target_info): """ [MS-NLMP] v20140502 NT LAN Manager (NTLM) Authentication Protocol 3.3.2 NTLM v2 Authentication Computes an appropriate NTLMv2 response. The algorithm is based on jCIFS and the ComputeResponse() implementatio...
""" lo_response_version = b'\x01' hi_response_version = b'\x01' reserved_dword = b'\x00' * 4 reserved_bytes = b'\x00' * 6 response_key = PasswordAuthentication.ntowfv2(domain, user, password) proof_material = lo_response_version proof_material += hi_response_version proof_material += reserved_bytes proof_material += ti...
def xml(self, value): """Set new XML string""" self._xml = value self._root = s2t(value)
def root(self, value): """Set new XML tree""" self._xml = t2s(value) self._root = value
def xsl_elements(self): """Find all "XSL" styled runs, normalize related paragraph and returns list of XslElements""" def append_xsl_elements(xsl_elements, r, xsl): if r is not None: r.xpath('.//w:t', namespaces=self.namespaces)[0].text = xsl xe = XslElement(r, logger=self.logger) xsl_elements.append(xe) return None, '...
def render_xsl(self, node, context): """Render all XSL elements""" for e in self.xsl_elements: e.render(e.run)
def remove_style(self): """Remove all XSL run rStyle elements""" for n in self.root.xpath('.//w:rStyle[@w:val="%s"]' % self.style, namespaces=self.namespaces): n.getparent().remove(n)