code
stringlengths
66
870k
docstring
stringlengths
19
26.7k
func_name
stringlengths
1
138
language
stringclasses
1 value
repo
stringlengths
7
68
path
stringlengths
5
324
url
stringlengths
46
389
license
stringclasses
7 values
def image_to_pdf_or_hocr( image, lang=None, config='', nice=0, extension='pdf', timeout=0, ): """ Returns the result of a Tesseract OCR run on the provided image to pdf/hocr """ if extension not in {'pdf', 'hocr'}: raise ValueError(f'Unsupported extension: {extension}') ...
Returns the result of a Tesseract OCR run on the provided image to pdf/hocr
image_to_pdf_or_hocr
python
madmaze/pytesseract
pytesseract/pytesseract.py
https://github.com/madmaze/pytesseract/blob/master/pytesseract/pytesseract.py
Apache-2.0
def image_to_alto_xml( image, lang=None, config='', nice=0, timeout=0, ): """ Returns the result of a Tesseract OCR run on the provided image to ALTO XML """ if get_tesseract_version(cached=True) < TESSERACT_ALTO_VERSION: raise ALTONotSupported() config = f'-c tessedit_...
Returns the result of a Tesseract OCR run on the provided image to ALTO XML
image_to_alto_xml
python
madmaze/pytesseract
pytesseract/pytesseract.py
https://github.com/madmaze/pytesseract/blob/master/pytesseract/pytesseract.py
Apache-2.0
def image_to_boxes( image, lang=None, config='', nice=0, output_type=Output.STRING, timeout=0, ): """ Returns string containing recognized characters and their box boundaries """ config = ( f'{config.strip()} -c tessedit_create_boxfile=1 batch.nochop makebox' ) ar...
Returns string containing recognized characters and their box boundaries
image_to_boxes
python
madmaze/pytesseract
pytesseract/pytesseract.py
https://github.com/madmaze/pytesseract/blob/master/pytesseract/pytesseract.py
Apache-2.0
def image_to_data( image, lang=None, config='', nice=0, output_type=Output.STRING, timeout=0, pandas_config=None, ): """ Returns string containing box boundaries, confidences, and other information. Requires Tesseract 3.05+ """ if get_tesseract_version(cached=True) < TES...
Returns string containing box boundaries, confidences, and other information. Requires Tesseract 3.05+
image_to_data
python
madmaze/pytesseract
pytesseract/pytesseract.py
https://github.com/madmaze/pytesseract/blob/master/pytesseract/pytesseract.py
Apache-2.0
def image_to_osd( image, lang='osd', config='', nice=0, output_type=Output.STRING, timeout=0, ): """ Returns string containing the orientation and script detection (OSD) """ config = f'--psm 0 {config.strip()}' args = [image, 'osd', lang, config, nice, timeout] return { ...
Returns string containing the orientation and script detection (OSD)
image_to_osd
python
madmaze/pytesseract
pytesseract/pytesseract.py
https://github.com/madmaze/pytesseract/blob/master/pytesseract/pytesseract.py
Apache-2.0
def test_image_to_data_pandas_output(test_file_small): """Test and compare the type and meta information of the result.""" result = image_to_data(test_file_small, output_type=Output.DATAFRAME) assert isinstance(result, pandas.DataFrame) expected_columns = [ 'level', 'page_num', '...
Test and compare the type and meta information of the result.
test_image_to_data_pandas_output
python
madmaze/pytesseract
tests/pytesseract_test.py
https://github.com/madmaze/pytesseract/blob/master/tests/pytesseract_test.py
Apache-2.0
def test_image_to_data_common_output(test_file_small, output): """Test and compare the type of the result.""" result = image_to_data(test_file_small, output_type=output) expected_dict_result = { 'level': [1, 2, 3, 4, 5], 'page_num': [1, 1, 1, 1, 1], 'block_num': [0, 1, 1, 1, 1], ...
Test and compare the type of the result.
test_image_to_data_common_output
python
madmaze/pytesseract
tests/pytesseract_test.py
https://github.com/madmaze/pytesseract/blob/master/tests/pytesseract_test.py
Apache-2.0
def test_wrong_tesseract_cmd(monkeypatch, test_file, test_path): """Test wrong or missing tesseract command.""" import pytesseract monkeypatch.setattr('pytesseract.pytesseract.tesseract_cmd', test_path) with pytest.raises(TesseractNotFoundError): pytesseract.get_languages.__wrapped__() wi...
Test wrong or missing tesseract command.
test_wrong_tesseract_cmd
python
madmaze/pytesseract
tests/pytesseract_test.py
https://github.com/madmaze/pytesseract/blob/master/tests/pytesseract_test.py
Apache-2.0
def test_main_not_found_cases( capsys, monkeypatch, test_file, test_invalid_file, ): """Test wrong or missing tesseract command in main.""" import pytesseract monkeypatch.setattr('sys.argv', ['', test_invalid_file]) assert pytesseract.pytesseract.main() == 1 captured = capsys.readou...
Test wrong or missing tesseract command in main.
test_main_not_found_cases
python
madmaze/pytesseract
tests/pytesseract_test.py
https://github.com/madmaze/pytesseract/blob/master/tests/pytesseract_test.py
Apache-2.0
def test_proper_oserror_exception_handling(monkeypatch, test_file, test_path): """ "Test for bubbling up OSError exceptions.""" import pytesseract monkeypatch.setattr( 'pytesseract.pytesseract.tesseract_cmd', test_path, ) with pytest.raises( TesseractNotFoundError if IS_PYT...
"Test for bubbling up OSError exceptions.
test_proper_oserror_exception_handling
python
madmaze/pytesseract
tests/pytesseract_test.py
https://github.com/madmaze/pytesseract/blob/master/tests/pytesseract_test.py
Apache-2.0
def __init__(self, n_vocab=None, vectors=None, residual_embeddings=False, layer0=False, layer1=True, trainable=False, model_cache=MODEL_CACHE): """Initialize an MTLSTM. If layer0 and layer1 are True, they are concatenated along the last dimension so that layer0 outputs contribute the first 600 entrie...
Initialize an MTLSTM. If layer0 and layer1 are True, they are concatenated along the last dimension so that layer0 outputs contribute the first 600 entries and layer1 contributes the second 600 entries. If residual embeddings is also true, inputs are also concatenated along the last dimension with...
__init__
python
salesforce/cove
cove/encoder.py
https://github.com/salesforce/cove/blob/master/cove/encoder.py
BSD-3-Clause
def forward(self, inputs, lengths, hidden=None): """ Arguments: inputs (Tensor): If MTLSTM handles embedding, a Long Tensor of size (batch_size, timesteps). Otherwise, a Float Tensor of size (batch_size, timesteps, features). lengths (Long Tensor): le...
Arguments: inputs (Tensor): If MTLSTM handles embedding, a Long Tensor of size (batch_size, timesteps). Otherwise, a Float Tensor of size (batch_size, timesteps, features). lengths (Long Tensor): lenghts of each sequence for handling padding hidd...
forward
python
salesforce/cove
cove/encoder.py
https://github.com/salesforce/cove/blob/master/cove/encoder.py
BSD-3-Clause
def forward(self, input, context): """ input: batch x dim context: batch x sourceL x dim """ if not self.dot: targetT = self.linear_in(input).unsqueeze(2) # batch x dim x 1 else: targetT = input.unsqueeze(2) # Get attention attn =...
input: batch x dim context: batch x sourceL x dim
forward
python
salesforce/cove
OpenNMT-py/onmt/modules/GlobalAttention.py
https://github.com/salesforce/cove/blob/master/OpenNMT-py/onmt/modules/GlobalAttention.py
BSD-3-Clause
def encode(s): """Encode a folder name using IMAP modified UTF-7 encoding. Despite the function's name, the output is still a unicode string. """ if not isinstance(s, text_type): return s r = [] _in = [] def extend_result_if_chars_buffered(): if _in: r.extend([...
Encode a folder name using IMAP modified UTF-7 encoding. Despite the function's name, the output is still a unicode string.
encode
python
charlierguo/gmail
gmail/utf.py
https://github.com/charlierguo/gmail/blob/master/gmail/utf.py
MIT
def decode(s): """Decode a folder name from IMAP modified UTF-7 encoding to unicode. Despite the function's name, the input may still be a unicode string. If the input is bytes, it's first decoded to unicode. """ if isinstance(s, binary_type): s = s.decode('latin-1') if not isinstance(s...
Decode a folder name from IMAP modified UTF-7 encoding to unicode. Despite the function's name, the input may still be a unicode string. If the input is bytes, it's first decoded to unicode.
decode
python
charlierguo/gmail
gmail/utf.py
https://github.com/charlierguo/gmail/blob/master/gmail/utf.py
MIT
def run_migrations_online(): """Run migrations in 'online' mode. In this scenario we need to create an Engine and associate a connection with the context. """ engine = create_engine( database_connection_url, poolclass=pool.NullPool) connection = engine.connect() context.configure( connection=connection,...
Run migrations in 'online' mode. In this scenario we need to create an Engine and associate a connection with the context.
run_migrations_online
python
rsmusllp/king-phisher
data/server/king_phisher/alembic/env.py
https://github.com/rsmusllp/king-phisher/blob/master/data/server/king_phisher/alembic/env.py
BSD-3-Clause
def _compare_paths(path1, path2): """ Check if *path1* is the same as *path2*, taking into account file system links. """ if os.path.islink(path1): path1 = os.readlink(path1) if os.path.islink(path2): path2 = os.readlink(path2) return os.path.abspath(path1) == os.path.abspath(path2)
Check if *path1* is the same as *path2*, taking into account file system links.
_compare_paths
python
rsmusllp/king-phisher
king_phisher/archive.py
https://github.com/rsmusllp/king-phisher/blob/master/king_phisher/archive.py
BSD-3-Clause
def patch_zipfile(input_file, patches, output_file=None): """ Patch content into the specified input Zip file. The *input_file* must be either an input path string to the file to patch or a :py:class:`zipfile.ZipFile` instance. Patch data is supplied in the *patch* argument which is a dictionary keyed by the paths...
Patch content into the specified input Zip file. The *input_file* must be either an input path string to the file to patch or a :py:class:`zipfile.ZipFile` instance. Patch data is supplied in the *patch* argument which is a dictionary keyed by the paths to modify, values are then used in place of the specified pa...
patch_zipfile
python
rsmusllp/king-phisher
king_phisher/archive.py
https://github.com/rsmusllp/king-phisher/blob/master/king_phisher/archive.py
BSD-3-Clause
def __init__(self, file_name, mode, encoding='utf-8'): """ :param str file_name: The path to the file to open as an archive. :param str mode: The mode to open the file such as 'r' or 'w'. :param str encoding: The encoding to use for strings. """ self._mode = mode + ':bz2' self.encoding = encoding self.f...
:param str file_name: The path to the file to open as an archive. :param str mode: The mode to open the file such as 'r' or 'w'. :param str encoding: The encoding to use for strings.
__init__
python
rsmusllp/king-phisher
king_phisher/archive.py
https://github.com/rsmusllp/king-phisher/blob/master/king_phisher/archive.py
BSD-3-Clause
def add_data(self, name, data): """ Add arbitrary data directly to the archive under the specified name. This allows data to be directly inserted into the archive without first writing it to a file or file like object. :param str name: The name of the destination file in the archive. :param data: The data ...
Add arbitrary data directly to the archive under the specified name. This allows data to be directly inserted into the archive without first writing it to a file or file like object. :param str name: The name of the destination file in the archive. :param data: The data to place into the archive. :type da...
add_data
python
rsmusllp/king-phisher
king_phisher/archive.py
https://github.com/rsmusllp/king-phisher/blob/master/king_phisher/archive.py
BSD-3-Clause
def close(self): """Close the handle to the archive.""" if 'w' in self.mode: self.add_data(self.metadata_file_name, serializers.JSON.dumps(self.metadata, pretty=True)) self._tar_h.close()
Close the handle to the archive.
close
python
rsmusllp/king-phisher
king_phisher/archive.py
https://github.com/rsmusllp/king-phisher/blob/master/king_phisher/archive.py
BSD-3-Clause
def files(self): """ This property is a generator which yields tuples of two objects each where the first is the file name and the second is the file object. The metadata file is skipped. :return: A generator which yields all the contained file name and file objects. :rtype: tuple """ for name in self....
This property is a generator which yields tuples of two objects each where the first is the file name and the second is the file object. The metadata file is skipped. :return: A generator which yields all the contained file name and file objects. :rtype: tuple
files
python
rsmusllp/king-phisher
king_phisher/archive.py
https://github.com/rsmusllp/king-phisher/blob/master/king_phisher/archive.py
BSD-3-Clause
def file_names(self): """ This property is a generator which yields the names of all of the contained files. The metadata file is skipped. :return: A generator which yields all the contained file names. :rtype: str """ for name in self._tar_h.getnames(): if name == self.metadata_file_name: continu...
This property is a generator which yields the names of all of the contained files. The metadata file is skipped. :return: A generator which yields all the contained file names. :rtype: str
file_names
python
rsmusllp/king-phisher
king_phisher/archive.py
https://github.com/rsmusllp/king-phisher/blob/master/king_phisher/archive.py
BSD-3-Clause
def from_dict(cls, value): """ Load the collection item file from the specified dict object. :param dict value: The dictionary to load the data from. :return: """ # make sure both keys are present or neither are present return cls(value.get('path-destination', value['path-source']), value['path-source'],...
Load the collection item file from the specified dict object. :param dict value: The dictionary to load the data from. :return:
from_dict
python
rsmusllp/king-phisher
king_phisher/catalog.py
https://github.com/rsmusllp/king-phisher/blob/master/king_phisher/catalog.py
BSD-3-Clause
def to_dict(self): """ Dump the instance to a dictionary suitable for being reloaded with :py:meth:`.from_dict`. :return: The instance represented as a dictionary. :rtype: dict """ data = { 'path-destination': self.path_destination, 'path-source': self.path_source } if self.signature and self.s...
Dump the instance to a dictionary suitable for being reloaded with :py:meth:`.from_dict`. :return: The instance represented as a dictionary. :rtype: dict
to_dict
python
rsmusllp/king-phisher
king_phisher/catalog.py
https://github.com/rsmusllp/king-phisher/blob/master/king_phisher/catalog.py
BSD-3-Clause
def __init__(self, repo, type, items): """ :param repo: The repository this collection is associated with. :type repo: :py:class:`.Repository` :param str type: The collection type of these items. :param dict items: The items that are members of this collection, keyed by their name. """ self.__repo_ref = w...
:param repo: The repository this collection is associated with. :type repo: :py:class:`.Repository` :param str type: The collection type of these items. :param dict items: The items that are members of this collection, keyed by their name.
__init__
python
rsmusllp/king-phisher
king_phisher/catalog.py
https://github.com/rsmusllp/king-phisher/blob/master/king_phisher/catalog.py
BSD-3-Clause
def __init__(self, data, keys=None): """ :param dict data: The formatted repository data. :param keys: The keys to use for verifying remote data. :type keys: :py:class:`~king_phisher.security_keys.SecurityKeys` """ self.security_keys = keys or security_keys.SecurityKeys() """The :py:class:`~king_phisher.s...
:param dict data: The formatted repository data. :param keys: The keys to use for verifying remote data. :type keys: :py:class:`~king_phisher.security_keys.SecurityKeys`
__init__
python
rsmusllp/king-phisher
king_phisher/catalog.py
https://github.com/rsmusllp/king-phisher/blob/master/king_phisher/catalog.py
BSD-3-Clause
def to_dict(self): """ Dump the instance to a dictionary suitable for being reloaded with :py:meth:`.__init__`. :return: The instance represented as a dictionary. :rtype: dict """ data = { 'id': self.id, 'title': self.title, 'url-base': self.url_base } if self.collections: data['collectio...
Dump the instance to a dictionary suitable for being reloaded with :py:meth:`.__init__`. :return: The instance represented as a dictionary. :rtype: dict
to_dict
python
rsmusllp/king-phisher
king_phisher/catalog.py
https://github.com/rsmusllp/king-phisher/blob/master/king_phisher/catalog.py
BSD-3-Clause
def get_file(self, item_file, encoding=None): """ Download and return the file data from the repository. If no encoding is specified, the data is return as bytes, otherwise it is decoded to a string using the specified encoding. The file's contents are verified using the signature that must be specified by th...
Download and return the file data from the repository. If no encoding is specified, the data is return as bytes, otherwise it is decoded to a string using the specified encoding. The file's contents are verified using the signature that must be specified by the *item_file* information. :param item_file: T...
get_file
python
rsmusllp/king-phisher
king_phisher/catalog.py
https://github.com/rsmusllp/king-phisher/blob/master/king_phisher/catalog.py
BSD-3-Clause
def get_item_files(self, collection_type, name, destination): """ Download all of the file references from the named item. :param str collection_type: The type of collection the specified item is in. :param str name: The name of the item to retrieve. :param str destination: The path of where to save the down...
Download all of the file references from the named item. :param str collection_type: The type of collection the specified item is in. :param str name: The name of the item to retrieve. :param str destination: The path of where to save the downloaded files to.
get_item_files
python
rsmusllp/king-phisher
king_phisher/catalog.py
https://github.com/rsmusllp/king-phisher/blob/master/king_phisher/catalog.py
BSD-3-Clause
def __init__(self, data, keys=None): """ :param dict data: The formatted catalog data. :param keys: The keys to use for verifying remote data. :type keys: :py:class:`~king_phisher.security_keys.SecurityKeys` """ self.security_keys = keys or security_keys.SecurityKeys() """The :py:class:`~king_phisher.secu...
:param dict data: The formatted catalog data. :param keys: The keys to use for verifying remote data. :type keys: :py:class:`~king_phisher.security_keys.SecurityKeys`
__init__
python
rsmusllp/king-phisher
king_phisher/catalog.py
https://github.com/rsmusllp/king-phisher/blob/master/king_phisher/catalog.py
BSD-3-Clause
def from_url(cls, url, keys=None, encoding='utf-8'): """ Initialize a new :py:class:`.Catalog` object from a resource at the specified URL. The resulting data is validated against a schema file with :py:func:`~king_phisher.utilities.validate_json_schema` before being passed to :py:meth:`~.__init__`. :param...
Initialize a new :py:class:`.Catalog` object from a resource at the specified URL. The resulting data is validated against a schema file with :py:func:`~king_phisher.utilities.validate_json_schema` before being passed to :py:meth:`~.__init__`. :param str url: The URL to the catalog data to load. :param ke...
from_url
python
rsmusllp/king-phisher
king_phisher/catalog.py
https://github.com/rsmusllp/king-phisher/blob/master/king_phisher/catalog.py
BSD-3-Clause
def sign_item_files(local_path, signing_key, repo_path=None): """ This utility function is used to create a :py:class:`.CollectionItemFile` iterator from the specified source to be included in either a catalog file or one of it's included files. .. warning:: This function contains a black list of file extension...
This utility function is used to create a :py:class:`.CollectionItemFile` iterator from the specified source to be included in either a catalog file or one of it's included files. .. warning:: This function contains a black list of file extensions which will be skipped. This is to avoid signing files originat...
sign_item_files
python
rsmusllp/king-phisher
king_phisher/catalog.py
https://github.com/rsmusllp/king-phisher/blob/master/king_phisher/catalog.py
BSD-3-Clause
def convert_hex_to_tuple(hex_color, raw=False): """ Converts an RGB hex triplet such as #ff0000 into an RGB tuple. If *raw* is True then each value is on a scale from 0 to 255 instead of 0.0 to 1.0. :param str hex_color: The hex code for the desired color. :param bool raw: Whether the values are raw or percentage...
Converts an RGB hex triplet such as #ff0000 into an RGB tuple. If *raw* is True then each value is on a scale from 0 to 255 instead of 0.0 to 1.0. :param str hex_color: The hex code for the desired color. :param bool raw: Whether the values are raw or percentages. :return: The color as a red, green, blue tuple. ...
convert_hex_to_tuple
python
rsmusllp/king-phisher
king_phisher/color.py
https://github.com/rsmusllp/king-phisher/blob/master/king_phisher/color.py
BSD-3-Clause
def convert_tuple_to_hex(rgb, raw=False): """ Converts an RGB color tuple info a hex string such as #ff0000. If *raw* is True then each value is treated as if it were on a scale from 0 to 255 instead of 0.0 to 1.0. :param tuple rgb: The RGB tuple to convert into a string. :param bool raw: Whether the values are ...
Converts an RGB color tuple info a hex string such as #ff0000. If *raw* is True then each value is treated as if it were on a scale from 0 to 255 instead of 0.0 to 1.0. :param tuple rgb: The RGB tuple to convert into a string. :param bool raw: Whether the values are raw or percentages. :return: The RGB color as...
convert_tuple_to_hex
python
rsmusllp/king-phisher
king_phisher/color.py
https://github.com/rsmusllp/king-phisher/blob/master/king_phisher/color.py
BSD-3-Clause
def get_scale(color_low, color_high, count, ascending=True): """ Create a scale of colors gradually moving from the low color to the high color. :param tuple color_low: The darker color to start the scale with. :param tuple color_high: The lighter color to end the scale with. :param count: The total number of re...
Create a scale of colors gradually moving from the low color to the high color. :param tuple color_low: The darker color to start the scale with. :param tuple color_high: The lighter color to end the scale with. :param count: The total number of resulting colors. :param bool ascending: Whether the colors should...
get_scale
python
rsmusllp/king-phisher
king_phisher/color.py
https://github.com/rsmusllp/king-phisher/blob/master/king_phisher/color.py
BSD-3-Clause
def print_error(message): """ Print an error message to the console. :param str message: The message to print """ prefix = '[-] ' if print_colors: prefix = termcolor.colored(prefix, 'red', attrs=['bold']) print(prefix + message)
Print an error message to the console. :param str message: The message to print
print_error
python
rsmusllp/king-phisher
king_phisher/color.py
https://github.com/rsmusllp/king-phisher/blob/master/king_phisher/color.py
BSD-3-Clause
def print_good(message): """ Print a good message to the console. :param str message: The message to print """ prefix = '[+] ' if print_colors: prefix = termcolor.colored(prefix, 'green', attrs=['bold']) print(prefix + message)
Print a good message to the console. :param str message: The message to print
print_good
python
rsmusllp/king-phisher
king_phisher/color.py
https://github.com/rsmusllp/king-phisher/blob/master/king_phisher/color.py
BSD-3-Clause
def print_status(message): """ Print a status message to the console. :param str message: The message to print """ prefix = '[*] ' if print_colors: prefix = termcolor.colored(prefix, 'blue', attrs=['bold']) print(prefix + message)
Print a status message to the console. :param str message: The message to print
print_status
python
rsmusllp/king-phisher
king_phisher/color.py
https://github.com/rsmusllp/king-phisher/blob/master/king_phisher/color.py
BSD-3-Clause
def names(cls): """Iterate over the names in a group of constants.""" for name in dir(cls): if name.upper() != name: continue yield name
Iterate over the names in a group of constants.
names
python
rsmusllp/king-phisher
king_phisher/constants.py
https://github.com/rsmusllp/king-phisher/blob/master/king_phisher/constants.py
BSD-3-Clause
def items(cls): """Iterate over the names and values in a group of constants.""" for name in dir(cls): if name.upper() != name: continue yield (name, getattr(cls, name))
Iterate over the names and values in a group of constants.
items
python
rsmusllp/king-phisher
king_phisher/constants.py
https://github.com/rsmusllp/king-phisher/blob/master/king_phisher/constants.py
BSD-3-Clause
def values(cls): """Iterate over the values in a group of constants.""" for name in dir(cls): if name.upper() != name: continue yield getattr(cls, name)
Iterate over the values in a group of constants.
values
python
rsmusllp/king-phisher
king_phisher/constants.py
https://github.com/rsmusllp/king-phisher/blob/master/king_phisher/constants.py
BSD-3-Clause
def __init__(self, response_sent=False): """ :param bool response_sent: Whether or not a response has already been sent to the client. """ super(KingPhisherAbortRequestError, self).__init__() self.response_sent = response_sent
:param bool response_sent: Whether or not a response has already been sent to the client.
__init__
python
rsmusllp/king-phisher
king_phisher/errors.py
https://github.com/rsmusllp/king-phisher/blob/master/king_phisher/errors.py
BSD-3-Clause
def data_path_append(path): """ Add a directory to the data search path. The directory will be used by the :py:func:`.data_file` and :py:func:`.data_directory` functions. :param str path: The path to add for searching. """ path_var = os.environ[ENV_VAR].split(os.pathsep) if path in path_var: return path_var...
Add a directory to the data search path. The directory will be used by the :py:func:`.data_file` and :py:func:`.data_directory` functions. :param str path: The path to add for searching.
data_path_append
python
rsmusllp/king-phisher
king_phisher/find.py
https://github.com/rsmusllp/king-phisher/blob/master/king_phisher/find.py
BSD-3-Clause
def init_data_path(directory=None): """ Add a directory to the data search path for either client or server data files. :param str directory: The directory to add, either 'client' or 'server'. """ found = False possible_data_paths = [] if its.frozen: possible_data_paths.append(os.path.dirname(sys.executable)...
Add a directory to the data search path for either client or server data files. :param str directory: The directory to add, either 'client' or 'server'.
init_data_path
python
rsmusllp/king-phisher
king_phisher/find.py
https://github.com/rsmusllp/king-phisher/blob/master/king_phisher/find.py
BSD-3-Clause
def data_file(name, access_mode=os.R_OK): """ Locate a data file by searching the directories specified in :py:data:`.ENV_VAR`. If *access_mode* is specified, it needs to be a value suitable for use with :py:func:`os.access`. :param str name: The name of the file to locate. :param int access_mode: The access tha...
Locate a data file by searching the directories specified in :py:data:`.ENV_VAR`. If *access_mode* is specified, it needs to be a value suitable for use with :py:func:`os.access`. :param str name: The name of the file to locate. :param int access_mode: The access that is required for the file. :return: The path...
data_file
python
rsmusllp/king-phisher
king_phisher/find.py
https://github.com/rsmusllp/king-phisher/blob/master/king_phisher/find.py
BSD-3-Clause
def data_directory(name, access_mode=os.R_OK): """ Locate a subdirectory in the data search path. :param str name: The directory name to locate. :param int access_mode: The access that is required for the directory. :return: The path to the located directory. :rtype: str """ search_path = os.environ[ENV_VAR] ...
Locate a subdirectory in the data search path. :param str name: The directory name to locate. :param int access_mode: The access that is required for the directory. :return: The path to the located directory. :rtype: str
data_directory
python
rsmusllp/king-phisher
king_phisher/find.py
https://github.com/rsmusllp/king-phisher/blob/master/king_phisher/find.py
BSD-3-Clause
def init_database(database_file): """ Create and initialize the GeoLite2 database engine. This must be done before classes and functions in this module attempt to look up results. If the specified database file does not exist, a new copy will be downloaded. :param str database_file: The GeoLite2 database file to ...
Create and initialize the GeoLite2 database engine. This must be done before classes and functions in this module attempt to look up results. If the specified database file does not exist, a new copy will be downloaded. :param str database_file: The GeoLite2 database file to use. :return: The initialized GeoLite...
init_database
python
rsmusllp/king-phisher
king_phisher/geoip.py
https://github.com/rsmusllp/king-phisher/blob/master/king_phisher/geoip.py
BSD-3-Clause
def lookup(ip, lang='en'): """ Lookup the geo location information for the specified IP from the configured GeoLite2 City database. :param str ip: The IP address to look up the information for. :param str lang: The language to prefer for regional names. :return: The geo location information as a dict. The keys a...
Lookup the geo location information for the specified IP from the configured GeoLite2 City database. :param str ip: The IP address to look up the information for. :param str lang: The language to prefer for regional names. :return: The geo location information as a dict. The keys are the values of :py:data:`.D...
lookup
python
rsmusllp/king-phisher
king_phisher/geoip.py
https://github.com/rsmusllp/king-phisher/blob/master/king_phisher/geoip.py
BSD-3-Clause
def __init__(self, ip, lang='en', result=None): """ :param str ip: The IP address to look up geographic location data for. :param str lang: The language to prefer for regional names. :param dict result: A raw query result from a previous call to :py:func:`.lookup`. """ if isinstance(ip, str): ip = ipaddr...
:param str ip: The IP address to look up geographic location data for. :param str lang: The language to prefer for regional names. :param dict result: A raw query result from a previous call to :py:func:`.lookup`.
__init__
python
rsmusllp/king-phisher
king_phisher/geoip.py
https://github.com/rsmusllp/king-phisher/blob/master/king_phisher/geoip.py
BSD-3-Clause
def get_timedelta_for_offset(offset): """ Take a POSIX environment variable style offset from UTC and convert it into a :py:class:`~datetime.timedelta` instance suitable for use with the :py:mod:`icalendar`. :param str offset: The offset from UTC such as "-5:00" :return: The parsed offset. :rtype: :py:class:`da...
Take a POSIX environment variable style offset from UTC and convert it into a :py:class:`~datetime.timedelta` instance suitable for use with the :py:mod:`icalendar`. :param str offset: The offset from UTC such as "-5:00" :return: The parsed offset. :rtype: :py:class:`datetime.timedelta`
get_timedelta_for_offset
python
rsmusllp/king-phisher
king_phisher/ics.py
https://github.com/rsmusllp/king-phisher/blob/master/king_phisher/ics.py
BSD-3-Clause
def get_tz_posix_env_var(tz_name): """ Get the timezone information in the POSIX TZ environment variable format from the IANA timezone data files included in the :py:mod:`pytz` package. :param str tz_name: The name of the timezone to get the environment variable for such as "America/New_York". :return: The TZ e...
Get the timezone information in the POSIX TZ environment variable format from the IANA timezone data files included in the :py:mod:`pytz` package. :param str tz_name: The name of the timezone to get the environment variable for such as "America/New_York". :return: The TZ environment variable string, if it is sp...
get_tz_posix_env_var
python
rsmusllp/king-phisher
king_phisher/ics.py
https://github.com/rsmusllp/king-phisher/blob/master/king_phisher/ics.py
BSD-3-Clause
def parse_tz_posix_env_var(posix_env_var): """ Get the details regarding a timezone by parsing the POSIX style TZ environment variable. :param str posix_env_var: The POSIX style TZ environment variable. :return: The parsed TZ environment variable. :rtype: :py:class:`.TimezoneOffsetDetails` """ match = POSIX_VA...
Get the details regarding a timezone by parsing the POSIX style TZ environment variable. :param str posix_env_var: The POSIX style TZ environment variable. :return: The parsed TZ environment variable. :rtype: :py:class:`.TimezoneOffsetDetails`
parse_tz_posix_env_var
python
rsmusllp/king-phisher
king_phisher/ics.py
https://github.com/rsmusllp/king-phisher/blob/master/king_phisher/ics.py
BSD-3-Clause
def __init__(self, tz_name=None): """ :param str tz_name: The timezone to represent, if not specified it defaults to the local timezone. """ super(Timezone, self).__init__() if tz_name is None: tz_name = tzlocal.get_localzone().zone self.add('tzid', tz_name) tz_details = parse_tz_posix_env_var(get_...
:param str tz_name: The timezone to represent, if not specified it defaults to the local timezone.
__init__
python
rsmusllp/king-phisher
king_phisher/ics.py
https://github.com/rsmusllp/king-phisher/blob/master/king_phisher/ics.py
BSD-3-Clause
def __init__(self, organizer_email, start, summary, organizer_cn=None, description=None, duration='1h', location=None): """ :param str organizer_email: The email of the event organizer. :param start: The start time for the event. :type start: :py:class:`datetime.datetime` :param str summary: A short summary o...
:param str organizer_email: The email of the event organizer. :param start: The start time for the event. :type start: :py:class:`datetime.datetime` :param str summary: A short summary of the event. :param str organizer_cn: The name of the event organizer. :param str description: A more complete descriptio...
__init__
python
rsmusllp/king-phisher
king_phisher/ics.py
https://github.com/rsmusllp/king-phisher/blob/master/king_phisher/ics.py
BSD-3-Clause
def add_attendee(self, email, cn=None, rsvp=True): """ Add an attendee to the event. If the event is being sent via an email, the recipient should be added as an attendee. :param str email: The attendee's email address. :param str cn: The attendee's common name. :param bool rsvp: Whether or not to request ...
Add an attendee to the event. If the event is being sent via an email, the recipient should be added as an attendee. :param str email: The attendee's email address. :param str cn: The attendee's common name. :param bool rsvp: Whether or not to request an RSVP response from the attendee.
add_attendee
python
rsmusllp/king-phisher
king_phisher/ics.py
https://github.com/rsmusllp/king-phisher/blob/master/king_phisher/ics.py
BSD-3-Clause
def is_loopback(address): """ Check if an address is a loopback address or a common name for the loopback interface. :param str address: The address to check. :return: Whether or not the address is a loopback address. :rtype: bool """ if address == 'localhost': return True elif is_valid(address) and ip_addr...
Check if an address is a loopback address or a common name for the loopback interface. :param str address: The address to check. :return: Whether or not the address is a loopback address. :rtype: bool
is_loopback
python
rsmusllp/king-phisher
king_phisher/ipaddress.py
https://github.com/rsmusllp/king-phisher/blob/master/king_phisher/ipaddress.py
BSD-3-Clause
def is_valid(address): """ Check that the string specified appears to be either a valid IPv4 or IPv6 address. :param str address: The IP address to validate. :return: Whether the IP address appears to be valid or not. :rtype: bool """ try: ipaddress.ip_address(address) except ValueError: return False ret...
Check that the string specified appears to be either a valid IPv4 or IPv6 address. :param str address: The IP address to validate. :return: Whether the IP address appears to be valid or not. :rtype: bool
is_valid
python
rsmusllp/king-phisher
king_phisher/ipaddress.py
https://github.com/rsmusllp/king-phisher/blob/master/king_phisher/ipaddress.py
BSD-3-Clause
def __init__(self, name, description, default=None): """ :param str name: The name of this option. :param str description: The description of this option. :param default: The default value of this option. """ self.name = name self.description = description self.default = default
:param str name: The name of this option. :param str description: The description of this option. :param default: The default value of this option.
__init__
python
rsmusllp/king-phisher
king_phisher/plugins.py
https://github.com/rsmusllp/king-phisher/blob/master/king_phisher/plugins.py
BSD-3-Clause
def __init__(self, name, description, choices, default=None): """ :param str name: The name of this option. :param str description: The description of this option. :param tuple choices: The supported values for this option. :param default: The default value of this option. """ self.choices = choices sup...
:param str name: The name of this option. :param str description: The description of this option. :param tuple choices: The supported values for this option. :param default: The default value of this option.
__init__
python
rsmusllp/king-phisher
king_phisher/plugins.py
https://github.com/rsmusllp/king-phisher/blob/master/king_phisher/plugins.py
BSD-3-Clause
def __init__(self, items): """ :param dict items: A dictionary or two-dimensional array mapping requirement names to their respective values. """ # call dict here to allow items to be a two dimensional array suitable for passing to dict items = dict(items) packages = items.get('packages') if isinstance(pa...
:param dict items: A dictionary or two-dimensional array mapping requirement names to their respective values.
__init__
python
rsmusllp/king-phisher
king_phisher/plugins.py
https://github.com/rsmusllp/king-phisher/blob/master/king_phisher/plugins.py
BSD-3-Clause
def is_compatible(self): """Whether or not all requirements are met.""" for req_type, req_details, req_met in self.compatibility_iter(): if not req_met: return False return True
Whether or not all requirements are met.
is_compatible
python
rsmusllp/king-phisher
king_phisher/plugins.py
https://github.com/rsmusllp/king-phisher/blob/master/king_phisher/plugins.py
BSD-3-Clause
def compatibility_iter(self): """ Iterate over each of the requirements, evaluate them and yield a tuple regarding them. """ StrictVersion = distutils.version.StrictVersion if self._storage.get('minimum-python-version'): # platform.python_version() cannot be used with StrictVersion because it returns let...
Iterate over each of the requirements, evaluate them and yield a tuple regarding them.
compatibility_iter
python
rsmusllp/king-phisher
king_phisher/plugins.py
https://github.com/rsmusllp/king-phisher/blob/master/king_phisher/plugins.py
BSD-3-Clause
def __init__(self, path, args=None, library_path=constants.AUTOMATIC): """ :param tuple path: A tuple of directories from which to load plugins. :param tuple args: Arguments which should be passed to plugins when their class is initialized. :param str library_path: A path to use for plugins library dependenc...
:param tuple path: A tuple of directories from which to load plugins. :param tuple args: Arguments which should be passed to plugins when their class is initialized. :param str library_path: A path to use for plugins library dependencies. This value will be added to :py:attr:`sys.path` if it is not already...
__init__
python
rsmusllp/king-phisher
king_phisher/plugins.py
https://github.com/rsmusllp/king-phisher/blob/master/king_phisher/plugins.py
BSD-3-Clause
def get_plugin_path(self, name): """ Get the path at which the plugin data resides. This is either the path to the single plugin file or a folder in the case that the plugin is a module. In either case, the path is an absolute path. :param str name: The name of the plugin to get the path for. :return: The ...
Get the path at which the plugin data resides. This is either the path to the single plugin file or a folder in the case that the plugin is a module. In either case, the path is an absolute path. :param str name: The name of the plugin to get the path for. :return: The path of the plugin data. :rtype: str...
get_plugin_path
python
rsmusllp/king-phisher
king_phisher/plugins.py
https://github.com/rsmusllp/king-phisher/blob/master/king_phisher/plugins.py
BSD-3-Clause
def enable(self, name): """ Enable a plugin by it's name. This will create a new instance of the plugin modules "Plugin" class, passing it the arguments defined in :py:attr:`.plugin_init_args`. A reference to the plugin instance is kept in :py:attr:`.enabled_plugins`. After the instance is created, the plug...
Enable a plugin by it's name. This will create a new instance of the plugin modules "Plugin" class, passing it the arguments defined in :py:attr:`.plugin_init_args`. A reference to the plugin instance is kept in :py:attr:`.enabled_plugins`. After the instance is created, the plugins :py:meth:`~.PluginBase.in...
enable
python
rsmusllp/king-phisher
king_phisher/plugins.py
https://github.com/rsmusllp/king-phisher/blob/master/king_phisher/plugins.py
BSD-3-Clause
def disable(self, name): """ Disable a plugin by it's name. This call the plugins :py:meth:`.PluginBase.finalize` method to allow it to perform any clean up operations. :param str name: The name of the plugin to disable. """ self._lock.acquire() inst = self.enabled_plugins[name] inst.finalize() ins...
Disable a plugin by it's name. This call the plugins :py:meth:`.PluginBase.finalize` method to allow it to perform any clean up operations. :param str name: The name of the plugin to disable.
disable
python
rsmusllp/king-phisher
king_phisher/plugins.py
https://github.com/rsmusllp/king-phisher/blob/master/king_phisher/plugins.py
BSD-3-Clause
def load(self, name, reload_module=False): """ Load a plugin into memory, this is effectively the Python equivalent of importing it. A reference to the plugin class is kept in :py:attr:`.loaded_plugins`. If the plugin is already loaded, no changes are made. :param str name: The name of the plugin to load. ...
Load a plugin into memory, this is effectively the Python equivalent of importing it. A reference to the plugin class is kept in :py:attr:`.loaded_plugins`. If the plugin is already loaded, no changes are made. :param str name: The name of the plugin to load. :param bool reload_module: Reload the module t...
load
python
rsmusllp/king-phisher
king_phisher/plugins.py
https://github.com/rsmusllp/king-phisher/blob/master/king_phisher/plugins.py
BSD-3-Clause
def load_all(self, on_error=None): """ Load all available plugins. Exceptions while loading specific plugins are ignored. If *on_error* is specified, it will be called from within the exception handler when a plugin fails to load correctly. It will be called with two parameters, the name of the plugin and the...
Load all available plugins. Exceptions while loading specific plugins are ignored. If *on_error* is specified, it will be called from within the exception handler when a plugin fails to load correctly. It will be called with two parameters, the name of the plugin and the exception instance. :param on_erro...
load_all
python
rsmusllp/king-phisher
king_phisher/plugins.py
https://github.com/rsmusllp/king-phisher/blob/master/king_phisher/plugins.py
BSD-3-Clause
def load_module(self, name, reload_module=False): """ Load the module which contains a plugin into memory and return the entire module object. :param str name: The name of the plugin module to load. :param bool reload_module: Reload the module to allow changes to take affect. :return: The plugin module. ...
Load the module which contains a plugin into memory and return the entire module object. :param str name: The name of the plugin module to load. :param bool reload_module: Reload the module to allow changes to take affect. :return: The plugin module.
load_module
python
rsmusllp/king-phisher
king_phisher/plugins.py
https://github.com/rsmusllp/king-phisher/blob/master/king_phisher/plugins.py
BSD-3-Clause
def install_packages(self, packages): """ This function will take a list of Python packages and attempt to install them through pip to the :py:attr:`.library_path`. .. versionadded:: 1.14.0 :param list packages: list of python packages to install using pip. :return: The process results from the command ex...
This function will take a list of Python packages and attempt to install them through pip to the :py:attr:`.library_path`. .. versionadded:: 1.14.0 :param list packages: list of python packages to install using pip. :return: The process results from the command execution. :rtype: :py:class:`~.ProcessResu...
install_packages
python
rsmusllp/king-phisher
king_phisher/plugins.py
https://github.com/rsmusllp/king-phisher/blob/master/king_phisher/plugins.py
BSD-3-Clause
def uninstall(self, name): """ Uninstall a plugin by first unloading it and then delete it's data on disk. The plugin data on disk is found with the :py:meth:`.get_plugin_path` method. :param str name: The name of the plugin to uninstall. :return: Whether or not the plugin was successfully uninstalled. :...
Uninstall a plugin by first unloading it and then delete it's data on disk. The plugin data on disk is found with the :py:meth:`.get_plugin_path` method. :param str name: The name of the plugin to uninstall. :return: Whether or not the plugin was successfully uninstalled. :rtype: bool
uninstall
python
rsmusllp/king-phisher
king_phisher/plugins.py
https://github.com/rsmusllp/king-phisher/blob/master/king_phisher/plugins.py
BSD-3-Clause
def unload(self, name): """ Unload a plugin from memory. If the specified plugin is currently enabled, it will first be disabled before being unloaded. If the plugin is not already loaded, no changes are made. :param str name: The name of the plugin to unload. """ self._lock.acquire() if not name in se...
Unload a plugin from memory. If the specified plugin is currently enabled, it will first be disabled before being unloaded. If the plugin is not already loaded, no changes are made. :param str name: The name of the plugin to unload.
unload
python
rsmusllp/king-phisher
king_phisher/plugins.py
https://github.com/rsmusllp/king-phisher/blob/master/king_phisher/plugins.py
BSD-3-Clause
def unload_all(self): """ Unload all available plugins. Exceptions while unloading specific plugins are ignored. """ self._lock.acquire() self.logger.info("unloading {0:,} plugins".format(len(self.loaded_plugins))) for name in tuple(self.loaded_plugins.keys()): try: self.unload(name) except Exce...
Unload all available plugins. Exceptions while unloading specific plugins are ignored.
unload_all
python
rsmusllp/king-phisher
king_phisher/plugins.py
https://github.com/rsmusllp/king-phisher/blob/master/king_phisher/plugins.py
BSD-3-Clause
def openssl_decrypt_data(ciphertext, password, digest='sha256', encoding='utf-8'): """ Decrypt *ciphertext* in the same way as OpenSSL. For the meaning of *digest* see the :py:func:`.openssl_derive_key_and_iv` function documentation. .. note:: This function can be used to decrypt ciphertext created with the `...
Decrypt *ciphertext* in the same way as OpenSSL. For the meaning of *digest* see the :py:func:`.openssl_derive_key_and_iv` function documentation. .. note:: This function can be used to decrypt ciphertext created with the ``openssl`` command line utility. .. code-block:: none openssl enc -e -aes-256-cb...
openssl_decrypt_data
python
rsmusllp/king-phisher
king_phisher/security_keys.py
https://github.com/rsmusllp/king-phisher/blob/master/king_phisher/security_keys.py
BSD-3-Clause
def openssl_derive_key_and_iv(password, salt, key_length, iv_length, digest='sha256', encoding='utf-8'): """ Derive an encryption key and initialization vector (IV) in the same way as OpenSSL. .. note:: Different versions of OpenSSL use a different default value for the *digest* function used to derive keys an...
Derive an encryption key and initialization vector (IV) in the same way as OpenSSL. .. note:: Different versions of OpenSSL use a different default value for the *digest* function used to derive keys and initialization vectors. A specific one can be used by passing the ``-md`` option to the ``openssl`` com...
openssl_derive_key_and_iv
python
rsmusllp/king-phisher
king_phisher/security_keys.py
https://github.com/rsmusllp/king-phisher/blob/master/king_phisher/security_keys.py
BSD-3-Clause
def from_file(cls, file_path, password=None, encoding='utf-8'): """ Load the signing key from the specified file. If *password* is specified, the file is assumed to have been encrypted using OpenSSL with ``aes-256-cbc`` as the cipher and ``sha256`` as the message digest. This uses :py:func:`.openssl_decrypt_d...
Load the signing key from the specified file. If *password* is specified, the file is assumed to have been encrypted using OpenSSL with ``aes-256-cbc`` as the cipher and ``sha256`` as the message digest. This uses :py:func:`.openssl_decrypt_data` internally for decrypting the data. :param str file_path: T...
from_file
python
rsmusllp/king-phisher
king_phisher/security_keys.py
https://github.com/rsmusllp/king-phisher/blob/master/king_phisher/security_keys.py
BSD-3-Clause
def sign_dict(self, data, signature_encoding='base64'): """ Sign a dictionary object. The dictionary will have a 'signature' key added is required by the :py:meth:`.VerifyingKey.verify_dict` method. To serialize the dictionary to data suitable for the operation the :py:func:`json.dumps` function is used and t...
Sign a dictionary object. The dictionary will have a 'signature' key added is required by the :py:meth:`.VerifyingKey.verify_dict` method. To serialize the dictionary to data suitable for the operation the :py:func:`json.dumps` function is used and the resulting data is then UTF-8 encoded. :param dict dat...
sign_dict
python
rsmusllp/king-phisher
king_phisher/security_keys.py
https://github.com/rsmusllp/king-phisher/blob/master/king_phisher/security_keys.py
BSD-3-Clause
def verify_dict(self, data, signature_encoding='base64'): """ Verify a signed dictionary object. The dictionary must have a 'signature' key as added by the :py:meth:`.SigningKey.sign_dict` method. To serialize the dictionary to data suitable for the operation the :py:func:`json.dumps` function is used and the...
Verify a signed dictionary object. The dictionary must have a 'signature' key as added by the :py:meth:`.SigningKey.sign_dict` method. To serialize the dictionary to data suitable for the operation the :py:func:`json.dumps` function is used and the resulting data is then UTF-8 encoded. :param dict data: T...
verify_dict
python
rsmusllp/king-phisher
king_phisher/security_keys.py
https://github.com/rsmusllp/king-phisher/blob/master/king_phisher/security_keys.py
BSD-3-Clause
def verify(self, key_id, data, signature): """ Verify the data with the specified signature as signed by the specified key. This function will raise an exception if the verification fails for any reason, including if the key can not be found. :param str key_id: The key's identifier. :param bytes data: The ...
Verify the data with the specified signature as signed by the specified key. This function will raise an exception if the verification fails for any reason, including if the key can not be found. :param str key_id: The key's identifier. :param bytes data: The data to verify against the signature. :param b...
verify
python
rsmusllp/king-phisher
king_phisher/security_keys.py
https://github.com/rsmusllp/king-phisher/blob/master/king_phisher/security_keys.py
BSD-3-Clause
def verify_dict(self, data, signature_encoding='base64'): """ Verify the signed dictionary, using the key specified within the 'signed-by' key. This function will raise an exception if the verification fails for any reason, including if the key can not be found. :param str key_id: The key's identifier. :...
Verify the signed dictionary, using the key specified within the 'signed-by' key. This function will raise an exception if the verification fails for any reason, including if the key can not be found. :param str key_id: The key's identifier. :param bytes data: The data to verify against the signature. :...
verify_dict
python
rsmusllp/king-phisher
king_phisher/security_keys.py
https://github.com/rsmusllp/king-phisher/blob/master/king_phisher/security_keys.py
BSD-3-Clause
def dumps(cls, data, pretty=True): """ Convert a Python object to a JSON encoded string. :param data: The object to encode. :param bool pretty: Set options to make the resulting JSON data more readable. :return: The encoded data. :rtype: str """ kwargs = {'default': cls._json_default} if pretty: k...
Convert a Python object to a JSON encoded string. :param data: The object to encode. :param bool pretty: Set options to make the resulting JSON data more readable. :return: The encoded data. :rtype: str
dumps
python
rsmusllp/king-phisher
king_phisher/serializers.py
https://github.com/rsmusllp/king-phisher/blob/master/king_phisher/serializers.py
BSD-3-Clause
def loads(cls, data, strict=True): """ Load JSON encoded data. :param str data: The encoded data to load. :param bool strict: Do not try remove trailing commas from the JSON data. :return: The Python object represented by the encoded data. """ if not strict: data = CLEAN_JSON_REGEX.sub(r'\1', data) ...
Load JSON encoded data. :param str data: The encoded data to load. :param bool strict: Do not try remove trailing commas from the JSON data. :return: The Python object represented by the encoded data.
loads
python
rsmusllp/king-phisher
king_phisher/serializers.py
https://github.com/rsmusllp/king-phisher/blob/master/king_phisher/serializers.py
BSD-3-Clause
def from_elementtree_element(element, require_type=True): """ Load a value from an :py:class:`xml.etree.ElementTree.SubElement` instance. If *require_type* is True, then the element must specify an acceptable value via the "type" attribute. If *require_type* is False and no type attribute is specified, the value i...
Load a value from an :py:class:`xml.etree.ElementTree.SubElement` instance. If *require_type* is True, then the element must specify an acceptable value via the "type" attribute. If *require_type* is False and no type attribute is specified, the value is returned as a string. :param element: The element to load ...
from_elementtree_element
python
rsmusllp/king-phisher
king_phisher/serializers.py
https://github.com/rsmusllp/king-phisher/blob/master/king_phisher/serializers.py
BSD-3-Clause
def to_elementtree_subelement(parent, tag, value, attrib=None): """ Serialize *value* to an :py:class:`xml.etree.ElementTree.SubElement` with appropriate information describing it's type. If *value* is not of a supported type, a :py:exc:`TypeError` will be raised. :param parent: The parent element to associate th...
Serialize *value* to an :py:class:`xml.etree.ElementTree.SubElement` with appropriate information describing it's type. If *value* is not of a supported type, a :py:exc:`TypeError` will be raised. :param parent: The parent element to associate this subelement with. :type parent: :py:class:`xml.etree.ElementTree....
to_elementtree_subelement
python
rsmusllp/king-phisher
king_phisher/serializers.py
https://github.com/rsmusllp/king-phisher/blob/master/king_phisher/serializers.py
BSD-3-Clause
def get_smtp_servers(domain): """ Get the SMTP servers for the specified domain by querying their MX records. :param str domain: The domain to look up the MX records for. :return: The smtp servers for the specified domain. :rtype: list """ mx_records = dns.resolver.query(domain, 'MX') return [str(r.exchange).r...
Get the SMTP servers for the specified domain by querying their MX records. :param str domain: The domain to look up the MX records for. :return: The smtp servers for the specified domain. :rtype: list
get_smtp_servers
python
rsmusllp/king-phisher
king_phisher/sms.py
https://github.com/rsmusllp/king-phisher/blob/master/king_phisher/sms.py
BSD-3-Clause
def lookup_carrier_gateway(carrier): """ Lookup the SMS gateway for the specified carrier. Normalization on the carrier name does take place and if an invalid or unknown value is specified, None will be returned. :param str carrier: The name of the carrier to lookup. :return: The SMS gateway for the specified ca...
Lookup the SMS gateway for the specified carrier. Normalization on the carrier name does take place and if an invalid or unknown value is specified, None will be returned. :param str carrier: The name of the carrier to lookup. :return: The SMS gateway for the specified carrier. :rtype: str
lookup_carrier_gateway
python
rsmusllp/king-phisher
king_phisher/sms.py
https://github.com/rsmusllp/king-phisher/blob/master/king_phisher/sms.py
BSD-3-Clause
def send_sms(message_text, phone_number, carrier, from_address=None): """ Send an SMS message by emailing the carriers SMS gateway. This method requires no money however some networks are blocked by the carriers due to being flagged for spam which can cause issues. :param str message_text: The message to send. :...
Send an SMS message by emailing the carriers SMS gateway. This method requires no money however some networks are blocked by the carriers due to being flagged for spam which can cause issues. :param str message_text: The message to send. :param str phone_number: The phone number to send the SMS to. :param str c...
send_sms
python
rsmusllp/king-phisher
king_phisher/sms.py
https://github.com/rsmusllp/king-phisher/blob/master/king_phisher/sms.py
BSD-3-Clause
def __init__(self, localaddr, remoteaddr=None): """ :param tuple localaddr: The local address to bind to. :param tuple remoteaddr: The remote address to use as an upstream SMTP relayer. """ self.logger = logging.getLogger('KingPhisher.SMTPD') super(BaseSMTPServer, self).__init__(localaddr, remoteaddr) sel...
:param tuple localaddr: The local address to bind to. :param tuple remoteaddr: The remote address to use as an upstream SMTP relayer.
__init__
python
rsmusllp/king-phisher
king_phisher/smtp_server.py
https://github.com/rsmusllp/king-phisher/blob/master/king_phisher/smtp_server.py
BSD-3-Clause
def __init__(self, mechanism, qualifier, rvalue=None): """ :param str mechanism: The SPF mechanism that this directive uses. :param str qualifier: The qualifier value of the directive in it's single character format. :param str rvalue: The optional rvalue for directives which use them. """ if qualifier not ...
:param str mechanism: The SPF mechanism that this directive uses. :param str qualifier: The qualifier value of the directive in it's single character format. :param str rvalue: The optional rvalue for directives which use them.
__init__
python
rsmusllp/king-phisher
king_phisher/spf.py
https://github.com/rsmusllp/king-phisher/blob/master/king_phisher/spf.py
BSD-3-Clause
def from_string(cls, directive): """ Parse an SPF directive from a string and return it's class representation. :param str directive: The SPF directive to parse. """ if ':' in directive: (mechanism, rvalue) = directive.split(':', 1) else: (mechanism, rvalue) = (directive, None) mechanism = mechan...
Parse an SPF directive from a string and return it's class representation. :param str directive: The SPF directive to parse.
from_string
python
rsmusllp/king-phisher
king_phisher/spf.py
https://github.com/rsmusllp/king-phisher/blob/master/king_phisher/spf.py
BSD-3-Clause
def __init__(self, directives, domain=None): """ :param list directives: A list of :py:class:`.SPFDirective` instances. :param str domain: The domain with which this record is associated with. """ self.directives = directives self.domain = domain
:param list directives: A list of :py:class:`.SPFDirective` instances. :param str domain: The domain with which this record is associated with.
__init__
python
rsmusllp/king-phisher
king_phisher/spf.py
https://github.com/rsmusllp/king-phisher/blob/master/king_phisher/spf.py
BSD-3-Clause
def validate_record(ip, domain, sender=None): """ Check if an SPF record exists for the domain and can be parsed by this module. :return: Whether the record exists and is parsable or not. :rtype: bool """ try: result = check_host(ip, domain, sender) except SPFPermError: return False return isinstance(resu...
Check if an SPF record exists for the domain and can be parsed by this module. :return: Whether the record exists and is parsable or not. :rtype: bool
validate_record
python
rsmusllp/king-phisher
king_phisher/spf.py
https://github.com/rsmusllp/king-phisher/blob/master/king_phisher/spf.py
BSD-3-Clause
def __init__(self, ip, domain, sender=None, timeout=DEFAULT_DNS_TIMEOUT): """ :param ip: The IP address of the host sending the message. :type ip: str, :py:class:`ipaddress.IPv4Address`, :py:class:`ipaddress.IPv6Address` :param str domain: The domain to check the SPF policy of. :param str sender: The "MAIL FR...
:param ip: The IP address of the host sending the message. :type ip: str, :py:class:`ipaddress.IPv4Address`, :py:class:`ipaddress.IPv6Address` :param str domain: The domain to check the SPF policy of. :param str sender: The "MAIL FROM" identity of the message being sent. :param int timeout: The timeout for D...
__init__
python
rsmusllp/king-phisher
king_phisher/spf.py
https://github.com/rsmusllp/king-phisher/blob/master/king_phisher/spf.py
BSD-3-Clause
def check_host(self): """ Check the SPF policy described by the object. The string representing the matched policy is returned if an SPF policy exists, otherwise None will be returned if no policy is defined. :return: The result of the SPF policy described by the object. :rtype: None, str """ if not se...
Check the SPF policy described by the object. The string representing the matched policy is returned if an SPF policy exists, otherwise None will be returned if no policy is defined. :return: The result of the SPF policy described by the object. :rtype: None, str
check_host
python
rsmusllp/king-phisher
king_phisher/spf.py
https://github.com/rsmusllp/king-phisher/blob/master/king_phisher/spf.py
BSD-3-Clause
def _hostname_matches_additional(self, ip, name, additional): """ Search for *name* in *additional* and if it is found, check that it includes *ip*. :param ip: The IP address to search for. :type ip: :py:class:`ipaddress.IPv4Address`, :py:class:`ipaddress.IPv6Address` :param str name: The name to search fo...
Search for *name* in *additional* and if it is found, check that it includes *ip*. :param ip: The IP address to search for. :type ip: :py:class:`ipaddress.IPv4Address`, :py:class:`ipaddress.IPv6Address` :param str name: The name to search for. :param tuple additional: The additional data returned from a d...
_hostname_matches_additional
python
rsmusllp/king-phisher
king_phisher/spf.py
https://github.com/rsmusllp/king-phisher/blob/master/king_phisher/spf.py
BSD-3-Clause
def expand_macros(self, value, ip, domain, sender): """ Expand a string based on the macros it contains as specified by section 7 of :rfc:`7208`. :param str value: The string containing macros to expand. :param ip: The IP address to use when expanding macros. :type ip: str, :py:class:`ipaddress.IPv4Address...
Expand a string based on the macros it contains as specified by section 7 of :rfc:`7208`. :param str value: The string containing macros to expand. :param ip: The IP address to use when expanding macros. :type ip: str, :py:class:`ipaddress.IPv4Address`, :py:class:`ipaddress.IPv6Address` :param str domain:...
expand_macros
python
rsmusllp/king-phisher
king_phisher/spf.py
https://github.com/rsmusllp/king-phisher/blob/master/king_phisher/spf.py
BSD-3-Clause
def __init__(self, server, username, password, remote_server, local_port=0, private_key=None, missing_host_key_policy=None): """ :param tuple server: The SSH server to connect to. :param str username: The username to authenticate with. :param str password: The password to authenticate with. :param tuple remot...
:param tuple server: The SSH server to connect to. :param str username: The username to authenticate with. :param str password: The password to authenticate with. :param tuple remote_server: The remote server to connect to through the specified SSH server. :param int local_port: The local port to forward, if...
__init__
python
rsmusllp/king-phisher
king_phisher/ssh_forward.py
https://github.com/rsmusllp/king-phisher/blob/master/king_phisher/ssh_forward.py
BSD-3-Clause
def _run_pipenv(args, **kwargs): """ Execute Pipenv with the supplied arguments and return the :py:class:`~.ProcessResults`. If the exit status is non-zero, then the stdout buffer from the Pipenv execution will be written to stderr. :param tuple args: The arguments for the Pipenv. :param str cwd: An optional cur...
Execute Pipenv with the supplied arguments and return the :py:class:`~.ProcessResults`. If the exit status is non-zero, then the stdout buffer from the Pipenv execution will be written to stderr. :param tuple args: The arguments for the Pipenv. :param str cwd: An optional current working directory to use for the...
_run_pipenv
python
rsmusllp/king-phisher
king_phisher/startup.py
https://github.com/rsmusllp/king-phisher/blob/master/king_phisher/startup.py
BSD-3-Clause
def pipenv_entry(parser, entry_point): """ Run through startup logic for a Pipenv script (see Pipenv: `Custom Script Shortcuts`_ for more information). This sets up a basic stream logging configuration, establishes the Pipenv environment and finally calls the actual entry point using :py:func:`os.execve`. .. not...
Run through startup logic for a Pipenv script (see Pipenv: `Custom Script Shortcuts`_ for more information). This sets up a basic stream logging configuration, establishes the Pipenv environment and finally calls the actual entry point using :py:func:`os.execve`. .. note:: Due to the use of :py:func:`os.execve...
pipenv_entry
python
rsmusllp/king-phisher
king_phisher/startup.py
https://github.com/rsmusllp/king-phisher/blob/master/king_phisher/startup.py
BSD-3-Clause