func_code_string
stringlengths
52
1.94M
func_documentation_string
stringlengths
1
47.2k
def create_writer(self, name, *args, **kwargs): self._check_format(name) return self._formats[name]['writer'](*args, **kwargs)
Create a new writer instance for a given format.
def convert(self, contents_or_path, from_=None, to=None, reader=None, writer=None, from_kwargs=None, to_kwargs=None, ): # Load the file if 'contents_or_path' is a path. ...
Convert contents between supported formats. Parameters ---------- contents : str The contents to convert from. from_ : str or None The name of the source format. If None, this is the ipymd_cells format. to : str or None The name o...
def clean_meta(self, meta): if not self.verbose_metadata: default_kernel_name = (self.default_kernel_name or self._km.kernel_name) if (meta.get("kernelspec", {}) .get("name", None) == default_kernel_name): de...
Removes unwanted metadata Parameters ---------- meta : dict Notebook metadata.
def clean_cell_meta(self, meta): for k, v in DEFAULT_CELL_METADATA.items(): if meta.get(k, None) == v: meta.pop(k, None) return meta
Remove cell metadata that matches the default cell metadata.
def _starts_with_regex(line, regex): if not regex.startswith('^'): regex = '^' + regex reg = re.compile(regex) return reg.match(line)
Return whether a line starts with a regex or not.
def create_prompt(prompt): if prompt is None: prompt = 'python' if prompt == 'python': prompt = PythonPromptManager elif prompt == 'ipython': prompt = IPythonPromptManager # Instanciate the class. if isinstance(prompt, BasePromptManager): return prompt else: ...
Create a prompt manager. Parameters ---------- prompt : str or class driving from BasePromptManager The prompt name ('python' or 'ipython') or a custom PromptManager class.
def split_input_output(self, text): lines = _to_lines(text) i = 0 for line in lines: if _starts_with_regex(line, self.input_prompt_regex): i += 1 else: break return lines[:i], lines[i:]
Split code into input lines and output lines, according to the input and output prompt templates.
def get(self, path, content=True, type=None, format=None): path = path.strip('/') # File extension of the chosen format. file_extension = format_manager().file_extension(self.format) if not self.exists(path): raise web.HTTPError(404, u'No such file or directory: %s' ...
Takes a path for an entity and returns its model Parameters ---------- path : str the API path that describes the relative path for the target content : bool Whether to include the contents in the reply type : str, optional The requested type -...
def _read_notebook(self, os_path, as_version=4): with self.open(os_path, 'r', encoding='utf-8') as f: try: # NEW file_ext = _file_extension(os_path) if file_ext == '.ipynb': return nbformat.read(f, as_version=as_version) ...
Read a notebook from an os path.
def save(self, model, path=''): path = path.strip('/') if 'type' not in model: raise web.HTTPError(400, u'No file type provided') if 'content' not in model and model['type'] != 'directory': raise web.HTTPError(400, u'No file content provided') self.run_pr...
Save the file model and return the model with no content.
def _split_python(python): python = _preprocess(python) if not python: return [] lexer = PythonSplitLexer() lexer.read(python) return lexer.chunks
Split Python source into chunks. Chunks are separated by at least two return lines. The break must not be followed by a space. Also, long Python strings spanning several lines are not splitted.
def _is_chunk_markdown(source): lines = source.splitlines() if all(line.startswith('# ') for line in lines): # The chunk is a Markdown *unless* it is commented Python code. source = '\n'.join(line[2:] for line in lines if not line[2:].startswith('#')) # skip head...
Return whether a chunk contains Markdown contents.
def _add_hash(source): source = '\n'.join('# ' + line.rstrip() for line in source.splitlines()) return source
Add a leading hash '#' at the beginning of every line in the source.
def _filter_markdown(source, filters): lines = source.splitlines() # Filters is a list of 'hN' strings where 1 <= N <= 6. headers = [_replace_header_filter(filter) for filter in filters] lines = [line for line in lines if line.startswith(tuple(headers))] return '\n'.join(lines)
Only keep some Markdown headers from a Markdown string.
def parse_lheading(self, m): level = 1 if m.group(2) == '=' else 2 self.renderer.heading(m.group(1), level=level)
Parse setext heading.
def ensure_newline(self, n): assert n >= 0 text = self._output.getvalue().rstrip('\n') if not text: return self._output = StringIO() self._output.write(text) self._output.write('\n' * n) text = self._output.getvalue() assert text[-n-1]...
Make sure there are 'n' line breaks at the end.
def _meta_from_regex(self, m): body = m.group('body') is_notebook = m.group('sep_close') == '---' if is_notebook: # make it into a valid YAML object by stripping --- body = body.strip()[:-3] + '...' try: if body: return self._m...
Extract and parse YAML metadata from a meta match Notebook metadata must appear at the beginning of the file and follows the Jekyll front-matter convention of dashed delimiters: --- some: yaml --- Cell metadata follows the YAML spec of dashes and periods ...
def _code_cell(self, source): input, output = self._prompt.to_cell(source) return {'cell_type': 'code', 'input': input, 'output': output}
Split the source into input and output.
def _preprocess(text, tab=4): text = re.sub(r'\r\n|\r', '\n', text) text = text.replace('\t', ' ' * tab) text = text.replace('\u00a0', ' ') text = text.replace('\u2424', '\n') pattern = re.compile(r'^ +$', re.M) text = pattern.sub('', text) text = _rstrip_lines(text) return text
Normalize a text.
def _diff(text_0, text_1): diff = difflib.ndiff(text_0.splitlines(), text_1.splitlines()) return _diff_removed_lines(diff)
Return a diff between two strings.
def _write_json(file, contents): with open(file, 'w') as f: return json.dump(contents, f, indent=2, sort_keys=True)
Write a dict to a JSON file.
def _numbered_style(): style = ListStyle(name='_numbered_list') lls = ListLevelStyleNumber(level=1) lls.setAttribute('displaylevels', 1) lls.setAttribute('numsuffix', '. ') lls.setAttribute('numformat', '1') llp = ListLevelProperties() llp.setAttribute('listlevelpositionandspacemode', '...
Create a numbered list style.
def _create_style(name, family=None, **kwargs): if family == 'paragraph' and 'marginbottom' not in kwargs: kwargs['marginbottom'] = '.5cm' style = Style(name=name, family=family) # Extract paragraph properties. kwargs_par = {} keys = sorted(kwargs.keys()) for k in keys: if '...
Helper function for creating a new style.
def default_styles(): styles = {} def _add_style(name, **kwargs): styles[name] = _create_style(name, **kwargs) _add_style('heading-1', family='paragraph', fontsize='24pt', fontweight='bold', ) _add_style('heading-2', ...
Generate default ODF styles.
def load_styles(path_or_doc): if isinstance(path_or_doc, string_types): doc = load(path_or_doc) else: # Recover the OpenDocumentText instance. if isinstance(path_or_doc, ODFDocument): doc = path_or_doc._doc else: doc = path_or_doc assert isins...
Return a dictionary of all styles contained in an ODF document.
def _item_type(item): tag = item['tag'] style = item.get('style', None) if tag == 'p': if style is None or 'paragraph' in style: return 'paragraph' else: return style elif tag == 'span': if style in (None, 'normal-text'): return 'text' ...
Indicate to the ODF reader the type of the block or text.
def add_styles(self, **styles): for stylename in sorted(styles): self._doc.styles.addElement(styles[stylename])
Add ODF styles to the current document.
def _add_element(self, cls, **kwargs): # Convert stylename strings to actual style elements. kwargs = self._replace_stylename(kwargs) el = cls(**kwargs) self._doc.text.addElement(el)
Add an element.
def _style_name(self, el): if el.attributes is None: return None style_field = ('urn:oasis:names:tc:opendocument:xmlns:text:1.0', 'style-name') name = el.attributes.get(style_field, None) if not name: return None return self...
Return the style name of an element.
def start_container(self, cls, **kwargs): # Convert stylename strings to actual style elements. kwargs = self._replace_stylename(kwargs) # Create the container. container = cls(**kwargs) self._containers.append(container)
Append a new container.
def end_container(self, cancel=None): if not self._containers: return container = self._containers.pop() if len(self._containers) >= 1: parent = self._containers[-1] else: parent = self._doc.text if not cancel: parent.addEl...
Finishes and registers the currently-active container, unless 'cancel' is True.
def container(self, cls, **kwargs): self.start_container(cls, **kwargs) yield self.end_container()
Container context manager.
def start_paragraph(self, stylename=None): # Use the next paragraph style if one was set. if stylename is None: stylename = self._next_p_style or 'normal-paragraph' self.start_container(P, stylename=stylename)
Start a new paragraph.
def require_paragraph(self): if self._containers and _is_paragraph(self._containers[-1]): return False else: self.start_paragraph() return True
Create a new paragraph unless the currently-active container is already a paragraph.
def _code_line(self, line): assert self._containers container = self._containers[-1] # Handle extra spaces. text = line while text: if text.startswith(' '): r = re.match(r'(^ +)', text) n = len(r.group(1)) cont...
Add a code line.
def code(self, text, lang=None): # WARNING: lang is discarded currently. with self.paragraph(stylename='code'): lines = text.splitlines() for line in lines[:-1]: self._code_line(line) self.linebreak() self._code_line(lines[-1])
Add a code block.
def start_numbered_list(self): self._ordered = True self.start_container(List, stylename='_numbered_list') self.set_next_paragraph_style('numbered-list-paragraph' if self._item_level <= 0 else 'sublist-paragraph...
Start a numbered list.
def start_list(self): self._ordered = False self.start_container(List) self.set_next_paragraph_style('list-paragraph' if self._item_level <= 0 else 'sublist-paragraph')
Start a list.
def text(self, text, stylename=None): assert self._containers container = self._containers[-1] if stylename is not None: stylename = self._get_style_name(stylename) container.addElement(Span(stylename=stylename, text=text)) else: container.add...
Add text within the current container.
def _cell_output(cell): outputs = cell.get('outputs', []) # Add stdout. stdout = ('\n'.join(_ensure_string(output.get('text', '')) for output in outputs)).rstrip() # Add text output. text_outputs = [] for output in outputs: out = output.get('data', {}).get('t...
Return the output of an ipynb cell.
def dump_add_vspacing(buff, vspacing): 'Post-processing to add some nice-ish spacing for deeper map/list levels.' if isinstance(vspacing, int): vspacing = ['\n']*(vspacing+1) buff.seek(0) result = list() for line in buff: level = 0 line = line.decode('utf-8') result.append(line) if ':' in line or re.sear...
Post-processing to add some nice-ish spacing for deeper map/list levels.
def _dump(self, service, grep=None): if grep: return self.adb_shell('dumpsys {0} | grep "{1}"'.format(service, grep)) return self.adb_shell('dumpsys {0}'.format(service))
Perform a service dump. :param service: Service to dump. :param grep: Grep for this string. :returns: Dump, optionally grepped.
def _dump_has(self, service, grep, search): dump_grep = self._dump(service, grep=grep) if not dump_grep: return False return dump_grep.strip().find(search) > -1
Check if a dump has particular content. :param service: Service to dump. :param grep: Grep for this string. :param search: Check for this substring. :returns: Found or not.
def _ps(self, search=''): if not self.available: return result = [] ps = self.adb_streaming_shell('ps') try: for bad_line in ps: # The splitting of the StreamingShell doesn't always work # this is to ensure that we get only...
Perform a ps command with optional filtering. :param search: Check for this substring. :returns: List of matching fields
def connect(self, always_log_errors=True): self._adb_lock.acquire(**LOCK_KWARGS) try: if not self.adb_server_ip: # python-adb try: if self.adbkey: signer = Signer(self.adbkey) # Conne...
Connect to an Amazon Fire TV device. Will attempt to establish ADB connection to the given host. Failure sets state to UNKNOWN and disables sending actions. :returns: True if successful, False otherwise
def update(self, get_running_apps=True): # The `screen_on`, `awake`, `wake_lock_size`, `current_app`, and `running_apps` properties. screen_on, awake, wake_lock_size, _current_app, running_apps = self.get_properties(get_running_apps=get_running_apps, lazy=True) # Check if device is off....
Get the state of the device, the current app, and the running apps. :param get_running_apps: whether or not to get the ``running_apps`` property :return state: the state of the device :return current_app: the current app :return running_apps: the running apps
def app_state(self, app): if not self.available or not self.screen_on: return STATE_OFF if self.current_app["package"] == app: return STATE_ON return STATE_OFF
Informs if application is running.
def state(self): # Check if device is disconnected. if not self.available: return STATE_UNKNOWN # Check if device is off. if not self.screen_on: return STATE_OFF # Check if screen saver is on. if not self.awake: return STATE_ID...
Compute and return the device state. :returns: Device state.
def available(self): if not self.adb_server_ip: # python-adb return bool(self._adb) # pure-python-adb try: # make sure the server is available adb_devices = self._adb_client.devices() # make sure the device is available ...
Check whether the ADB connection is intact.
def running_apps(self): ps = self.adb_shell(RUNNING_APPS_CMD) if ps: return [line.strip().rsplit(' ', 1)[-1] for line in ps.splitlines() if line.strip()] return []
Return a list of running user applications.
def current_app(self): current_focus = self.adb_shell(CURRENT_APP_CMD) if current_focus is None: return None current_focus = current_focus.replace("\r", "") matches = WINDOW_REGEX.search(current_focus) # case 1: current app was successfully found if m...
Return the current app.
def wake_lock_size(self): output = self.adb_shell(WAKE_LOCK_SIZE_CMD) if not output: return None return int(output.split("=")[1].strip())
Get the size of the current wake lock.
def get_properties(self, get_running_apps=True, lazy=False): if get_running_apps: output = self.adb_shell(SCREEN_ON_CMD + (SUCCESS1 if lazy else SUCCESS1_FAILURE0) + " && " + AWAKE_CMD + (SUCCESS1 if lazy else SUCCESS1_FAILURE0) + " && " + ...
Get the ``screen_on``, ``awake``, ``wake_lock_size``, ``current_app``, and ``running_apps`` properties.
def is_valid_device_id(device_id): valid = valid_device_id.match(device_id) if not valid: logging.error("A valid device identifier contains " "only ascii word characters or dashes. " "Device '%s' not added.", device_id) return valid
Check if device identifier is valid. A valid device identifier contains only ascii word characters or dashes. :param device_id: Device identifier :returns: Valid or not.
def add(device_id, host, adbkey='', adb_server_ip='', adb_server_port=5037): valid = is_valid_device_id(device_id) and is_valid_host(host) if valid: devices[device_id] = FireTV(str(host), str(adbkey), str(adb_server_ip), str(adb_server_port)) return valid
Add a device. Creates FireTV instance associated with device identifier. :param device_id: Device identifier. :param host: Host in <address>:<port> format. :param adbkey: The path to the "adbkey" file :param adb_server_ip: the IP address for the ADB server :param adb_server_port: the port for ...
def add_device(): req = request.get_json() success = False if 'device_id' in req and 'host' in req: success = add(req['device_id'], req['host'], req.get('adbkey', ''), req.get('adb_server_ip', ''), req.get('adb_server_port', 5037)) return jsonify(success=success)
Add a device via HTTP POST. POST JSON in the following format :: { "device_id": "<your_device_id>", "host": "<address>:<port>", "adbkey": "<path to the adbkey file>" }
def list_devices(): output = {} for device_id, device in devices.items(): output[device_id] = { 'host': device.host, 'state': device.state } return jsonify(devices=output)
List devices via HTTP GET.
def device_state(device_id): if device_id not in devices: return jsonify(success=False) return jsonify(state=devices[device_id].state)
Get device state via HTTP GET.
def current_app(device_id): if not is_valid_device_id(device_id): abort(403) if device_id not in devices: abort(404) current = devices[device_id].current_app if current is None: abort(404) return jsonify(current_app=current)
Get currently running app.
def running_apps(device_id): if not is_valid_device_id(device_id): abort(403) if device_id not in devices: abort(404) return jsonify(running_apps=devices[device_id].running_apps)
Get running apps via HTTP GET.
def get_app_state(device_id, app_id): if not is_valid_app_id(app_id): abort(403) if not is_valid_device_id(device_id): abort(403) if device_id not in devices: abort(404) app_state = devices[device_id].app_state(app_id) return jsonify(state=app_state, status=app_state)
Get the state of the requested app
def device_action(device_id, action_id): success = False if device_id in devices: input_cmd = getattr(devices[device_id], action_id, None) if callable(input_cmd): input_cmd() success = True return jsonify(success=success)
Initiate device action via HTTP GET.
def app_start(device_id, app_id): if not is_valid_app_id(app_id): abort(403) if not is_valid_device_id(device_id): abort(403) if device_id not in devices: abort(404) success = devices[device_id].launch_app(app_id) return jsonify(success=success)
Starts an app with corresponding package name
def app_stop(device_id, app_id): if not is_valid_app_id(app_id): abort(403) if not is_valid_device_id(device_id): abort(403) if device_id not in devices: abort(404) success = devices[device_id].stop_app(app_id) return jsonify(success=success)
stops an app with corresponding package name
def device_connect(device_id): success = False if device_id in devices: devices[device_id].connect() success = True return jsonify(success=success)
Force a connection attempt via HTTP GET.
def _parse_config(config_file_path): config_file = open(config_file_path, 'r') config = yaml.load(config_file) config_file.close() return config
Parse Config File from yaml file.
def _add_devices_from_config(args): config = _parse_config(args.config) for device in config['devices']: if args.default: if device == "default": raise ValueError('devicename "default" in config is not allowed if default param is set') if config['devices'][de...
Add devices from config.
def main(): parser = argparse.ArgumentParser(description='AFTV Server') parser.add_argument('-p', '--port', type=int, help='listen port', default=5556) parser.add_argument('-d', '--default', help='default Amazon Fire TV host', nargs='?') parser.add_argument('-c', '--config', type=str, help='Path to...
Set up the server.
def _load_words(self): with open(self._words_file, 'r') as f: self._censor_list = [line.strip() for line in f.readlines()]
Loads the list of profane words from file.
def set_censor(self, character): # TODO: what if character isn't str()-able? if isinstance(character, int): character = str(character) self._censor_char = character
Replaces the original censor character '*' with ``character``.
def get_profane_words(self): profane_words = [] if self._custom_censor_list: profane_words = [w for w in self._custom_censor_list] # Previous versions of Python don't have list.copy() else: profane_words = [w for w in self._censor_list] profane_words.ext...
Returns all profane words currently in use.
def censor(self, input_text): bad_words = self.get_profane_words() res = input_text for word in bad_words: # Apply word boundaries to the bad word regex_string = r'{0}' if self._no_word_boundaries else r'\b{0}\b' regex_string = regex_string.format(wor...
Returns input_text with any profane words censored.
def unpack_multiple(data): chunks = [] while data: info = SMB2NetworkInterfaceInfo() data = info.unpack(data) chunks.append(info) return chunks
Get's a list of SMB2NetworkInterfaceInfo messages from the byte value passed in. This is the raw buffer value that is set on the SMB2IOCTLResponse message. :param data: bytes of the messages :return: List of SMB2NetworkInterfaceInfo messages
def get_response_structure(name): return { CreateContextName.SMB2_CREATE_DURABLE_HANDLE_REQUEST: SMB2CreateDurableHandleResponse(), CreateContextName.SMB2_CREATE_DURABLE_HANDLE_RECONNECT: SMB2CreateDurableHandleReconnect(), CreateConte...
Returns the response structure for a know list of create context responses. :param name: The constant value above :return: The response structure or None if unknown
def get_context_data(self): buffer_name = self['buffer_name'].get_value() structure = CreateContextName.get_response_structure(buffer_name) if structure: structure.unpack(self['buffer_data'].get_value()) return structure else: # unknown struct...
Get the buffer_data value of a context response and try to convert it to the relevant structure based on the buffer_name used. If it is an unknown structure then the raw bytes are returned. :return: relevant Structure of buffer_data or bytes if unknown name
def pack_multiple(messages): data = b"" msg_count = len(messages) for i, msg in enumerate(messages): if i == msg_count - 1: msg['next_entry_offset'] = 0 else: # because the end padding val won't be populated if the entry ...
Converts a list of SMB2CreateEABuffer structures and packs them as a bytes object used when setting to the SMB2CreateContextRequest buffer_data field. This should be used as it would calculate the correct next_entry_offset field value for each buffer entry. :param messages: List of SMB2...
def set_name(self, print_name, substitute_name): print_bytes = print_name.encode('utf-16-le') sub_bytes = substitute_name.encode('utf-16-le') path_buffer = print_bytes + sub_bytes self['print_name_offset'].set_value(0) self['print_name_length'].set_value(len(print_bytes)...
Set's the path_buffer and print/substitute name length of the message with the values passed in. These values should be a string and not a byte string as it is encoded in this function. :param print_name: The print name string to set :param substitute_name: The substitute name string to...
def connect(self, require_secure_negotiate=True): log.info("Session: %s - Creating connection to share %s" % (self.session.username, self.share_name)) utf_share_name = self.share_name.encode('utf-16-le') connect = SMB2TreeConnectRequest() connect['buffer'] = utf...
Connect to the share. :param require_secure_negotiate: For Dialects 3.0 and 3.0.2, will verify the negotiation parameters with the server to prevent SMB downgrade attacks
def disconnect(self): if not self._connected: return log.info("Session: %s, Tree: %s - Disconnecting from Tree Connect" % (self.session.username, self.share_name)) req = SMB2TreeDisconnect() log.info("Session: %s, Tree: %s - Sending Tree Disconnect m...
Disconnects the tree connection.
def connect(self, dialect=None, timeout=60): log.info("Setting up transport connection") self.transport.connect() log.info("Starting negotiation with SMB server") smb_response = self._send_smb2_negotiate(dialect, timeout) log.info("Negotiated dialect: %s" ...
Will connect to the target server and negotiate the capabilities with the client. Once setup, the client MUST call the disconnect() function to close the listener thread. This function will populate various connection properties that denote the capabilities of the server. :param...
def disconnect(self, close=True): if close: for session in list(self.session_table.values()): session.disconnect(True) log.info("Disconnecting transport connection") self.transport.disconnect()
Closes the connection as well as logs off any of the Disconnects the TCP connection and shuts down the socket listener running in a thread. :param close: Will close all sessions in the connection as well as the tree connections of each session.
def send(self, message, sid=None, tid=None, credit_request=None): header = self._generate_packet_header(message, sid, tid, credit_request) # get the actual Session and TreeConnect object instead of the IDs session = self.session_table.get(si...
Will send a message to the server that is passed in. The final unencrypted header is returned to the function that called this. :param message: An SMB message structure to send :param sid: A session_id that the message is sent for :param tid: A tree_id object that the message is sent fo...
def send_compound(self, messages, sid, tid, related=False): send_data = b"" session = self.session_table[sid] tree = session.tree_connect_table[tid] requests = [] total_requests = len(messages) for i, message in enumerate(messages): if i == total_requ...
Sends multiple messages within 1 TCP request, will fail if the size of the total length exceeds the maximum of the transport max. :param messages: A list of messages to send to the server :param sid: The session_id that the request is sent for :param tid: A tree_id object that the messa...
def receive(self, request, wait=True, timeout=None): start_time = time.time() # check if we have received a response while True: self._flush_message_buffer() status = request.response['status'].get_value() if \ request.response else None ...
Polls the message buffer of the TCP connection and waits until a valid message is received based on the message_id passed in. :param request: The Request object to wait get the response for :param wait: Wait for the final response in the case of a STATUS_PENDING response, the pendin...
def echo(self, sid=0, timeout=60, credit_request=1): log.info("Sending Echo request with a timeout of %d and credit " "request of %d" % (timeout, credit_request)) echo_msg = SMB2Echo() log.debug(str(echo_msg)) req = self.send(echo_msg, sid=sid, credit_request=cr...
Sends an SMB2 Echo request to the server. This can be used to request more credits from the server with the credit_request param. On a Samba server, the sid can be 0 but for a Windows SMB Server, the sid of an authenticated session must be passed into this function or else the socket wi...
def _flush_message_buffer(self): while True: message_bytes = self.transport.receive() # there were no messages receives, so break from the loop if message_bytes is None: break # check if the message is encrypted and decrypt if necessary ...
Loops through the transport message_buffer until there are no messages left in the queue. Each response is assigned to the Request object based on the message_id which are then available in self.outstanding_requests
def _calculate_credit_charge(self, message): credit_size = 65536 if not self.supports_multi_credit: credit_charge = 0 elif message.COMMAND == Commands.SMB2_READ: max_size = message['length'].get_value() + \ message['read_channel_info_length...
Calculates the credit charge for a request based on the command. If connection.supports_multi_credit is not True then the credit charge isn't valid so it returns 0. The credit charge is the number of credits that are required for sending/receiving data over 64 kilobytes, in the existing...
def disconnect(self, close=True): if not self._connected: # already disconnected so let's return return if close: for open in list(self.open_table.values()): open.close(False) for tree in list(self.tree_connect_table.values()): ...
Logs off the session :param close: Will close all tree connects in a session
def _smb3kdf(self, ki, label, context): kdf = KBKDFHMAC( algorithm=hashes.SHA256(), mode=Mode.CounterMode, length=16, rlen=4, llen=4, location=CounterLocation.BeforeFixed, label=label, context=context, ...
See SMB 3.x key derivation function https://blogs.msdn.microsoft.com/openspecification/2017/05/26/smb-2-and-smb-3-security-in-windows-10-the-anatomy-of-signing-and-cryptographic-keys/ :param ki: The session key is the KDK used as an input to the KDF :param label: The purpose of this derived key...
def pack(self): value = self._get_calculated_value(self.value) packed_value = self._pack_value(value) size = self._get_calculated_size(self.size, packed_value) if len(packed_value) != size: raise ValueError("Invalid packed data length for field %s of %d " ...
Packs the field value into a byte string so it can be sent to the server. :param structure: The message structure class object :return: A byte string of the packed field's value
def set_value(self, value): parsed_value = self._parse_value(value) self.value = parsed_value
Parses, and sets the value attribute for the field. :param value: The value to be parsed and set, the allowed input types vary depending on the Field used
def unpack(self, data): size = self._get_calculated_size(self.size, data) self.set_value(data[0:size]) return data[len(self):]
Takes in a byte string and set's the field value based on field definition. :param structure: The message structure class object :param data: The byte string of the data to unpack :return: The remaining data for subsequent fields
def _get_calculated_value(self, value): if isinstance(value, types.LambdaType): expanded_value = value(self.structure) return self._get_calculated_value(expanded_value) else: # perform one final parsing of the value in case lambda value # returned...
Get's the final value of the field and runs the lambda functions recursively until a final value is derived. :param value: The value to calculate/expand :return: The final value
def _get_calculated_size(self, size, data): # if the size is derived from a lambda function, run it now; otherwise # return the value we passed in or the length of the data if the size # is None (last field value) if size is None: return len(data) elif isinst...
Get's the final size of the field and runs the lambda functions recursively until a final size is derived. If size is None then it will just return the length of the data as it is assumed it is the final field (None should only be set on size for the final field). :param size: The size ...
def _get_struct_format(self, size): if isinstance(size, types.LambdaType): size = size(self.structure) struct_format = { 1: 'B', 2: 'H', 4: 'L', 8: 'Q' } if size not in struct_format.keys(): raise InvalidFie...
Get's the format specified for use in struct. This is only designed for 1, 2, 4, or 8 byte values and will throw an exception if it is anything else. :param size: The size as an int :return: The struct format specifier for the size specified
def unpack_response(file_information_class, buffer): structs = smbprotocol.query_info resp_structure = { FileInformationClass.FILE_DIRECTORY_INFORMATION: structs.FileDirectoryInformation, FileInformationClass.FILE_NAMES_INFORMATION: struct...
Pass in the buffer value from the response object to unpack it and return a list of query response structures for the request. :param buffer: The raw bytes value of the SMB2QueryDirectoryResponse buffer field. :return: List of query_info.* structures based on the FileInf...
def create(self, impersonation_level, desired_access, file_attributes, share_access, create_disposition, create_options, create_contexts=None, send=True): create = SMB2CreateRequest() create['impersonation_level'] = impersonation_level create['desired_acces...
This will open the file based on the input parameters supplied. Any file open should also be called with Open.close() when it is finished. More details on how each option affects the open process can be found here https://msdn.microsoft.com/en-us/library/cc246502.aspx. Supports out of ...
def read(self, offset, length, min_length=0, unbuffered=False, wait=True, send=True): if length > self.connection.max_read_size: raise SMBException("The requested read length %d is greater than " "the maximum negotiated read size %d" ...
Reads from an opened file or pipe Supports out of band send function, call this function with send=False to return a tuple of (SMB2ReadRequest, receive_func) instead of sending the the request and waiting for the response. The receive_func can be used to get the response from the server...
def write(self, data, offset=0, write_through=False, unbuffered=False, wait=True, send=True): data_len = len(data) if data_len > self.connection.max_write_size: raise SMBException("The requested write length %d is greater than " "the maxi...
Writes data to an opened file. Supports out of band send function, call this function with send=False to return a tuple of (SMBWriteRequest, receive_func) instead of sending the the request and waiting for the response. The receive_func can be used to get the response from the server by...
def flush(self, send=True): flush = SMB2FlushRequest() flush['file_id'] = self.file_id if not send: return flush, self._flush_response log.info("Session: %s, Tree Connect: %s - sending SMB2 Flush Request " "for file %s" % (self.tree_connect.session.u...
A command sent by the client to request that a server flush all cached file information for the opened file. Supports out of band send function, call this function with send=False to return a tuple of (SMB2FlushRequest, receive_func) instead of sending the the request and waiting for th...