sentence1
stringlengths
52
3.87M
sentence2
stringlengths
1
47.2k
label
stringclasses
1 value
def send_buffer(self): """Utility function that sends the buffer into the provided socket. The buffer itself will slowly clear out and is modified in place. """ buf = self._send_buf sock = self.connection._sock try: timeout = sock.gettimeout() sock...
Utility function that sends the buffer into the provided socket. The buffer itself will slowly clear out and is modified in place.
entailment
def send_pending_requests(self): """Sends all pending requests into the connection. The default is to only send pending data that fits into the socket without blocking. This returns `True` if all data was sent or `False` if pending data is left over. """ assert_open(self...
Sends all pending requests into the connection. The default is to only send pending data that fits into the socket without blocking. This returns `True` if all data was sent or `False` if pending data is left over.
entailment
def wait_for_responses(self, client): """Waits for all responses to come back and resolves the eventual results. """ assert_open(self) if self.has_pending_requests: raise RuntimeError('Cannot wait for responses if there are ' 'pending r...
Waits for all responses to come back and resolves the eventual results.
entailment
def _get_command_buffer(self, host_id, command_name): """Returns the command buffer for the given command and arguments.""" buf = self._cb_poll.get(host_id) if buf is not None: return buf if self._max_concurrency is not None: while len(self._cb_poll) >= self._max...
Returns the command buffer for the given command and arguments.
entailment
def _release_command_buffer(self, command_buffer): """This is called by the command buffer when it closes.""" if command_buffer.closed: return self._cb_poll.unregister(command_buffer.host_id) self.connection_pool.release(command_buffer.connection) command_buffer.conn...
This is called by the command buffer when it closes.
entailment
def join(self, timeout=None): """Waits for all outstanding responses to come back or the timeout to be hit. """ remaining = timeout while self._cb_poll and (remaining is None or remaining > 0): now = time.time() rv = self._cb_poll.poll(remaining) ...
Waits for all outstanding responses to come back or the timeout to be hit.
entailment
def target(self, hosts): """Temporarily retarget the client for one call. This is useful when having to deal with a subset of hosts for one call. """ if self.__is_retargeted: raise TypeError('Cannot use target more than once.') rv = FanoutClient(hosts, connection_poo...
Temporarily retarget the client for one call. This is useful when having to deal with a subset of hosts for one call.
entailment
def target_key(self, key): """Temporarily retarget the client for one call to route specifically to the one host that the given key routes to. In that case the result on the promise is just the one host's value instead of a dictionary. .. versionadded:: 1.3 """ ...
Temporarily retarget the client for one call to route specifically to the one host that the given key routes to. In that case the result on the promise is just the one host's value instead of a dictionary. .. versionadded:: 1.3
entailment
def get_mapping_client(self, max_concurrency=64, auto_batch=None): """Returns a thread unsafe mapping client. This client works similar to a redis pipeline and returns eventual result objects. It needs to be joined on to work properly. Instead of using this directly you shold use the :...
Returns a thread unsafe mapping client. This client works similar to a redis pipeline and returns eventual result objects. It needs to be joined on to work properly. Instead of using this directly you shold use the :meth:`map` context manager which automatically joins. Returns...
entailment
def get_fanout_client(self, hosts, max_concurrency=64, auto_batch=None): """Returns a thread unsafe fanout client. Returns an instance of :class:`FanoutClient`. """ if auto_batch is None: auto_batch = self.auto_batch return FanoutClient(host...
Returns a thread unsafe fanout client. Returns an instance of :class:`FanoutClient`.
entailment
def map(self, timeout=None, max_concurrency=64, auto_batch=None): """Returns a context manager for a map operation. This runs multiple queries in parallel and then joins in the end to collect all results. In the context manager the client available is a :class:`MappingClient`. ...
Returns a context manager for a map operation. This runs multiple queries in parallel and then joins in the end to collect all results. In the context manager the client available is a :class:`MappingClient`. Example usage:: results = {} with cluster.map() as ...
entailment
def fanout(self, hosts=None, timeout=None, max_concurrency=64, auto_batch=None): """Returns a context manager for a map operation that fans out to manually specified hosts instead of using the routing system. This can for instance be used to empty the database on all hosts. The ...
Returns a context manager for a map operation that fans out to manually specified hosts instead of using the routing system. This can for instance be used to empty the database on all hosts. The context manager returns a :class:`FanoutClient`. Example usage:: with cluster.fanout(...
entailment
def resolved(value): """Creates a promise object resolved with a certain value.""" p = Promise() p._state = 'resolved' p.value = value return p
Creates a promise object resolved with a certain value.
entailment
def rejected(reason): """Creates a promise object rejected with a certain value.""" p = Promise() p._state = 'rejected' p.reason = reason return p
Creates a promise object rejected with a certain value.
entailment
def resolve(self, value): """Resolves the promise with the given value.""" if self is value: raise TypeError('Cannot resolve promise with itself.') if isinstance(value, Promise): value.done(self.resolve, self.reject) return if self._state != 'pending...
Resolves the promise with the given value.
entailment
def reject(self, reason): """Rejects the promise with the given reason.""" if self._state != 'pending': raise RuntimeError('Promise is no longer pending.') self.reason = reason self._state = 'rejected' errbacks = self._errbacks self._errbacks = None f...
Rejects the promise with the given reason.
entailment
def done(self, on_success=None, on_failure=None): """Attaches some callbacks to the promise and returns the promise.""" if on_success is not None: if self._state == 'pending': self._callbacks.append(on_success) elif self._state == 'resolved': on_su...
Attaches some callbacks to the promise and returns the promise.
entailment
def then(self, success=None, failure=None): """A utility method to add success and/or failure callback to the promise which will also return another promise in the process. """ rv = Promise() def on_success(v): try: rv.resolve(success(v)) ...
A utility method to add success and/or failure callback to the promise which will also return another promise in the process.
entailment
def get_key(self, command, args): """Returns the key a command operates on.""" spec = COMMANDS.get(command.upper()) if spec is None: raise UnroutableCommand('The command "%r" is unknown to the ' 'router and cannot be handled as a ' ...
Returns the key a command operates on.
entailment
def get_host_for_command(self, command, args): """Returns the host this command should be executed against.""" return self.get_host_for_key(self.get_key(command, args))
Returns the host this command should be executed against.
entailment
def _rebuild_circle(self): """Updates the hash ring.""" self._hashring = {} self._sorted_keys = [] total_weight = 0 for node in self._nodes: total_weight += self._weights.get(node, 1) for node in self._nodes: weight = self._weights.get(node, 1) ...
Updates the hash ring.
entailment
def _get_node_pos(self, key): """Return node position(integer) for a given key or None.""" if not self._hashring: return k = md5_bytes(key) key = (k[3] << 24) | (k[2] << 16) | (k[1] << 8) | k[0] nodes = self._sorted_keys pos = bisect(nodes, key) if ...
Return node position(integer) for a given key or None.
entailment
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()
Removes node from circle and rebuild it.
entailment
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()
Adds node to circle and rebuild it.
entailment
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]]
Return node for a given key. Else return None.
entailment
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
Error checking proper value returns
entailment
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: degrees = -degrees elif minutes ...
Take in dd string and convert to dms
entailment
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_annotated = True ...
convert dms to dd
entailment
def get_fobj(fname, mode='w+'): """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* parame...
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...
entailment
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, parsed and a Dot class will be returned, representing the graph. """ fd = open(path, 'rb') data = fd.read() fd.close() return graph_from_dot_data(data...
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.
entailment
def graph_from_edges(edge_list, node_prefix='', directed=False): """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...
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.
entailment
def graph_from_adjacency_matrix(matrix, node_prefix='', directed=False): """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. ...
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.
entailment
def graph_from_incidence_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. ...
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.
entailment
def __find_executables(path): """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 """ success = False progs = { "do...
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
entailment
def find_graphviz(): """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...
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. ...
entailment
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() for obj_dict_list in self.obj_dict['nodes'].values(): node_objs.extend([ Node(obj_dict=obj_...
Get the list of Node instances. This method returns the list of Node instances composing the graph.
entailment
def del_edge(self, src_or_list, dst=None, index=None): """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 ...
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...
entailment
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() for obj_dict_list in self.obj_dict['edges'].values(): edge_objs.extend([ Edge(obj_dict=obj_...
Get the list of Edge instances. This method returns the list of Edge instances composing the graph.
entailment
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. """ graph = list() if self.obj_dict.get('strict', None) is not None: if self == self.get_parent_graph() and self.o...
Returns a string representation of the graph in dot language. It will return the graph and all its subelements in string from.
entailment
def write(self, path, prog=None, format='raw'): """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' c...
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...
entailment
def get_crumbs(self): """ Get crumbs for navigation links. Returns: tuple: concatenated list of crumbs using these crumbs and the crumbs of the parent classes through ``__mro__``. """ crumbs = [] for cls in reversed(type(self)....
Get crumbs for navigation links. Returns: tuple: concatenated list of crumbs using these crumbs and the crumbs of the parent classes through ``__mro__``.
entailment
def get(self, request, *args, **kwargs): """ 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: ...
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.
entailment
def realtime(widget, url_name=None, url_regex=None, time_interval=None): """ 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 match...
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...
entailment
def get_realtime_urls(admin_view_func=lambda x: x): """ 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()``. """ ...
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()``.
entailment
def setup_db(connection_string): """ 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. """ global DB_Session, engine new_database = False if connectio...
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.
entailment
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 = self.username # This should block until ...
Start a PTY - intended to run it a (green)thread.
entailment
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']['ntp_pool'] while True: clnt = ntplib.NTPClient() try: ...
Make sure our Honeypot time is consistent, and not too far off from the actual time.
entailment
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]['port'] ...
Starts services.
entailment
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.')
Stops services
entailment
def prepare_environment(work_dir): """ 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...
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.
entailment
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 """ username = self.options['username'] password = self.options['password'] server_host = self.options['server'] ...
Launches a new HTTP client session on the server taken from the `self.options` dict. :param my_ip: IP of this Client itself
entailment
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('utf-8') doc = document_fromstring(html_text) links = [] for e in doc.cssselect('a...
Parses the response text and returns all the links in it. :param response: The Response object.
entailment
def bootstrap(server_workdir, drone_workdir): """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. """ root_logger = logging.ge...
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.
entailment
def database_exists(url): """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://post...
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...
entailment
def message_proxy(self, work_dir): """ 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 """ public_keys_dir = os....
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
entailment
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 = os.path.join(self.work_dir,...
Starts the BeeSwarm server.
entailment
def get_config(self, configfile): """ Loads the configuration from the JSON file, and returns it. :param configfile: Path to the configuration file """ with open(configfile) as config_file: config = json.load(config_file) return config
Loads the configuration from the JSON file, and returns it. :param configfile: Path to the configuration file
entailment
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: return self.start_time <= curr or curr <= self.end_ti...
Return true if current time is in the active range
entailment
def start(self): """ 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 """ password = self.options['password'] server_host = self.options['server'] ...
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
entailment
def create_session(self, server_host, server_port, honeypot_id): """ Creates a new session. :param server_host: IP address of the server :param server_port: Server port :return: A new `BaitSession` object. """ protocol = self.__class__.__name__.lower() ...
Creates a new session. :param server_host: IP address of the server :param server_port: Server port :return: A new `BaitSession` object.
entailment
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 """ username = self.options['username'] password = self.options['password'] server_host = self.options['server'] ...
Launches a new FTP client session on the server taken from the `self.options` dict. :param my_ip: IP of this Client itself
entailment
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) command = getattr(self, cmd_name) self.state['last_command'] = cmd_name command()
Launches a few "sensing" commands such as 'ls', or 'pwd' and updates the current bait state.
entailment
def decide(self): """ Decides the next command to be launched based on the current state. :return: Tuple containing the next command name, and it's parameters. """ next_command_name = random.choice(self.COMMAND_MAP[self.state['last_command']]) param = '' if n...
Decides the next command to be launched based on the current state. :return: Tuple containing the next command name, and it's parameters.
entailment
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 command """ command = getattr(self, cmd_name) if param: command(param) else: comm...
Run the command with the parameters. :param cmd_name: The name of command to run :param param: Params for the command
entailment
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._process_list)
Run the FTP LIST command, and update the state.
entailment
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. Filename: {}'.format(filename)) self.client.retrbinary('RETR {}'.format(filename), self._save_f...
Run the FTP RETR command, and download the file :param filename: Name of the file to download
entailment
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(newdir) self.state['current_dir'] = self.client.pwd()
Send the FTP CWD command :param newdir: Directory to change to
entailment
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_line: Line to process """ res = list_line.split(' ', 8) if res[0].startswith('-'): ...
Processes a line of 'ls -l' output, and updates state accordingly. :param list_line: Line to process
entailment
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('-') begin = begin.strip() end = end.strip() begin_hours, begin_min = begin.split(...
Makes sure the form data is in 'hh:mm - hh:mm' format and the start time is less than end time.
entailment
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 clientbase.ClientBase.__subclasses__(): ...
Starts sending client bait to the configured Honeypot.
entailment
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 """ username = self.options['username'] password = self.options['password'] server_host = self.options['server'] ...
Launches a new POP3 client session on the server taken from the `self.options` dict. :param my_ip: IP of this Client itself
entailment
def get_matching_session(self, session, db_session, timediff=5): """ 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. :pa...
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 ...
entailment
def _classify_malicious_sessions(self): """ Will classify all unclassified sessions as malicious activity. :param delay_seconds: no sessions newer than (now - delay_seconds) will be processed. """ min_datetime = datetime.utcnow() - timedelta(seconds=self.delay_seconds) ...
Will classify all unclassified sessions as malicious activity. :param delay_seconds: no sessions newer than (now - delay_seconds) will be processed.
entailment
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 """ username = self.options['username'] password = self.options['password'] server_host = self.options['server'] ...
Launches a new SSH client session on the server taken from the `self.options` dict. :param my_ip: IP of this Client itself
entailment
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(cmd + '\n')
Send a command to the remote SSH server. :param cmd: The command to send
entailment
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(): time.sleep(0.5) return self.comm_chan.recv(2048)
Get the response from the server. *This may not return the full response* :return: Response data
entailment
def connect_login(self): """ Try to login to the Remote SSH Server. :return: Response text on successful login :raise: `AuthenticationFailed` on unsuccessful login """ self.client.connect(self.options['server'], self.options['port'], self.options['username'], ...
Try to login to the Remote SSH Server. :return: Response text on successful login :raise: `AuthenticationFailed` on unsuccessful login
entailment
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
Transforms a list of 2 element tuples to a dictionary
entailment
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_time = '' d = '' for i in range(9): # Incrementally builds up the 9 character string, using c...
Converts an absolute path to an entry resembling the output of the ls command on most UNIX systems.
entailment
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_dir, "client.key")...
Starts services.
entailment
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']['mode'] is None: ...
Restarts the drone
entailment
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 some time for the ...
Stops services
entailment
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 """ username = self.options['username'] password = self.options['password'] server_host = self.options['server'] ...
Launches a new SMTP client session on the server taken from the `self.options` dict. :param my_ip: IP of this Client itself
entailment
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. """ while True: mail_key = random.choice(self.mailbox.keys()) mail = self.mailbox[mail_key] ...
Choose and return a random email from the mail archive. :return: Tuple containing From Address, To Address and the mail body.
entailment
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=15)
Connect to the SMTP server.
entailment
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: read_line = self.readline(prompt=self.PROMPT)...
The actual service to which the user has connected.
entailment
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) elif isinstance(item, ...
Ascii-fies list values
entailment
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(value, unicode): value...
Ascii-fies dict keys and values
entailment
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) self.sock.sendall(char)...
Emulates human typing speed
entailment
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 """ login = self.options['username'] password = self.options['password'] server_host = self.options['server'] ...
Launches a new Telnet client session on the server taken from the `self.options` dict. :param my_ip: IP of this Client itself
entailment
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)
Open a new telnet session on the remote server.
entailment
def login(self, login, password): """ 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 """ self.client.read_until('Username: ') self....
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
entailment
def logout(self): """ Logout from the remote server. """ self.client.write('exit\r\n') self.client.read_all() self.client.close()
Logout from the remote server.
entailment
def add_auth_attempt(self, auth_type, successful, **kwargs): """ :param username: :param password: :param auth_type: possible values: plain: plaintext username/password :return: """ entry = {'timestamp': datetime.utcnow(), ...
:param username: :param password: :param auth_type: possible values: plain: plaintext username/password :return:
entailment
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): param = '-l' elif cmd_name == 'uname': # Choose opt...
Launch a command in the 'senses' List, and update the current state.
entailment
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']]) param = '' if next_command_name == 'cd': try: par...
Choose the next command to execute, and its parameters, based on the current state.
entailment
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()
Run the specified command with its parameters.
entailment
def json_record(self, message, extra, record): """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...
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'})`. ...
entailment
def mutate_json_record(self, json_record): """Override it to convert fields of `json_record` to needed types. Default implementation converts `datetime` to string in ISO8601 format. """ for attr_name in json_record: attr = json_record[attr_name] if isinstance(at...
Override it to convert fields of `json_record` to needed types. Default implementation converts `datetime` to string in ISO8601 format.
entailment
def stop(self): """ Stop the thread. """ self._stop.set() if self._channel is not None: self._channel.close()
Stop the thread.
entailment