text stringlengths 81 112k |
|---|
Removes node from circle and rebuild it.
def remove_node(self, node):
"""Removes node from circle and rebuild it."""
try:
self._nodes.remove(node)
del self._weights[node]
except (KeyError, ValueError):
pass
self._rebuild_circle() |
Adds node to circle and rebuild it.
def add_node(self, node, weight=1):
"""Adds node to circle and rebuild it."""
self._nodes.add(node)
self._weights[node] = weight
self._rebuild_circle() |
Return node for a given key. Else return None.
def get_node(self, key):
"""Return node for a given key. Else return None."""
pos = self._get_node_pos(key)
if pos is None:
return None
return self._hashring[self._sorted_keys[pos]] |
Error checking proper value returns
def check_error(result, func, cargs):
"Error checking proper value returns"
if result != 0:
msg = 'Error in "%s": %s' % (func.__name__, get_errors(result) )
raise RTreeError(msg)
return |
Take in dd string and convert to dms
def ddtodms(self, dd):
"""Take in dd string and convert to dms"""
negative = dd < 0
dd = abs(dd)
minutes,seconds = divmod(dd*3600,60)
degrees,minutes = divmod(minutes,60)
if negative:
if degrees > 0:
degree... |
convert dms to dd
def dmstodd(self, dms):
""" convert dms to dd"""
size = len(dms)
letters = 'WENS'
is_annotated = False
try:
float(dms)
except ValueError:
for letter in letters:
if letter in dms.upper():
is_an... |
Obtain a proper file object.
Parameters
----------
fname : string, file object, file descriptor
If a string or file descriptor, then we create a file object. If
*fname* is a file object, then we do nothing and ignore the specified
*mode* parameter.
mode : str
The mode of... |
Load graph as defined by a DOT file.
The file is assumed to be in DOT format. It will
be loaded, parsed and a Dot class will be returned,
representing the graph.
def graph_from_dot_file(path):
"""Load graph as defined by a DOT file.
The file is assumed to be in DOT format. It will
be loaded, ... |
Creates a basic graph out of an edge list.
The edge list has to be a list of tuples representing
the nodes connected by the edge.
The values can be anything: bool, int, float, str.
If the graph is undirected by default, it is only
calculated from one of the symmetric halves of the matrix.
def gra... |
Creates a basic graph out of an adjacency matrix.
The matrix has to be a list of rows of values
representing an adjacency matrix.
The values can be anything: bool, int, float, as long
as they can evaluate to True or False.
def graph_from_adjacency_matrix(matrix, node_prefix='', directed=False):
""... |
Creates a basic graph out of an incidence matrix.
The matrix has to be a list of rows of values
representing an incidence matrix.
The values can be anything: bool, int, float, as long
as they can evaluate to True or False.
def graph_from_incidence_matrix(matrix, node_prefix='', directed=False):
""... |
Used by find_graphviz
path - single directory as a string
If any of the executables are found, it will return a dictionary
containing the program names as keys and their paths as values.
Otherwise returns None
def __find_executables(path):
"""Used by find_graphviz
path - single directory as... |
Locate Graphviz's executables in the system.
Tries three methods:
First: Windows Registry (Windows only)
This requires Mark Hammond's pywin32 is installed.
Secondly: Search the path
It will look for 'dot', 'twopi' and 'neato' in all the directories
specified in the PATH environment variable.
... |
Get the list of Node instances.
This method returns the list of Node instances
composing the graph.
def get_node_list(self):
"""Get the list of Node instances.
This method returns the list of Node instances
composing the graph.
"""
node_objs = list()
f... |
Delete an edge from the graph.
Given an edge's (source, destination) node names all
matching edges(s) will be deleted if 'index' is not
specified or set to None.
If there are several matching edges and 'index' is
given, only the edge in that position will be deleted.
'i... |
Get the list of Edge instances.
This method returns the list of Edge instances
composing the graph.
def get_edge_list(self):
"""Get the list of Edge instances.
This method returns the list of Edge instances
composing the graph.
"""
edge_objs = list()
f... |
Returns a string representation of the graph in dot language.
It will return the graph and all its subelements in string from.
def to_string(self):
"""Returns a string representation of the graph in dot language.
It will return the graph and all its subelements in string from.
"""
... |
Write graph to file in selected format.
Given a filename 'path' it will open/create and truncate
such file and write on it a representation of the graph
defined by the dot object and in the format specified by
'format'. 'path' can also be an open file-like object, such as
a Stri... |
Get crumbs for navigation links.
Returns:
tuple:
concatenated list of crumbs using these crumbs and the
crumbs of the parent classes through ``__mro__``.
def get_crumbs(self):
"""
Get crumbs for navigation links.
Returns:
tuple:
... |
Django view get function.
Add items of extra_context, crumbs and grid to context.
Args:
request (): Django's request object.
*args (): request args.
**kwargs (): request kwargs.
Returns:
response: render to response with context.
def get(self, ... |
Return a widget as real-time.
Args:
widget (Widget): the widget to register and return as real-time.
url_name (str): the URL name to call to get updated content.
url_regex (regex): the URL regex to be matched.
time_interval (int): the interval of refreshment in milliseconds.
Re... |
Get the URL for real-time widgets.
Args:
admin_view_func (callable): an admin_view method from an AdminSite
instance. By default: identity.
Returns:
list: the list of the real-time URLs as django's ``url()``.
def get_realtime_urls(admin_view_func=lambda x: x):
"""
Get the ... |
Sets up the database schema and adds defaults.
:param connection_string: Database URL. e.g: sqlite:///filename.db
This is usually taken from the config file.
def setup_db(connection_string):
"""
Sets up the database schema and adds defaults.
:param connection_string: D... |
Start a PTY - intended to run it a (green)thread.
def start_pty_request(self, channel, term, modes):
"""Start a PTY - intended to run it a (green)thread."""
request = self.dummy_request()
request._sock = channel
request.modes = modes
request.term = term
request.username ... |
Make sure our Honeypot time is consistent, and not too far off
from the actual time.
def check_time(self):
""" Make sure our Honeypot time is consistent, and not too far off
from the actual time. """
poll = self.config['timecheck']['poll']
ntp_poll = self.config['timecheck']['n... |
Starts services.
def start(self):
""" Starts services. """
# protocol handlers
for c in handlerbase.HandlerBase.__subclasses__():
cap_name = c.__name__.lower()
if cap_name in self.config['capabilities']:
port = self.config['capabilities'][cap_name]['po... |
Stops services
def stop(self):
"""Stops services"""
for s in self._servers:
s.stop()
for g in self._server_greenlets:
g.kill()
logger.info('All workers stopped.') |
Performs a few maintenance tasks before the Honeypot is run. Copies the data directory,
and the config file to the cwd. The config file copied here is overwritten if
the __init__ method is called with a configuration URL.
:param work_dir: The directory to copy files to.
def prepare_env... |
Launches a new HTTP client session on the server taken from the `self.options` dict.
:param my_ip: IP of this Client itself
def start(self):
"""
Launches a new HTTP client session on the server taken from the `self.options` dict.
:param my_ip: IP of this Client itself
"""... |
Parses the response text and returns all the links in it.
:param response: The Response object.
def _get_links(self, response):
"""
Parses the response text and returns all the links in it.
:param response: The Response object.
"""
html_text = response.text.encode(... |
Bootstraps localhost configurations for a Beeswarm server and a honeypot.
:param server_workdir: Output directory for the server configuration file.
:param drone_workdir: Output directory for the drone configuration file.
def bootstrap(server_workdir, drone_workdir):
"""Bootstraps localhost configurations... |
Check if a database exists.
:param url: A SQLAlchemy engine URL.
Performs backend-specific testing to quickly determine if a database
exists on the server. ::
database_exists('postgres://postgres@localhost/name') #=> False
create_database('postgres://postgres@localhost/name')
dat... |
drone_data_inboud is for data comming from drones
drone_data_outbound is for commands to the drones, topic must either be a drone ID or all for sending
a broadcast message to all drones
def message_proxy(self, work_dir):
"""
drone_data_inboud is for data comming ... |
Starts the BeeSwarm server.
def start(self):
"""
Starts the BeeSwarm server.
"""
self.started = True
if self.app:
web_port = self.config['network']['web_port']
logger.info('Starting server listening on port {0}'.format(web_port))
key_file ... |
Loads the configuration from the JSON file, and returns it.
:param configfile: Path to the configuration file
def get_config(self, configfile):
"""
Loads the configuration from the JSON file, and returns it.
:param configfile: Path to the configuration file
"""
with ... |
Return true if current time is in the active range
def time_in_range(self):
"""Return true if current time is in the active range"""
curr = datetime.datetime.now().time()
if self.start_time <= self.end_time:
return self.start_time <= curr <= self.end_time
else:
r... |
Launches a new Telnet client session on the server taken from the `self.options` dict.
This session always fails.
:param my_ip: IP of this Client itself
def start(self):
"""
Launches a new Telnet client session on the server taken from the `self.options` dict.
This ... |
Creates a new session.
:param server_host: IP address of the server
:param server_port: Server port
:return: A new `BaitSession` object.
def create_session(self, server_host, server_port, honeypot_id):
"""
Creates a new session.
:param server_host: IP address of th... |
Launches a new FTP client session on the server taken from the `self.options` dict.
:param my_ip: IP of this Client itself
def start(self):
"""
Launches a new FTP client session on the server taken from the `self.options` dict.
:param my_ip: IP of this Client itself
"""
... |
Launches a few "sensing" commands such as 'ls', or 'pwd'
and updates the current bait state.
def sense(self):
"""
Launches a few "sensing" commands such as 'ls', or 'pwd'
and updates the current bait state.
"""
cmd_name = random.choice(self.senses)
co... |
Decides the next command to be launched based on the current state.
:return: Tuple containing the next command name, and it's parameters.
def decide(self):
"""
Decides the next command to be launched based on the current state.
:return: Tuple containing the next command name, and ... |
Run the command with the parameters.
:param cmd_name: The name of command to run
:param param: Params for the command
def act(self, cmd_name, param):
"""
Run the command with the parameters.
:param cmd_name: The name of command to run
:param param: Params for the c... |
Run the FTP LIST command, and update the state.
def list(self):
"""
Run the FTP LIST command, and update the state.
"""
logger.debug('Sending FTP list command.')
self.state['file_list'] = []
self.state['dir_list'] = []
self.client.retrlines('LIST', self._proc... |
Run the FTP RETR command, and download the file
:param filename: Name of the file to download
def retrieve(self, filename):
"""
Run the FTP RETR command, and download the file
:param filename: Name of the file to download
"""
logger.debug('Sending FTP retr command.... |
Send the FTP CWD command
:param newdir: Directory to change to
def cwd(self, newdir):
"""
Send the FTP CWD command
:param newdir: Directory to change to
"""
logger.debug('Sending FTP cwd command. New Workding Directory: {}'.format(newdir))
self.client.cwd(n... |
Processes a line of 'ls -l' output, and updates state accordingly.
:param list_line: Line to process
def _process_list(self, list_line):
# -rw-r--r-- 1 ftp ftp 68 May 09 19:37 testftp.txt
"""
Processes a line of 'ls -l' output, and updates state accordingly.
:param list_l... |
Makes sure the form data is in 'hh:mm - hh:mm' format and the start time is less than end time.
def validate_time_range(form, field):
""" Makes sure the form data is in 'hh:mm - hh:mm' format and the start time is less than end time."""
string = field.data
try:
begin, end = string.split('-')
... |
Starts sending client bait to the configured Honeypot.
def start(self):
"""
Starts sending client bait to the configured Honeypot.
"""
logger.info('Starting client.')
self.dispatcher_greenlets = []
for _, entry in self.config['baits'].items():
for b in ... |
Launches a new POP3 client session on the server taken from the `self.options` dict.
:param my_ip: IP of this Client itself
def start(self):
"""
Launches a new POP3 client session on the server taken from the `self.options` dict.
:param my_ip: IP of this Client itself
"""
... |
Tries to match a session with it's counterpart. For bait session it will try to match it with honeypot sessions
and the other way around.
:param session: session object which will be used as base for query.
:param timediff: +/- allowed time difference between a session and a potential matching ... |
Will classify all unclassified sessions as malicious activity.
:param delay_seconds: no sessions newer than (now - delay_seconds) will be processed.
def _classify_malicious_sessions(self):
"""
Will classify all unclassified sessions as malicious activity.
:param delay_seconds: no sess... |
Launches a new SSH client session on the server taken from the `self.options` dict.
:param my_ip: IP of this Client itself
def start(self):
"""
Launches a new SSH client session on the server taken from the `self.options` dict.
:param my_ip: IP of this Client itself
"""
... |
Send a command to the remote SSH server.
:param cmd: The command to send
def send_command(self, cmd):
"""
Send a command to the remote SSH server.
:param cmd: The command to send
"""
logger.debug('Sending {0} command.'.format(cmd))
self.comm_chan.sendall(cm... |
Get the response from the server. *This may not return the full response*
:return: Response data
def get_response(self):
"""
Get the response from the server. *This may not return the full response*
:return: Response data
"""
while not self.comm_chan.recv_ready():
... |
Try to login to the Remote SSH Server.
:return: Response text on successful login
:raise: `AuthenticationFailed` on unsuccessful login
def connect_login(self):
"""
Try to login to the Remote SSH Server.
:return: Response text on successful login
:raise: `Authentica... |
Transforms a list of 2 element tuples to a dictionary
def list2dict(list_of_options):
"""Transforms a list of 2 element tuples to a dictionary"""
d = {}
for key, value in list_of_options:
d[key] = value
return d |
Converts an absolute path to an entry resembling the output of
the ls command on most UNIX systems.
def path_to_ls(fn):
""" Converts an absolute path to an entry resembling the output of
the ls command on most UNIX systems."""
st = os.stat(fn)
full_mode = 'rwxrwxrwx'
mode = ''
file_... |
Starts services.
def start(self):
""" Starts services. """
cert_path = os.path.join(self.work_dir, 'certificates')
public_keys_dir = os.path.join(cert_path, 'public_keys')
private_keys_dir = os.path.join(cert_path, 'private_keys')
client_secret_file = os.path.join(private_keys_... |
Restarts the drone
def _start_drone(self):
"""
Restarts the drone
"""
with open(self.config_file, 'r') as config_file:
self.config = json.load(config_file, object_hook=asciify)
mode = None
if self.config['general']['mode'] == '' or self.config['general']['m... |
Stops services
def stop(self):
"""Stops services"""
logging.debug('Stopping drone, hang on.')
if self.drone is not None:
self.drone_greenlet.unlink(self.on_exception)
self.drone.stop()
self.drone_greenlet.kill()
self.drone = None
# just so... |
Launches a new SMTP client session on the server taken from the `self.options` dict.
:param my_ip: IP of this Client itself
def start(self):
"""
Launches a new SMTP client session on the server taken from the `self.options` dict.
:param my_ip: IP of this Client itself
"""
... |
Choose and return a random email from the mail archive.
:return: Tuple containing From Address, To Address and the mail body.
def get_one_mail(self):
"""
Choose and return a random email from the mail archive.
:return: Tuple containing From Address, To Address and the mail body.
... |
Connect to the SMTP server.
def connect(self):
"""
Connect to the SMTP server.
"""
# TODO: local_hostname should be configurable
self.client = smtplib.SMTP(self.options['server'], self.options['port'],
local_hostname='local.domain', timeout... |
The actual service to which the user has connected.
def handle(self):
"The actual service to which the user has connected."
if not self.authentication_ok():
return
if self.DOECHO:
self.writeline(self.WELCOME)
self.session_start()
while self.RUNSHELL:
... |
Ascii-fies list values
def _asciify_list(data):
""" Ascii-fies list values """
ret = []
for item in data:
if isinstance(item, unicode):
item = _remove_accents(item)
item = item.encode('utf-8')
elif isinstance(item, list):
item = _asciify_list(item)
... |
Ascii-fies dict keys and values
def _asciify_dict(data):
""" Ascii-fies dict keys and values """
ret = {}
for key, value in data.iteritems():
if isinstance(key, unicode):
key = _remove_accents(key)
key = key.encode('utf-8')
# # note new if
if isinstance(v... |
Emulates human typing speed
def write_human(self, buffer_):
""" Emulates human typing speed """
if self.IAC in buffer_:
buffer_ = buffer_.replace(self.IAC, self.IAC + self.IAC)
self.msg("send %r", buffer_)
for char in buffer_:
delta = random.gauss(80, 20)
... |
Launches a new Telnet client session on the server taken from the `self.options` dict.
:param my_ip: IP of this Client itself
def start(self):
"""
Launches a new Telnet client session on the server taken from the `self.options` dict.
:param my_ip: IP of this Client itself
... |
Open a new telnet session on the remote server.
def connect(self):
"""
Open a new telnet session on the remote server.
"""
self.client = BaitTelnetClient(self.options['server'], self.options['port'])
self.client.set_option_negotiation_callback(self.process_options) |
Login to the remote telnet server.
:param login: Username to use for logging in
:param password: Password to use for logging in
:raise: `InvalidLogin` on failed login
def login(self, login, password):
"""
Login to the remote telnet server.
:param login: Username to... |
Logout from the remote server.
def logout(self):
"""
Logout from the remote server.
"""
self.client.write('exit\r\n')
self.client.read_all()
self.client.close() |
:param username:
:param password:
:param auth_type: possible values:
plain: plaintext username/password
:return:
def add_auth_attempt(self, auth_type, successful, **kwargs):
"""
:param username:
:param password:
:param auth_type: p... |
Launch a command in the 'senses' List, and update the current state.
def sense(self):
""" Launch a command in the 'senses' List, and update the current state."""
cmd_name = random.choice(self.senses)
param = ''
if cmd_name == 'ls':
if random.randint(0, 1):
p... |
Choose the next command to execute, and its parameters, based on the current
state.
def decide(self):
""" Choose the next command to execute, and its parameters, based on the current
state.
"""
next_command_name = random.choice(self.COMMAND_MAP[self.state['last_command'... |
Run the specified command with its parameters.
def act(self, cmd_name, params=None):
""" Run the specified command with its parameters."""
command = getattr(self, cmd_name)
if params:
command(params)
else:
command() |
Prepares a JSON payload which will be logged.
Override this method to change JSON log format.
:param message: Log message, e.g., `logger.info(msg='Sign up')`.
:param extra: Dictionary that was passed as `extra` param
`logger.info('Sign up', extra={'referral_code': '52d6ce'})`.
... |
Override it to convert fields of `json_record` to needed types.
Default implementation converts `datetime` to string in ISO8601 format.
def mutate_json_record(self, json_record):
"""Override it to convert fields of `json_record` to needed types.
Default implementation converts `datetime` to s... |
Stop the thread.
def stop(self):
""" Stop the thread. """
self._stop.set()
if self._channel is not None:
self._channel.close() |
Listen to the stream and send events to the client.
def run(self):
""" Listen to the stream and send events to the client. """
channel = self._ssh_client.get_transport().open_session()
self._channel = channel
channel.exec_command("gerrit stream-events")
stdout = channel.makefile... |
Run a command.
:arg str command: The command to run.
:Return: The result as a string.
:Raises: `ValueError` if `command` is not a string.
def run_command(self, command):
""" Run a command.
:arg str command: The command to run.
:Return: The result as a string.
... |
Run a query.
:arg str term: The query term to run.
:Returns: A list of results as :class:`pygerrit.models.Change` objects.
:Raises: `ValueError` if `term` is not a string.
def query(self, term):
""" Run a query.
:arg str term: The query term to run.
:Returns: A list... |
Start streaming events from `gerrit stream-events`.
def start_event_stream(self):
""" Start streaming events from `gerrit stream-events`. """
if not self._stream:
self._stream = GerritStream(self, ssh_client=self._ssh_client)
self._stream.start() |
Stop streaming events from `gerrit stream-events`.
def stop_event_stream(self):
""" Stop streaming events from `gerrit stream-events`."""
if self._stream:
self._stream.stop()
self._stream.join()
self._stream = None
with self._events.mutex:
... |
Get the next event from the queue.
:arg boolean block: Set to True to block if no event is available.
:arg seconds timeout: Timeout to wait if no event is available.
:Returns: The next event as a :class:`pygerrit.events.GerritEvent`
instance, or `None` if:
- `block` is... |
Create event from `data` and add it to the queue.
:arg json data: The JSON data from which to create the event.
:Raises: :class:`pygerrit.error.GerritError` if the queue is full, or
the factory could not create the event.
def put_event(self, data):
""" Create event from `data` and... |
Extract the version from `version_string` using `pattern`.
Return the version as a string, with leading/trailing whitespace
stripped.
def _extract_version(version_string, pattern):
""" Extract the version from `version_string` using `pattern`.
Return the version as a string, with leading/trailing whi... |
Configure the ssh parameters from the config file.
def _configure(self):
""" Configure the ssh parameters from the config file. """
configfile = expanduser("~/.ssh/config")
if not isfile(configfile):
raise GerritError("ssh config file '%s' does not exist" %
... |
Connect to the remote.
def _do_connect(self):
""" Connect to the remote. """
self.load_system_host_keys()
if self.username is None or self.port is None:
self._configure()
try:
self.connect(hostname=self.hostname,
port=self.port,
... |
Connect to the remote if not already connected.
def _connect(self):
""" Connect to the remote if not already connected. """
if not self.connected.is_set():
try:
self.lock.acquire()
# Another thread may have connected while we were
# waiting to... |
Return the version of the remote Gerrit server.
def get_remote_version(self):
""" Return the version of the remote Gerrit server. """
if self.remote_version is None:
result = self.run_gerrit_command("version")
version_string = result.stdout.read()
pattern = re.compil... |
Run the given command.
Make sure we're connected to the remote server, and run `command`.
Return the results as a `GerritSSHCommandResult`.
Raise `ValueError` if `command` is not a string, or `GerritError` if
command execution fails.
def run_gerrit_command(self, command):
"""... |
Decorator to register the event identified by `name`.
Return the decorated class.
Raise GerritError if the event is already registered.
def register(cls, name):
""" Decorator to register the event identified by `name`.
Return the decorated class.
Raise GerritError if the eve... |
Create a new event instance.
Return an instance of the `GerritEvent` subclass after converting
`data` to json.
Raise GerritError if json parsed from `data` does not contain a `type`
key.
def create(cls, data):
""" Create a new event instance.
Return an instance of the... |
Strip off Gerrit's magic prefix and decode a response.
:returns:
Decoded JSON content as a dict, or raw text if content could not be
decoded as JSON.
:raises:
requests.HTTPError if the response contains an HTTP error status code.
def _decode_response(response):
""" Strip off Gerri... |
Send HTTP PUT to the endpoint.
:arg str endpoint: The endpoint to send to.
:returns:
JSON decoded result.
:raises:
requests.RequestException on timeout or connection error.
def put(self, endpoint, **kwargs):
""" Send HTTP PUT to the endpoint.
:arg str... |
Send HTTP DELETE to the endpoint.
:arg str endpoint: The endpoint to send to.
:returns:
JSON decoded result.
:raises:
requests.RequestException on timeout or connection error.
def delete(self, endpoint, **kwargs):
""" Send HTTP DELETE to the endpoint.
... |
Submit a review.
:arg str change_id: The change ID.
:arg str revision: The revision.
:arg str review: The review details as a :class:`GerritReview`.
:returns:
JSON decoded result.
:raises:
requests.RequestException on timeout or connection error.
def r... |
Add inline comments.
:arg dict comments: Comments to add.
Usage::
add_comments([{'filename': 'Makefile',
'line': 10,
'message': 'inline message'}])
add_comments([{'filename': 'Makefile',
'range':... |
override asyncio.Protocol
def connection_made(self, transport):
'''
override asyncio.Protocol
'''
self._connected = True
self.transport = transport
self.remote_ip, self.port = transport.get_extra_info('peername')[:2]
logging.debug(
'Connection made... |
override asyncio.Protocol
def connection_lost(self, exc):
'''
override asyncio.Protocol
'''
self._connected = False
logging.debug(
'Connection lost (address: {} port: {})'
.format(self.remote_ip, self.port))
for pid, (future, task) in self._requ... |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.