code
string
signature
string
docstring
string
loss_without_docstring
float64
loss_with_docstring
float64
factor
float64
if match is None: self.default_pool = pool else: self.pools.append((match, pool))
def add_pool(self, pool, match=None)
Adds a new account pool. If the given match argument is None, the pool the default pool. Otherwise, the match argument is a callback function that is invoked to decide whether or not the given pool should be used for a host. When Exscript logs into a host, the account is chosen in the f...
3.504566
5.974695
0.586568
for _, pool in self.pools: account = pool.get_account_from_hash(account_hash) if account is not None: return account return self.default_pool.get_account_from_hash(account_hash)
def get_account_from_hash(self, account_hash)
Returns the account with the given hash, if it is contained in any of the pools. Returns None otherwise. :type account_hash: str :param account_hash: The hash of an account object.
2.803578
2.90661
0.964552
if account is not None: for _, pool in self.pools: if pool.has_account(account): return pool.acquire_account(account, owner) if not self.default_pool.has_account(account): # The account is not in any pool. acco...
def acquire_account(self, account=None, owner=None)
Acquires the given account. If no account is given, one is chosen from the default pool. :type account: Account :param account: The account that is added. :type owner: object :param owner: An optional descriptor for the owner. :rtype: :class:`Account` :return:...
3.298731
3.193438
1.032972
# Check whether a matching account pool exists. for match, pool in self.pools: if match(host) is True: return pool.acquire_account(owner=owner) # Else, choose an account from the default account pool. return self.default_pool.acquire_account(owner=ow...
def acquire_account_for(self, host, owner=None)
Acquires an account for the given host and returns it. The host is passed to each of the match functions that were passed in when adding the pool. The first pool for which the match function returns True is chosen to assign an account. :type host: :class:`Host` :param host: The...
4.670753
4.19301
1.113938
for _, pool in self.pools: pool.release_accounts(owner) self.default_pool.release_accounts(owner)
def release_accounts(self, owner)
Releases all accounts that were acquired by the given owner. :type owner: object :param owner: The owner descriptor as passed to acquire_account().
5.003025
7.817483
0.639979
command = re.compile(command) self.response_list.append((command, response))
def add(self, command, response)
Register a command/response pair. The command may be either a string (which is then automatically compiled into a regular expression), or a pre-compiled regular expression object. If the given response handler is a string, it is sent as the response to any command that matches ...
7.041663
10.000828
0.704108
args = {} execfile(filename, args) commands = args.get('commands') if commands is None: raise Exception(filename + ' has no variable named "commands"') elif not hasattr(commands, '__iter__'): raise Exception(filename + ': "commands" is not iterabl...
def add_from_file(self, filename, handler_decorator=None)
Wrapper around add() that reads the handlers from the file with the given name. The file is a Python script containing a list named 'commands' of tuples that map command names to handlers. :type filename: str :param filename: The name of the file containing the tuples. ...
2.758695
3.062031
0.900936
for cmd, response in self.response_list: if not cmd.match(command): continue if response is None: return None elif hasattr(response, '__call__'): return response(command) else: return respons...
def eval(self, command)
Evaluate the given string against all registered commands and return the defined response. :type command: str :param command: The command that is evaluated. :rtype: str or None :return: The response, if one was defined.
3.315658
3.597894
0.921555
attempts = kwargs.get("attempts", 1) if "attempts" in kwargs: del kwargs["attempts"] queue = Queue(**kwargs) queue.add_account(users) queue.run(hosts, func, attempts) queue.destroy()
def run(users, hosts, func, **kwargs)
Convenience function that creates an Exscript.Queue instance, adds the given accounts, and calls Queue.run() with the given hosts and function as an argument. If you also want to pass arguments to the given function, you may use util.decorator.bind() like this:: def my_callback(job, host, conn, ...
4.137049
4.331823
0.955036
if only_authenticate: run(users, hosts, autoauthenticate()(func), **kwargs) else: run(users, hosts, autologin()(func), **kwargs)
def start(users, hosts, func, only_authenticate=False, **kwargs)
Like run(), but automatically logs into the host before passing the host to the callback function. :type users: Account|list[Account] :param users: The account(s) to use for logging in. :type hosts: Host|list[Host] :param hosts: A list of Host objects. :type func: function :param func: T...
5.170555
6.765783
0.764221
if only_authenticate: quickrun(hosts, autoauthenticate()(func), **kwargs) else: quickrun(hosts, autologin()(func), **kwargs)
def quickstart(hosts, func, only_authenticate=False, **kwargs)
Like quickrun(), but automatically logs into the host before passing the connection to the callback function. :type hosts: Host|list[Host] :param hosts: A list of Host objects. :type func: function :param func: The callback function. :type only_authenticate: bool :param only_authenticate...
5.811193
6.804408
0.854034
needle = ipv4.ip2int(destination[0]) for prefix in prefixes: network, pfxlen = ipv4.parse_prefix(prefix, default_pfxlen[0]) mask = ipv4.pfxlen2mask_int(pfxlen) if needle & mask == ipv4.ip2int(network) & mask: return [True] return [False]
def in_network(scope, prefixes, destination, default_pfxlen=[24])
Returns True if the given destination is in the network range that is defined by the given prefix (e.g. 10.0.0.1/22). If the given prefix does not have a prefix length specified, the given default prefix length is applied. If no such prefix length is given, the default length is /24. If a list of p...
3.194155
4.192669
0.761843
mask = ipv4.ip2int(mask[0]) return [ipv4.int2ip(ipv4.ip2int(ip) & mask) for ip in ips]
def mask(scope, ips, mask)
Applies the given IP mask (e.g. 255.255.255.0) to the given IP address (or list of IP addresses) and returns it. :type ips: string :param ips: A prefix, or a list of IP prefixes. :type mask: string :param mask: An IP mask. :rtype: string :return: The network(s) that result(s) from applyi...
4.011837
5.689788
0.705094
mask = ipv4.pfxlen2mask_int(pfxlen[0]) return [ipv4.int2ip(ipv4.ip2int(ip) & mask) for ip in ips]
def pfxmask(scope, ips, pfxlen)
Applies the given prefix length to the given ips, resulting in a (list of) IP network addresses. :type ips: string :param ips: An IP address, or a list of IP addresses. :type pfxlen: int :param pfxlen: An IP prefix length. :rtype: string :return: The mask(s) that result(s) from convertin...
3.914791
6.338681
0.617603
if host is None: raise TypeError('None can not be cast to Host') if hasattr(host, 'get_address'): return host if default_domain and not '.' in host: host += '.' + default_domain return Exscript.Host(host, default_protocol=default_protocol)
def to_host(host, default_protocol='telnet', default_domain='')
Given a string or a Host object, this function returns a Host object. :type host: string|Host :param host: A hostname (may be URL formatted) or a Host object. :type default_protocol: str :param default_protocol: Passed to the Host constructor. :type default_domain: str :param default_domain:...
4.212731
4.62598
0.910668
return [to_host(h, default_protocol, default_domain) for h in to_list(hosts)]
def to_hosts(hosts, default_protocol='telnet', default_domain='')
Given a string or a Host object, or a list of strings or Host objects, this function returns a list of Host objects. :type hosts: string|Host|list(string)|list(Host) :param hosts: One or more hosts or hostnames. :type default_protocol: str :param default_protocol: Passed to the Host constructor. ...
3.456402
5.251795
0.658137
if regex is None: raise TypeError('None can not be cast to re.RegexObject') if hasattr(regex, 'match'): return regex return re.compile(regex, flags)
def to_regex(regex, flags=0)
Given a string, this function returns a new re.RegexObject. Given a re.RegexObject, this function just returns the same object. :type regex: string|re.RegexObject :param regex: A regex or a re.RegexObject :type flags: int :param flags: See Python's re.compile(). :rtype: re.RegexObject :r...
4.331254
4.213425
1.027965
for file in filename: os.chmod(file, mode[0]) return True
def chmod(scope, filename, mode)
Changes the permissions of the given file (or list of files) to the given mode. You probably want to use an octal representation for the integer, e.g. "chmod(myfile, 0644)". :type filename: string :param filename: A filename. :type mode: int :param mode: The access permissions.
5.93217
12.918437
0.459202
for dir in dirname: if mode is None: os.makedirs(dir) else: os.makedirs(dir, mode[0]) return True
def mkdir(scope, dirname, mode=None)
Creates the given directory (or directories). The optional access permissions are set to the given mode, and default to whatever is the umask on your system defined. :type dirname: string :param dirname: A filename, or a list of dirnames. :type mode: int :param mode: The access permissions.
3.767439
5.189794
0.725932
with open(filename[0], 'r') as fp: lines = fp.readlines() scope.define(__response__=lines) return lines
def read(scope, filename)
Reads the given file and returns the result. The result is also stored in the built-in __response__ variable. :type filename: string :param filename: A filename. :rtype: string :return: The content of the file.
9.72544
7.269133
1.337909
with open(filename[0], mode[0]) as fp: fp.writelines(['%s\n' % line.rstrip() for line in lines]) return True
def write(scope, filename, lines, mode=['a'])
Writes the given string into the given file. The following modes are supported: - 'a': Append to the file if it already exists. - 'w': Replace the file if it already exists. :type filename: string :param filename: A filename. :type lines: string :param lines: The data that is written...
3.172708
5.584354
0.568142
mo = re.match(r'(\d+)\.(\d+)\.(\d+)\.(\d+)', string) if mo is None: return False for group in mo.groups(): if int(group) not in list(range(0, 256)): return False return True
def is_ip(string)
Returns True if the given string is an IPv4 address, False otherwise. :type string: string :param string: Any string. :rtype: bool :return: True if the string is an IP address, False otherwise.
2.257463
2.380573
0.948286
theip = ip.split('.') if len(theip) != 4: raise ValueError('ip should be 4 tuples') return '.'.join(str(int(l)).rjust(3, '0') for l in theip)
def normalize_ip(ip)
Transform the address into a fixed-length form, such as:: 192.168.0.1 -> 192.168.000.001 :type ip: string :param ip: An IP address. :rtype: string :return: The normalized IP.
3.938122
4.585564
0.858809
address, pfxlen = parse_prefix(prefix, default_length) ip = ip2int(address) return int2ip(ip & pfxlen2mask_int(pfxlen))
def network(prefix, default_length=24)
Given a prefix, this function returns the corresponding network address. :type prefix: string :param prefix: An IP prefix. :type default_length: long :param default_length: The default ip prefix length. :rtype: string :return: The IP network address.
5.664618
6.362912
0.890256
local_ip = ip2int(local_ip) network = local_ip & pfxlen2mask_int(30) return int2ip(network + 3 - (local_ip - network))
def remote_ip(local_ip)
Given an IP address, this function calculates the remaining available IP address under the assumption that it is a /30 network. In other words, given one link net address, this function returns the other link net address. :type local_ip: string :param local_ip: An IP address. :rtype: string ...
7.401243
8.449827
0.875905
ip_int = ip2int(ip) network, pfxlen = parse_prefix(prefix) network_int = ip2int(network) mask_int = pfxlen2mask_int(pfxlen) return ip_int&mask_int == network_int&mask_int
def matches_prefix(ip, prefix)
Returns True if the given IP address is part of the given network, returns False otherwise. :type ip: string :param ip: An IP address. :type prefix: string :param prefix: An IP prefix. :rtype: bool :return: True if the IP is in the prefix, False otherwise.
3.112282
3.768552
0.825856
if matches_prefix(ip, '10.0.0.0/8'): return True if matches_prefix(ip, '172.16.0.0/12'): return True if matches_prefix(ip, '192.168.0.0/16'): return True return False
def is_private(ip)
Returns True if the given IP address is private, returns False otherwise. :type ip: string :param ip: An IP address. :rtype: bool :return: True if the IP is private, False otherwise.
1.660243
1.992574
0.833215
ips = sorted(normalize_ip(ip) for ip in iterable) return [clean_ip(ip) for ip in ips]
def sort(iterable)
Given an IP address list, this function sorts the list. :type iterable: Iterator :param iterable: An IP address list. :rtype: list :return: The sorted IP address list.
6.677451
7.440352
0.897464
# path changes from bytes to Unicode in going from Python 2 to # Python 3. if sys.version_info[0] < 3: o = urlparse(urllib.parse.unquote_plus(path).decode('utf8')) else: o = urlparse(urllib.parse.unquote_plus(path)) path = o.path args = {} # Convert parse_qs' str --> ...
def _parse_url(path)
Given a urlencoded path, returns the path and the dictionary of query arguments, all in Unicode.
4.886276
4.555001
1.072728
'''A decorator to add digest authorization checks to HTTP Request Handlers''' def wrapped(self): if not hasattr(self, 'authenticated'): self.authenticated = None if self.authenticated: return func(self) auth = self.headers.get(u'Authorization') if auth i...
def _require_authenticate(func)
A decorator to add digest authorization checks to HTTP Request Handlers
2.764701
2.564113
1.078229
# at first, assume that the given path is the actual path and there are # no arguments self.server._dbg(self.path) self.path, self.args = _parse_url(self.path) # Extract POST data, if any. Clumsy syntax due to Python 2 and # 2to3's lack of a byte literal. ...
def _do_POSTGET(self, handler)
handle an HTTP request
4.794393
4.741623
1.011129
self.send_response(404) self.end_headers() self.wfile.write('not found'.encode('utf8'))
def handle_POST(self)
Overwrite this method to handle a POST request. The default action is to respond with "error 404 (not found)".
2.85959
2.329557
1.227525
self.send_response(404) self.end_headers() self.wfile.write('not found'.encode('utf8'))
def handle_GET(self)
Overwrite this method to handle a GET request. The default action is to respond with "error 404 (not found)".
2.710321
2.312133
1.172217
if not source: source = '%s[%s]' + (sys.argv[0], os.getpid()) data = '<%d>%s: %s' % (priority + facility, source, message) sock = socket.socket(socket.AF_INET, socket.SOCK_DGRAM) sock.sendto(data, (host, port)) sock.close()
def netlog(message, source=None, host='localhost', port=514, priority=syslog.LOG_DEBUG, facility=syslog.LOG_USER)
Python's built in syslog module does not support networking, so this is the alternative. The source argument specifies the message source that is documented on the receiving server. It defaults to "scriptname[pid]", where "scriptname" is sys.argv[0], and pid is the current process id. The priority a...
2.843931
2.847846
0.998625
oldpos = self.io.tell() self.io.seek(0) head = self.io.read(bytes) self.io.seek(oldpos) return head
def head(self, bytes)
Returns the number of given bytes from the head of the buffer. The buffer remains unchanged. :type bytes: int :param bytes: The number of bytes to return.
2.441226
3.340202
0.730862
self.io.seek(max(0, self.size() - bytes)) return self.io.read()
def tail(self, bytes)
Returns the number of given bytes from the tail of the buffer. The buffer remains unchanged. :type bytes: int :param bytes: The number of bytes to return.
4.935292
7.131857
0.692007
self.io.seek(0) head = self.io.read(bytes) tail = self.io.read() self.io.seek(0) self.io.write(tail) self.io.truncate() return head
def pop(self, bytes)
Like :class:`head()`, but also removes the head from the buffer. :type bytes: int :param bytes: The number of bytes to return and remove.
2.599759
2.464723
1.054787
self.io.write(data) if not self.monitors: return # Check whether any of the monitoring regular expressions matches. # If it does, we need to disable that monitor until the matching # data is no longer in the buffer. We accomplish this by keeping # tr...
def append(self, data)
Appends the given data to the buffer, and triggers all connected monitors, if any of them match the buffer content. :type data: str :param data: The data that is appended.
5.358761
5.116969
1.047253
self.io.seek(0) self.io.truncate() for item in self.monitors: item[2] = 0
def clear(self)
Removes all data from the buffer.
7.38431
6.087369
1.213054
self.monitors.append([to_regexs(pattern), callback, 0, limit])
def add_monitor(self, pattern, callback, limit=80)
Calls the given function whenever the given pattern matches the buffer. Arguments passed to the callback are the index of the match, and the match object of the regular expression. :type pattern: str|re.RegexObject|list(str|re.RegexObject) :param pattern: One or more regular e...
8.659984
12.115693
0.714774
tmpl = _render_template(string, **kwargs) mail = Mail() mail.set_from_template_string(tmpl) return mail
def from_template_string(string, **kwargs)
Reads the given SMTP formatted template, and creates a new Mail object using the information. :type string: str :param string: The SMTP formatted template. :type kwargs: str :param kwargs: Variables to replace in the template. :rtype: Mail :return: The resulting mail.
6.302457
5.817569
1.083349
with open(filename) as fp: return from_template_string(fp.read(), **kwargs)
def from_template(filename, **kwargs)
Like from_template_string(), but reads the template from the file with the given name instead. :type filename: string :param filename: The name of the template file. :type kwargs: str :param kwargs: Variables to replace in the template. :rtype: Mail :return: The resulting mail.
3.245724
4.385949
0.740028
sender = mail.get_sender() rcpt = mail.get_receipients() session = smtplib.SMTP(server) message = MIMEMultipart() message['Subject'] = mail.get_subject() message['From'] = mail.get_sender() message['To'] = ', '.join(mail.get_to()) message['Cc'] = ', '.join(mail.get_cc()) message...
def send(mail, server='localhost')
Sends the given mail. :type mail: Mail :param mail: The mail object. :type server: string :param server: The address of the mailserver.
2.345629
2.415557
0.971051
in_header = True body = '' for line in string.split('\n'): if not in_header: body += line + '\n' continue if not _is_header_line(line): body += line + '\n' in_header = False continue ...
def set_from_template_string(self, string)
Reads the given template (SMTP formatted) and sets all fields accordingly. :type string: string :param string: The template.
2.059915
2.178072
0.945751
header = "From: %s\r\n" % self.get_sender() header += "To: %s\r\n" % ',\r\n '.join(self.get_to()) header += "Cc: %s\r\n" % ',\r\n '.join(self.get_cc()) header += "Bcc: %s\r\n" % ',\r\n '.join(self.get_bcc()) header += "Subject: %s\r\n" % self.get_subject() return...
def get_smtp_header(self)
Returns the SMTP formatted header of the line. :rtype: string :return: The SMTP header.
1.556733
1.67034
0.931986
header = self.get_smtp_header() body = self.get_body().replace('\n', '\r\n') return header + '\r\n' + body + '\r\n'
def get_smtp_mail(self)
Returns the SMTP formatted email, as it may be passed to sendmail. :rtype: string :return: The SMTP formatted mail.
3.319495
3.354139
0.989671
aborted = logger.get_aborted_actions() succeeded = logger.get_succeeded_actions() total = aborted + succeeded if total == 0: return 'No actions done' elif total == 1 and succeeded == 1: return 'One action done (succeeded)' elif total == 1 and succeeded == 0: return '...
def status(logger)
Creates a one-line summary on the actions that were logged by the given Logger. :type logger: Logger :param logger: The logger that recorded what happened in the queue. :rtype: string :return: A string summarizing the status.
2.486223
2.49803
0.995273
summary = [] for log in logger.get_logs(): thestatus = log.has_error() and log.get_error(False) or 'ok' name = log.get_name() summary.append(name + ': ' + thestatus) return '\n'.join(summary)
def summarize(logger)
Creates a short summary on the actions that were logged by the given Logger. :type logger: Logger :param logger: The logger that recorded what happened in the queue. :rtype: string :return: A string summarizing the status of every performed task.
4.867979
4.743159
1.026316
output = [] # Print failed actions. errors = logger.get_aborted_actions() if show_errors and errors: output += _underline('Failed actions:') for log in logger.get_aborted_logs(): if show_traceback: output.append(log.get_name() + ':') outp...
def format(logger, show_successful=True, show_errors=True, show_traceback=True)
Prints a report of the actions that were logged by the given Logger. The report contains a list of successful actions, as well as the full error message on failed actions. :type logger: Logger :param logger: The logger that recorded what happened in the queue. :rtype: string :return: A string...
2.551377
2.713636
0.940206
if self.parent is None: vars = {} vars.update(self.variables) return vars vars = self.parent.get_vars() vars.update(self.variables) return vars
def get_vars(self)
Returns a complete dict of all variables that are defined in this scope, including the variables of the parent.
2.739554
2.193523
1.248929
vars = self.get_vars() vars = dict([k for k in list(vars.items()) if not k[0].startswith('_')]) return deepcopy(vars)
def copy_public_vars(self)
Like get_vars(), but does not include any private variables and deep copies each variable.
4.773764
4.090448
1.167052
with self.condition: try: item_id = self.name2id[name] except KeyError: return None return self.id2item[item_id] return None
def get_from_name(self, name)
Returns the item with the given name, or None if no such item is known.
3.84563
3.323367
1.157149
with self.condition: self.queue.append(item) uuid = self._register_item(name, item) self.condition.notify_all() return uuid
def append(self, item, name=None)
Adds the given item to the end of the pipeline.
5.062758
4.806871
1.053234
with self.condition: # If the job is already running (or about to be forced), # there is nothing to be done. if item in self.working or item in self.force: return self.queue.remove(item) if force: self.force.app...
def prioritize(self, item, force=False)
Moves the item to the very left of the queue.
4.090987
3.810676
1.073559
with self.condition: self.running = False self.condition.notify_all()
def stop(self)
Force the next() method to return while in another thread. The return value of next() will be None.
4.508269
3.768711
1.196236
with self.condition: try: return self.force[0] except IndexError: pass return self._get_next(False)
def try_next(self)
Like next(), but only returns the item that would be selected right now, without locking and without changing the queue.
9.020929
7.742029
1.165189
# Collect a list of viable input channels that may tell us something # about the terminal dimensions. fileno_list = [] try: fileno_list.append(sys.stdout.fileno()) except AttributeError: # Channel was redirected to an object that has no fileno() pass except ValueErro...
def get_terminal_size(default_rows=25, default_cols=80)
Returns the number of lines and columns of the current terminal. It attempts several strategies to determine the size and if all fail, it returns (80, 25). :rtype: int, int :return: The rows and columns of the terminal.
2.290676
2.273551
1.007532
return [s.replace(source[0], dest[0]) for s in strings]
def replace(scope, strings, source, dest)
Returns a copy of the given string (or list of strings) in which all occurrences of the given source are replaced by the given dest. :type strings: string :param strings: A string, or a list of strings. :type source: string :param source: What to replace. :type dest: string :param dest: ...
4.140067
8.148327
0.508088
accounts = [] cfgparser = __import__('configparser', {}, {}, ['']) parser = cfgparser.RawConfigParser() parser.optionxform = str parser.read(filename) for user, password in parser.items('account-pool'): password = base64.decodebytes(password.encode('latin1')) accounts.append...
def get_accounts_from_file(filename)
Reads a list of user/password combinations from the given file and returns a list of Account instances. The file content has the following format:: [account-pool] user1 = cGFzc3dvcmQ= user2 = cGFzc3dvcmQ= Note that "cGFzc3dvcmQ=" is a base64 encoded password. If the input file ...
3.452381
2.998542
1.151353
# Open the file. if not os.path.exists(filename): raise IOError('No such file: %s' % filename) # Read the hostnames. have = set() hosts = [] with codecs.open(filename, 'r', encoding) as file_handle: for line in file_handle: hostname = line.split('#')[0].strip() ...
def get_hosts_from_file(filename, default_protocol='telnet', default_domain='', remove_duplicates=False, encoding='utf-8')
Reads a list of hostnames from the file with the given name. :type filename: string :param filename: A full filename. :type default_protocol: str :param default_protocol: Passed to the Host constructor. :type default_domain: str :param default_domain: Appended to each hostname that has no do...
2.411034
2.458589
0.980658
# Open the file. if not os.path.exists(filename): raise IOError('No such file: %s' % filename) with codecs.open(filename, 'r', encoding) as file_handle: # Read and check the header. header = file_handle.readline().rstrip() if re.search(r'^(?:hostname|address)\b', header...
def get_hosts_from_csv(filename, default_protocol='telnet', default_domain='', encoding='utf-8')
Reads a list of hostnames and variables from the tab-separated .csv file with the given name. The first line of the file must contain the column names, e.g.:: address testvar1 testvar2 10.0.0.1 value1 othervalue 10.0.0.1 value2 othervalue2 10.0.0.2 foo bar For the above exa...
3.146638
3.125416
1.00679
# Open the file. if not os.path.exists(filename): raise IOError('No such file: %s' % filename) name = os.path.splitext(os.path.basename(filename))[0] if sys.version_info[0] < 3: module = imp.load_source(name, filename) else: module = importlib.machinery.SourceFileLoader...
def load_lib(filename)
Loads a Python file containing functions, and returns the content of the __lib__ variable. The __lib__ variable must contain a dictionary mapping function names to callables. Returns a dictionary mapping the namespaced function names to callables. The namespace is the basename of the file, without file...
2.46114
2.308791
1.065986
logger_id = id(logger) def decorator(function): func = add_label(function, 'log_to', logger_id=logger_id) return func return decorator
def log_to(logger)
Wraps a function that has a connection passed such that everything that happens on the connection is logged using the given logger. :type logger: Logger :param logger: The logger that handles the logging.
5.403401
8.699568
0.621111
logger = FileLogger(logdir, mode, delete, clearmem) _loggers.append(logger) return log_to(logger)
def log_to_file(logdir, mode='a', delete=False, clearmem=True)
Like :class:`log_to()`, but automatically creates a new FileLogger instead of having one passed. Note that the logger stays alive (in memory) forever. If you need to control the lifetime of a logger, use :class:`log_to()` instead.
3.929242
5.188184
0.757344
self.eof = 0 if not port: port = TELNET_PORT self.host = host self.port = port msg = "getaddrinfo returns an empty list" for res in socket.getaddrinfo(host, port, socket.AF_INET, socket.SOCK_STREAM): af, socktype, proto, canonname, sa = re...
def open(self, host, port=0)
Connect to a host. The optional second argument is the port number, which defaults to the standard telnet port (23). Don't try to reopen an already connected instance.
2.272934
2.217043
1.02521
if self.debuglevel > 0: self.stderr.write('Telnet(%s,%d): ' % (self.host, self.port)) if args: self.stderr.write(msg % args) else: self.stderr.write(msg) self.stderr.write('\n')
def msg(self, msg, *args)
Print a debug message, when the debug level is > 0. If extra arguments are present, they are substituted in the message using the standard string formatting operator.
2.48661
2.57711
0.964883
if self.sock: self.sock.close() self.sock = 0 self.eof = 1
def close(self)
Close the connection.
5.090852
3.875942
1.313449
if type(buffer) == type(0): buffer = chr(buffer) elif not isinstance(buffer, bytes): buffer = buffer.encode(self.encoding) if IAC in buffer: buffer = buffer.replace(IAC, IAC+IAC) self.msg("send %s", repr(buffer)) self.sock.send(buffer)
def write(self, buffer)
Write a string to the socket, doubling any IAC characters. Can block if the connection is blocked. May raise socket.error if the connection is closed.
3.364286
3.109731
1.081858
self.process_rawq() while not self.eof: self.fill_rawq() self.process_rawq() buf = self.cookedq.getvalue() self.cookedq.seek(0) self.cookedq.truncate() return buf
def read_all(self)
Read all data until EOF; block until connection closed.
4.566085
3.668421
1.2447
self.process_rawq() while self.cookedq.tell() == 0 and not self.eof: self.fill_rawq() self.process_rawq() buf = self.cookedq.getvalue() self.cookedq.seek(0) self.cookedq.truncate() return buf
def read_some(self)
Read at least one byte of cooked data unless EOF is hit. Return '' if EOF is hit. Block if no data is immediately available.
3.545114
2.978693
1.190158
self.process_rawq() while not self.eof and self.sock_avail(): self.fill_rawq() self.process_rawq() return self.read_very_lazy()
def read_very_eager(self)
Read everything that's possible without blocking in I/O (eager). Raise EOFError if connection closed and no cooked data available. Return '' if no cooked data available otherwise. Don't block unless in the midst of an IAC sequence.
9.288625
6.847378
1.356523
self.process_rawq() while self.cookedq.tell() == 0 and not self.eof and self.sock_avail(): self.fill_rawq() self.process_rawq() return self.read_very_lazy()
def read_eager(self)
Read readily available data. Raise EOFError if connection closed and no cooked data available. Return '' if no cooked data available otherwise. Don't block unless in the midst of an IAC sequence.
9.034896
6.44042
1.402843
buf = self.cookedq.getvalue() self.cookedq.seek(0) self.cookedq.truncate() if not buf and self.eof and not self.rawq: raise EOFError('telnet connection closed') return buf
def read_very_lazy(self)
Return any data available in the cooked queue (very lazy). Raise EOFError if connection closed and no data available. Return '' if no cooked data available otherwise. Don't block.
6.486899
4.815138
1.347189
self.data_callback = callback self.data_callback_kwargs = kwargs
def set_receive_callback(self, callback, *args, **kwargs)
The callback function called after each receipt of any data.
5.528165
4.287278
1.289435
if not self.can_naws: return self.window_size = rows, cols size = struct.pack('!HH', cols, rows) self.sock.send(IAC + SB + NAWS + size + IAC + SE)
def set_window_size(self, rows, cols)
Change the size of the terminal window, if the remote end supports NAWS. If it doesn't, the method returns silently.
5.413356
4.222677
1.281973
buf = b'' try: while self.rawq: # Handle non-IAC first (normal data). char = self.rawq_getchar() if char != IAC: buf = buf + char continue # Interpret the command byte that follo...
def process_rawq(self)
Transfer from raw queue to cooked queue. Set self.eof when connection is closed. Don't block unless in the midst of an IAC sequence.
3.12438
3.07004
1.0177
if not self.rawq: self.fill_rawq() if self.eof: raise EOFError # headaches for Py2/Py3 compatibility... c = self.rawq[self.irawq] if not py2: c = c.to_bytes((c.bit_length()+7)//8, 'big') self.irawq += 1 if sel...
def rawq_getchar(self)
Get next char from raw queue. Block if no data is immediately available. Raise EOFError when connection is closed.
3.504785
3.260756
1.074838
if self.irawq >= len(self.rawq): self.rawq = b'' self.irawq = 0 # The buffer size should be fairly small so as to avoid quadratic # behavior in process_rawq() above. buf = self.sock.recv(64) self.msg("recv %s", repr(buf)) self.eof = (not b...
def fill_rawq(self)
Fill raw queue from exactly one recv() system call. Block if no data is immediately available. Set self.eof when connection is closed.
6.061747
5.345757
1.133936
if sys.platform == "win32": self.mt_interact() return while True: rfd, wfd, xfd = select.select([self, sys.stdin], [], []) if self in rfd: try: text = self.read_eager() except EOFError: ...
def interact(self)
Interaction function, emulates a very dumb telnet client.
2.759815
2.544098
1.084791
import _thread _thread.start_new_thread(self.listener, ()) while 1: line = sys.stdin.readline() if not line: break self.write(line)
def mt_interact(self)
Multithreaded version of interact().
3.854396
3.59123
1.07328
while 1: try: data = self.read_eager() except EOFError: print('*** Connection closed by remote host ***') return if data: self.stdout.write(data) else: self.stdout.flush()
def listener(self)
Helper for mt_interact() -- this executes in the other thread.
4.650297
4.298181
1.081922
return self._waitfor(relist, timeout, False, cleanup)
def waitfor(self, relist, timeout=None, cleanup=None)
Read until one from a list of a regular expressions matches. The first argument is a list of regular expressions, either compiled (re.RegexObject instances) or uncompiled (strings). The optional second argument is a timeout, in seconds; default is no timeout. Return a tuple of ...
5.556136
11.197897
0.496177
return self._waitfor(relist, timeout, True, cleanup=cleanup)
def expect(self, relist, timeout=None, cleanup=None)
Like waitfor(), but removes the matched data from the incoming buffer.
8.626712
6.192121
1.393176
# Try to read the pid from the pidfile. logging.info("Checking pidfile '%s'", path) try: return int(open(path).read()) except IOError as xxx_todo_changeme: (code, text) = xxx_todo_changeme.args if code == errno.ENOENT: # no such file or directory return None ...
def read(path)
Returns the process id from the given file if it exists, or None otherwise. Raises an exception for all other types of OSError while trying to access the file. :type path: str :param path: The name of the pidfile. :rtype: int or None :return: The PID, or none if the file was not found.
4.116034
3.362665
1.224039
# try to read the pid from the pidfile pid = read(path) if pid is None: return False # Check if a process with the given pid exists. try: os.kill(pid, 0) # Signal 0 does not kill, but check. except OSError as xxx_todo_changeme1: (code, text) = xxx_todo_changeme1.ar...
def isalive(path)
Returns True if the file with the given name contains a process id that is still alive. Returns False otherwise. :type path: str :param path: The name of the pidfile. :rtype: bool :return: Whether the process is alive.
3.922728
3.475041
1.128829
# try to read the pid from the pidfile pid = read(path) if pid is None: return # Try to kill the process. logging.info("Killing PID %s", pid) try: os.kill(pid, 9) except OSError as xxx_todo_changeme2: # re-raise if the error wasn't "No such process" (cod...
def kill(path)
Kills the process, if it still exists. :type path: str :param path: The name of the pidfile.
3.679441
3.319048
1.108583
pid = os.getpid() logging.info("Writing PID %s to '%s'", pid, path) try: pidfile = open(path, 'wb') # get a non-blocking exclusive lock fcntl.flock(pidfile.fileno(), fcntl.LOCK_EX | fcntl.LOCK_NB) # clear out the file pidfile.seek(0) pidfile.truncate(0) ...
def write(path)
Writes the current process id to the given pidfile. :type path: str :param path: The name of the pidfile.
2.568837
2.614814
0.982416
if driver is None: self.manual_driver = None elif isinstance(driver, str): if driver not in driver_map: raise TypeError('no such driver:' + repr(driver)) self.manual_driver = driver_map[driver] elif isinstance(driver, Driver): ...
def set_driver(self, driver=None)
Defines the driver that is used to recognize prompts and implement behavior depending on the remote system. The driver argument may be an instance of a protocols.drivers.Driver subclass, a known driver name (string), or None. If the driver argument is None, the adapter automatically choo...
2.681616
3.13176
0.856265
if regex is None: self.manual_user_re = regex else: self.manual_user_re = to_regexs(regex)
def set_username_prompt(self, regex=None)
Defines a pattern that is used to monitor the response of the connected host for a username prompt. :type regex: RegEx :param regex: The pattern that, when matched, causes an error.
6.513094
11.258064
0.578527
if regex is None: self.manual_password_re = regex else: self.manual_password_re = to_regexs(regex)
def set_password_prompt(self, regex=None)
Defines a pattern that is used to monitor the response of the connected host for a password prompt. :type regex: RegEx :param regex: The pattern that, when matched, causes an error.
6.080326
10.1901
0.59669
if prompt is None: self.manual_prompt_re = prompt else: self.manual_prompt_re = to_regexs(prompt)
def set_prompt(self, prompt=None)
Defines a pattern that is waited for when calling the expect_prompt() method. If the set_prompt() method is not called, or if it is called with the prompt argument set to None, a default prompt is used that should work with many devices running Unix, IOS, IOS-XR, or Junos and others. ...
7.117182
10.654545
0.667995
if error is None: self.manual_error_re = error else: self.manual_error_re = to_regexs(error)
def set_error_prompt(self, error=None)
Defines a pattern that is used to monitor the response of the connected host. If the pattern matches (any time the expect() or expect_prompt() methods are used), an error is raised. :type error: RegEx :param error: The pattern that, when matched, causes an error.
6.767857
10.800076
0.626649
if error is None: self.manual_login_error_re = error else: self.manual_login_error_re = to_regexs(error)
def set_login_error_prompt(self, error=None)
Defines a pattern that is used to monitor the response of the connected host during the authentication procedure. If the pattern matches an error is raised. :type error: RegEx :param error: The pattern that, when matched, causes an error.
5.946486
8.146847
0.729913
if hostname is not None: self.host = hostname conn = self._connect_hook(self.host, port) self.os_guesser.protocol_info(self.get_remote_version()) self.auto_driver = driver_map[self.guess_os()] if self.get_banner(): self.os_guesser.data_received(se...
def connect(self, hostname=None, port=None)
Opens the connection to the remote host or IP address. :type hostname: string :param hostname: The remote host or IP address. :type port: int :param port: The remote TCP port number.
7.144429
8.058508
0.88657
with self._get_account(account) as account: if app_account is None: app_account = account self.authenticate(account, flush=False) if self.get_driver().supports_auto_authorize(): self.expect_prompt() self.auto_app_authorize(...
def login(self, account=None, app_account=None, flush=True)
Log into the connected host using the best method available. If an account is not given, default to the account that was used during the last call to login(). If a previous call was not made, use the account that was passed to the constructor. If that also fails, raise a TypeError. ...
5.289557
4.977025
1.062795
with self._get_account(account) as account: if app_account is None: app_account = account if not self.proto_authenticated: self.protocol_authenticate(account) self.app_authenticate(app_account, flush=flush)
def authenticate(self, account=None, app_account=None, flush=True)
Like login(), but skips the authorization procedure. .. HINT:: If you are unsure whether to use :class:`authenticate()` or :class:`login()`, stick with :class:`login`. :type account: Account :param account: The account for protocol level authentication. :type ap...
4.331134
4.230326
1.02383
with self._get_account(account) as account: user = account.get_name() password = account.get_password() key = account.get_key() if key is None: self._dbg(1, "Attempting to authenticate %s." % user) self._protocol_authentica...
def protocol_authenticate(self, account=None)
Low-level API to perform protocol-level authentication on protocols that support it. .. HINT:: In most cases, you want to use the login() method instead, as it automatically chooses the best login method for each protocol. :type account: Account :param account: A...
3.412554
3.7802
0.902744
with self._get_account(account) as account: user = account.get_name() password = account.get_password() self._dbg(1, "Attempting to app-authenticate %s." % user) self._app_authenticate(account, password, flush, bailout) self.app_authenticated = Tr...
def app_authenticate(self, account=None, flush=True, bailout=False)
Attempt to perform application-level authentication. Application level authentication is needed on devices where the username and password are requested from the user after the connection was already accepted by the remote device. The difference between app-level authentication and prot...
4.663363
5.294151
0.880852
with self._get_account(account) as account: user = account.get_name() password = account.get_authorization_password() if password is None: password = account.get_password() self._dbg(1, "Attempting to app-authorize %s." % user) ...
def app_authorize(self, account=None, flush=True, bailout=False)
Like app_authenticate(), but uses the authorization password of the account. For the difference between authentication and authorization please google for AAA. :type account: Account :param account: An account object, like login(). :type flush: bool :param flu...
4.388478
4.318517
1.0162
with self._get_account(account) as account: self._dbg(1, 'Calling driver.auto_authorize().') self.get_driver().auto_authorize(self, account, flush, bailout)
def auto_app_authorize(self, account=None, flush=True, bailout=False)
Like authorize(), but instead of just waiting for a user or password prompt, it automatically initiates the authorization procedure by sending a driver-specific command. In the case of devices that understand AAA, that means sending a command to the device. For example, on routers runni...
5.892094
7.308377
0.806211