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 following order: # Exscript checks whether an account was attached to the :class:`Host` object using :class:`Host.set_account()`), and uses that. # If the :class:`Host` has no account attached, Exscript walks through all pools that were passed to :class:`Queue.add_account_pool()`. For each pool, it passes the :class:`Host` to the function in the given match argument. If the return value is True, the account pool is used to acquire an account. (Accounts within each pool are taken in a round-robin fashion.) # If no matching account pool is found, an account is taken from the default account pool. # Finally, if all that fails and the default account pool contains no accounts, an error is raised. Example usage:: def do_nothing(conn): conn.autoinit() def use_this_pool(host): return host.get_name().startswith('foo') default_pool = AccountPool() default_pool.add_account(Account('default-user', 'password')) other_pool = AccountPool() other_pool.add_account(Account('user', 'password')) queue = Queue() queue.account_manager.add_pool(default_pool) queue.account_manager.add_pool(other_pool, use_this_pool) host = Host('localhost') queue.run(host, do_nothing) In the example code, the host has no account attached. As a result, the queue checks whether use_this_pool() returns True. Because the hostname does not start with 'foo', the function returns False, and Exscript takes the 'default-user' account from the default pool. :type pool: AccountPool :param pool: The account pool that is added. :type match: callable :param match: A callback to check if the pool should be used.
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. account.acquire() return account return self.default_pool.acquire_account(account, owner)
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: The account that was acquired.
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=owner)
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 host for which an account is acquired. :type owner: object :param owner: An optional descriptor for the owner. :rtype: :class:`Account` :return: The account that was acquired.
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 the given regular expression. If the given response handler is a function, it is called with the command passed as an argument. :type command: str|regex :param command: A string or a compiled regular expression. :type response: function|str :param response: A reponse, or a response handler.
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 iterable') for key, handler in commands: if handler_decorator: handler = handler_decorator(handler) self.add(key, handler)
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. :type handler_decorator: function :param handler_decorator: A function that is used to decorate each of the handlers in the file.
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 response if self.strict: raise Exception('Undefined command: ' + repr(command)) return None
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, my_arg, **kwargs): print(my_arg, kwargs.get('foo')) run(account, host, bind(my_callback, 'hello', foo = 'world'), max_threads = 10) :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: The callback function. :type kwargs: dict :param kwargs: Passed to the Exscript.Queue constructor.
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: The callback function. :type only_authenticate: bool :param only_authenticate: don't authorize, just authenticate? :type kwargs: dict :param kwargs: Passed to the Exscript.Queue constructor.
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: don't authorize, just authenticate? :type kwargs: dict :param kwargs: Passed to the Exscript.Queue constructor.
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 prefixes is passed, this function returns True only if the given destination is in ANY of the given prefixes. :type prefixes: string :param prefixes: A prefix, or a list of IP prefixes. :type destination: string :param destination: An IP address. :type default_pfxlen: int :param default_pfxlen: The default prefix length. :rtype: True :return: Whether the given destination is in the given network.
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 applying the mask.
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 converting the prefix length.
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: Appended to each hostname that has no domain. :rtype: Host :return: The Host object.
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. :type default_domain: str :param default_domain: Appended to each hostname that has no domain. :rtype: list[Host] :return: A list of Host objects.
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 :return: The Python regex object.
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 into the file. :type mode: string :param mode: Any of the above listed modes.
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 :return: The other IP address of the link address pair.
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 --> [str] dictionary to a str --> str # dictionary since we never use multi-value GET arguments # anyway. multiargs = parse_qs(o.query, keep_blank_values=True) for arg, value in list(multiargs.items()): args[arg] = value[0] return path, args
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 is None: msg = u"You are not allowed to access this page. Please login first!" return _error_401(self, msg) token, fields = auth.split(' ', 1) if token != 'Digest': return _error_401(self, 'Unsupported authentication type') # Check the header fields of the request. cred = parse_http_list(fields) cred = parse_keqv_list(cred) keys = u'realm', u'username', u'nonce', u'uri', u'response' if not all(cred.get(key) for key in keys): return _error_401(self, 'Incomplete authentication header') if cred['realm'] != self.server.realm: return _error_401(self, 'Incorrect realm') if 'qop' in cred and ('nc' not in cred or 'cnonce' not in cred): return _error_401(self, 'qop with missing nc or cnonce') # Check the username. username = cred['username'] password = self.server.get_password(username) if not username or password is None: return _error_401(self, 'Invalid username or password') # Check the digest string. location = u'%s:%s' % (self.command, self.path) location = md5hex(location.encode('utf8')) pwhash = md5hex('%s:%s:%s' % (username, self.server.realm, password)) if 'qop' in cred: info = (cred['nonce'], cred['nc'], cred['cnonce'], cred['qop'], location) else: info = cred['nonce'], location expect = u'%s:%s' % (pwhash, ':'.join(info)) expect = md5hex(expect.encode('utf8')) if expect != cred['response']: return _error_401(self, 'Invalid username or password') # Success! self.authenticated = True return func(self) return wrapped
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. self.data = u"".encode() length = self.headers.get('Content-Length') if length and length.isdigit(): self.data = self.rfile.read(int(length)) # POST data gets automatically decoded into Unicode. The bytestring # will still be available in the bdata attribute. self.bdata = self.data try: self.data = self.data.decode('utf8') except UnicodeDecodeError: self.data = None # Run the handler. try: handler() except: self.send_response(500) self.end_headers() self.wfile.write(format_exc().encode('utf8'))
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 and facility arguments are equivalent to those of Python's built in syslog module. :type source: str :param source: The source address. :type host: str :param host: The IP address or hostname of the receiving server. :type port: str :param port: The TCP port number of the receiving server. :type priority: int :param priority: The message priority. :type facility: int :param facility: The message facility.
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 # track of the position of the last matching byte. buf = str(self) for item in self.monitors: regex_list, callback, bytepos, limit = item bytepos = max(bytepos, len(buf) - limit) for i, regex in enumerate(regex_list): match = regex.search(buf, bytepos) if match is not None: item[2] = match.end() callback(i, match)
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 expressions. :type callback: callable :param callback: The function that is called. :type limit: int :param limit: The maximum size of the tail of the buffer that is searched, in number of bytes.
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.preamble = 'Your mail client is not MIME aware.' body = MIMEText(mail.get_body().encode("utf-8"), "plain", "utf-8") body.add_header('Content-Disposition', 'inline') message.attach(body) for filename in mail.get_attachments(): message.attach(_get_mime_object(filename)) session.sendmail(sender, rcpt, message.as_string())
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 key, value = _get_var_from_header_line(line) if key == 'from': self.set_sender(value) elif key == 'to': self.add_to(value) elif key == 'cc': self.add_cc(value) elif key == 'bcc': self.add_bcc(value) elif key == 'subject': self.set_subject(value) else: raise Exception('Invalid header field "%s"' % key) self.set_body(body.strip())
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 header
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 'One action done (failed)' elif total == succeeded: return '%d actions total (all succeeded)' % total elif succeeded == 0: return '%d actions total (all failed)' % total else: msg = '%d actions total (%d failed, %d succeeded)' return msg % (total, aborted, succeeded)
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() + ':') output.append(log.get_error()) else: output.append(log.get_name() + ': ' + log.get_error(False)) output.append('') # Print successful actions. if show_successful: output += _underline('Successful actions:') for log in logger.get_succeeded_logs(): output.append(log.get_name()) output.append('') return '\n'.join(output).strip()
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 summarizing the status of every performed task.
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.append(item) else: self.queue.appendleft(item) self.condition.notify_all()
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 ValueError: # Channel was closed while attemting to read it pass try: fileno_list.append(sys.stdin.fileno()) except AttributeError: pass except ValueError: # Channel was closed while attemting to read it pass try: fileno_list.append(sys.stderr.fileno()) except AttributeError: pass except ValueError: # Channel was closed while attemting to read it pass # Ask each channel for the terminal window size. for fd in fileno_list: try: rows, cols = _get_terminal_size(fd) except TypeError: # _get_terminal_size() returned None. pass else: return rows, cols # Try os.ctermid() try: fd = os.open(os.ctermid(), os.O_RDONLY) except AttributeError: # os.ctermid does not exist on Windows. pass except OSError: # The device pointed to by os.ctermid() does not exist. pass else: try: rows, cols = _get_terminal_size(fd) except TypeError: # _get_terminal_size() returned None. pass else: return rows, cols finally: os.close(fd) # Try `stty size` with open(os.devnull, 'w') as devnull: try: process = Popen(['stty', 'size'], stderr=devnull, stdout=PIPE, close_fds=True) except (OSError, ValueError): pass else: errcode = process.wait() output = process.stdout.read() try: rows, cols = output.split() return int(rows), int(cols) except (ValueError, TypeError): pass # Try environment variables. try: return tuple(int(os.getenv(var)) for var in ('LINES', 'COLUMNS')) except (ValueError, TypeError): pass # Give up. return default_rows, default_cols
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: What to replace it with. :rtype: string :return: The resulting string, or list of strings.
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(Account(user, password.decode('latin1'))) return accounts
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 contains extra config sections other than "account-pool", they are ignored. Each password needs to be base64 encrypted. To encrypt a password, you may use the following command:: python -c 'import base64; print(base64.b64encode("thepassword"))' :type filename: string :param filename: The name of the file containing the list of accounts. :rtype: list[Account] :return: The newly created account instances.
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() if hostname == '': continue if remove_duplicates and hostname in have: continue have.add(hostname) hosts.append(to_host(hostname, default_protocol, default_domain)) return hosts
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 domain. :type remove_duplicates: bool :param remove_duplicates: Whether duplicates are removed. :type encoding: str :param encoding: The encoding of the file. :rtype: list[Host] :return: The newly created host instances.
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) is None: msg = 'Syntax error in CSV file header:' msg += ' File does not start with "hostname" or "address".' raise Exception(msg) if re.search(r'^(?:hostname|address)(?:\t[^\t]+)*$', header) is None: msg = 'Syntax error in CSV file header:' msg += ' Make sure to separate columns by tabs.' raise Exception(msg) varnames = [str(v) for v in header.split('\t')] varnames.pop(0) # Walk through all lines and create a map that maps hostname to # definitions. last_uri = '' line_re = re.compile(r'[\r\n]*$') hosts = [] for line in file_handle: if line.strip() == '': continue line = line_re.sub('', line) values = line.split('\t') uri = values.pop(0).strip() # Add the hostname to our list. if uri != last_uri: # print "Reading hostname", hostname_url, "from csv." host = to_host(uri, default_protocol, default_domain) last_uri = uri hosts.append(host) # Define variables according to the definition. for i, varname in enumerate(varnames): try: value = values[i] except IndexError: value = '' if varname == 'hostname': host.set_name(value) else: host.append(varname, value) return hosts
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 example, the function returns *two* host objects, where the 'testvar1' variable of the first host holds a list containing two entries ('value1' and 'value2'), and the 'testvar1' variable of the second host contains a list with a single entry ('foo'). Both, the address and the hostname of each host are set to the address given in the first column. If you want the hostname set to another value, you may add a second column containing the hostname:: address hostname testvar 10.0.0.1 myhost value 10.0.0.2 otherhost othervalue :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 domain. :type encoding: str :param encoding: The encoding of the file. :rtype: list[Host] :return: The newly created host instances.
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(name, filename).load_module() return dict((name + '.' + k, v) for (k, v) in list(module.__lib__.items()))
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 extension. The result of this function can later be passed to run_template:: functions = load_lib('my_library.py') run_template(conn, 'foo.exscript', **functions) :type filename: string :param filename: A full filename. :rtype: dict[string->object] :return: The loaded functions.
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 = res try: self.sock = socket.socket(af, socktype, proto) self.sock.settimeout(self.connect_timeout) self.sock.connect(sa) except socket.error as msg_: msg = '{} => telnet://{}:{}'.format(msg_, host, port) if self.sock: self.sock.close() self.sock = None continue break if not self.sock: raise socket.error(msg)
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 follows after the IAC code. command = self.rawq_getchar() if command == theNULL: self.msg('IAC NOP') continue elif command == IAC: self.msg('IAC DATA') buf = buf + command continue # DO: Indicates the request that the other party perform, # or confirmation that you are expecting the other party # to perform, the indicated option. elif command == DO: opt = self.rawq_getchar() self.msg('IAC DO %s', ord(opt)) if opt == TTYPE: self.sock.send(IAC+WILL+opt) elif opt == NAWS: self.sock.send(IAC+WILL+opt) self.can_naws = True if self.window_size: self.set_window_size(*self.window_size) else: self.sock.send(IAC+WONT+opt) # DON'T: Indicates the demand that the other party stop # performing, or confirmation that you are no longer # expecting the other party to perform, the indicated # option. elif command == DONT: opt = self.rawq_getchar() self.msg('IAC DONT %s', ord(opt)) self.sock.send(IAC+WONT+opt) # SB: Indicates that what follows is subnegotiation of the # indicated option. elif command == SB: opt = self.rawq_getchar() self.msg('IAC SUBCOMMAND %d', ord(opt)) # We only handle the TTYPE command, so skip all other # commands. if opt != TTYPE: while self.rawq_getchar() != SE: pass continue # We also only handle the SEND_TTYPE option of TTYPE, # so skip everything else. subopt = self.rawq_getchar() if subopt != SEND_TTYPE: while self.rawq_getchar() != SE: pass continue # Mandatory end of the IAC subcommand. iac = self.rawq_getchar() end = self.rawq_getchar() if (iac, end) != (IAC, SE): # whoops, that's an unexpected response... self.msg( 'expected IAC SE, but got %d %d', ord(iac), ord(end)) self.msg('IAC SUBCOMMAND_END') # Send the next supported terminal. ttype = self.termtype.encode('latin1') self.msg('indicating support for terminal type %s', ttype) self.sock.send(IAC+SB+TTYPE+theNULL+ttype+IAC+SE) elif command in (WILL, WONT): opt = self.rawq_getchar() self.msg('IAC %s %d', command == WILL and 'WILL' or 'WONT', ord(opt)) if opt == ECHO: self.sock.send(IAC+DO+opt) else: self.sock.send(IAC+DONT+opt) else: self.msg('IAC %d not recognized' % ord(command)) except EOFError: # raised by self.rawq_getchar() pass buf = buf.decode(self.encoding) self.cookedq.write(buf) if self.data_callback is not None: self.data_callback(buf, **self.data_callback_kwargs)
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 self.irawq >= len(self.rawq): self.rawq = b'' self.irawq = 0 return c
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 buf) self.rawq = self.rawq + buf
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: print('*** Connection closed by remote host ***') break if text: self.stdout.write(text) self.stdout.flush() if sys.stdin in rfd: line = sys.stdin.readline() if not line: break self.write(line)
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 three items: the index in the list of the first regular expression that matches; the match object returned; and the text read up till and including the match. If EOF is read and no text was read, raise EOFError. Otherwise, when nothing matches, return (-1, None, text) where text is the text received so far (may be the empty string if a timeout happened). If a regular expression ends with a greedy match (e.g. '.*') or if more than one expression can match the same input, the results are undeterministic, and may depend on the I/O timing.
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 raise
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.args if code == errno.ESRCH: # No such process. return False return True
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" (code, text) = xxx_todo_changeme2.args # re-raise if the error wasn't "No such process" if code != errno.ESRCH: raise
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) # write the pid pidfile.write(str(pid)) finally: try: pidfile.close() except: pass
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): self.manual_driver = driver else: raise TypeError('unsupported argument type:' + type(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 chooses a driver using the guess_os() function. :type driver: Driver()|str :param driver: The pattern that, when matched, causes an error.
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. :type prompt: RegEx :param prompt: The pattern that matches the prompt of the remote host.
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(self.get_banner(), False) return conn
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(app_account, flush=flush)
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. The app_account is passed to :class:`app_authenticate()` and :class:`app_authorize()`. If app_account is not given, default to the value of the account argument. :type account: Account :param account: The account for protocol level authentication. :type app_account: Account :param app_account: The account for app level authentication. :type flush: bool :param flush: Whether to flush the last prompt from the buffer.
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 app_account: Account :param app_account: The account for app level authentication. :type flush: bool :param flush: Whether to flush the last prompt from the buffer.
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_authenticate(user, password) else: self._dbg(1, "Authenticate %s with key." % user) self._protocol_authenticate_by_key(user, key) self.proto_authenticated = True
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: An account object, like login().
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 = True
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 protocol-level authentication is that in the latter case, the prompting is handled by the client, whereas app-level authentication is handled by the remote device. App-level authentication comes in a large variety of forms, and while this method tries hard to support them all, there is no guarantee that it will always work. We attempt to smartly recognize the user and password prompts; for a list of supported operating systems please check the Exscript.protocols.drivers module. Returns upon finding the first command line prompt. Depending on whether the flush argument is True, it also removes the prompt from the incoming buffer. :type account: Account :param account: An account object, like login(). :type flush: bool :param flush: Whether to flush the last prompt from the buffer. :type bailout: bool :param bailout: Whether to wait for a prompt after sending the password.
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) self._app_authenticate(account, password, flush, bailout) self.app_authorized = True
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 flush: Whether to flush the last prompt from the buffer. :type bailout: bool :param bailout: Whether to wait for a prompt after sending the password.
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 running Cisco IOS, this command executes the 'enable' command before expecting the password. In the case of a device that is not recognized to support AAA, this method does nothing. :type account: Account :param account: An account object, like login(). :type flush: bool :param flush: Whether to flush the last prompt from the buffer. :type bailout: bool :param bailout: Whether to wait for a prompt after sending the password.
5.892094
7.308377
0.806211