INSTRUCTION stringlengths 1 8.43k | RESPONSE stringlengths 75 104k |
|---|---|
Accept a SSPI context ( server mode ). | def ssh_accept_sec_context(self, hostname, username, recv_token):
"""
Accept a SSPI context (server mode).
:param str hostname: The servers FQDN
:param str username: The name of the user who attempts to login
:param str recv_token: The SSPI Token received from the server,
... |
Verify the MIC token for a SSH2 message. | def ssh_check_mic(self, mic_token, session_id, username=None):
"""
Verify the MIC token for a SSH2 message.
:param str mic_token: The MIC token received from the client
:param str session_id: The SSH session ID
:param str username: The name of the user who attempts to login
... |
Checks if credentials are delegated ( server mode ). | def credentials_delegated(self):
"""
Checks if credentials are delegated (server mode).
:return: ``True`` if credentials are delegated, otherwise ``False``
"""
return self._gss_flags & sspicon.ISC_REQ_DELEGATE and (
self._gss_srv_ctxt_status or self._gss_flags
... |
Create an SFTP client channel from an open. Transport. | def from_transport(cls, t, window_size=None, max_packet_size=None):
"""
Create an SFTP client channel from an open `.Transport`.
Setting the window and packet sizes might affect the transfer speed.
The default settings in the `.Transport` class are the same as in
OpenSSH and sho... |
Generator version of. listdir_attr. | def listdir_iter(self, path=".", read_aheads=50):
"""
Generator version of `.listdir_attr`.
See the API docs for `.listdir_attr` for overall details.
This function adds one more kwarg on top of `.listdir_attr`:
``read_aheads``, an integer controlling how many
``SSH_FXP_... |
Rename a file or folder from oldpath to newpath. | def rename(self, oldpath, newpath):
"""
Rename a file or folder from ``oldpath`` to ``newpath``.
.. note::
This method implements 'standard' SFTP ``RENAME`` behavior; those
seeking the OpenSSH "POSIX rename" extension behavior should use
`posix_rename`.
... |
Rename a file or folder from oldpath to newpath following posix conventions. | def posix_rename(self, oldpath, newpath):
"""
Rename a file or folder from ``oldpath`` to ``newpath``, following
posix conventions.
:param str oldpath: existing name of the file or folder
:param str newpath: new name for the file or folder, will be
overwritten if it ... |
Create a folder ( directory ) named path with numeric mode mode. The default mode is 0777 ( octal ). On some systems mode is ignored. Where it is used the current umask value is first masked out. | def mkdir(self, path, mode=o777):
"""
Create a folder (directory) named ``path`` with numeric mode ``mode``.
The default mode is 0777 (octal). On some systems, mode is ignored.
Where it is used, the current umask value is first masked out.
:param str path: name of the folder to... |
Create a symbolic link to the source path at destination. | def symlink(self, source, dest):
"""
Create a symbolic link to the ``source`` path at ``destination``.
:param str source: path of the original file
:param str dest: path of the newly created symlink
"""
dest = self._adjust_cwd(dest)
self._log(DEBUG, "symlink({!r}... |
Change the owner ( uid ) and group ( gid ) of a file. As with Python s os. chown function you must pass both arguments so if you only want to change one use stat first to retrieve the current owner and group. | def chown(self, path, uid, gid):
"""
Change the owner (``uid``) and group (``gid``) of a file. As with
Python's `os.chown` function, you must pass both arguments, so if you
only want to change one, use `stat` first to retrieve the current
owner and group.
:param str pat... |
Set the access and modified times of the file specified by path. If times is None then the file s access and modified times are set to the current time. Otherwise times must be a 2 - tuple of numbers of the form ( atime mtime ) which is used to set the access and modified times respectively. This bizarre API is mimicke... | def utime(self, path, times):
"""
Set the access and modified times of the file specified by ``path``.
If ``times`` is ``None``, then the file's access and modified times
are set to the current time. Otherwise, ``times`` must be a 2-tuple
of numbers, of the form ``(atime, mtime)... |
Change the size of the file specified by path. This usually extends or shrinks the size of the file just like the ~file. truncate method on Python file objects. | def truncate(self, path, size):
"""
Change the size of the file specified by ``path``. This usually
extends or shrinks the size of the file, just like the `~file.truncate`
method on Python file objects.
:param str path: path of the file to modify
:param int size: the ne... |
Copy the contents of an open file object ( fl ) to the SFTP server as remotepath. Any exception raised by operations will be passed through. | def putfo(self, fl, remotepath, file_size=0, callback=None, confirm=True):
"""
Copy the contents of an open file object (``fl``) to the SFTP server as
``remotepath``. Any exception raised by operations will be passed
through.
The SFTP operations use pipelining for speed.
... |
Copy a local file ( localpath ) to the SFTP server as remotepath. Any exception raised by operations will be passed through. This method is primarily provided as a convenience. | def put(self, localpath, remotepath, callback=None, confirm=True):
"""
Copy a local file (``localpath``) to the SFTP server as ``remotepath``.
Any exception raised by operations will be passed through. This
method is primarily provided as a convenience.
The SFTP operations use ... |
Copy a remote file ( remotepath ) from the SFTP server and write to an open file or file - like object fl. Any exception raised by operations will be passed through. This method is primarily provided as a convenience. | def getfo(self, remotepath, fl, callback=None):
"""
Copy a remote file (``remotepath``) from the SFTP server and write to
an open file or file-like object, ``fl``. Any exception raised by
operations will be passed through. This method is primarily provided
as a convenience.
... |
Copy a remote file ( remotepath ) from the SFTP server to the local host as localpath. Any exception raised by operations will be passed through. This method is primarily provided as a convenience. | def get(self, remotepath, localpath, callback=None):
"""
Copy a remote file (``remotepath``) from the SFTP server to the local
host as ``localpath``. Any exception raised by operations will be
passed through. This method is primarily provided as a convenience.
:param str remot... |
Raises EOFError or IOError on error status ; otherwise does nothing. | def _convert_status(self, msg):
"""
Raises EOFError or IOError on error status; otherwise does nothing.
"""
code = msg.get_int()
text = msg.get_text()
if code == SFTP_OK:
return
elif code == SFTP_EOF:
raise EOFError(text)
elif code ... |
Return an adjusted path if we re emulating a current working directory for the server. | def _adjust_cwd(self, path):
"""
Return an adjusted path if we're emulating a "current working
directory" for the server.
"""
path = b(path)
if self._cwd is None:
return path
if len(path) and path[0:1] == b_slash:
# absolute path
... |
Execute all tests ( normal and slow ) with coverage enabled. | def coverage(ctx, opts=""):
"""
Execute all tests (normal and slow) with coverage enabled.
"""
return test(ctx, coverage=True, include_slow=True, opts=opts) |
Execute all tests and then watch for changes re - running. | def guard(ctx, opts=""):
"""
Execute all tests and then watch for changes, re-running.
"""
# TODO if coverage was run via pytest-cov, we could add coverage here too
return test(ctx, include_slow=True, loop_on_fail=True, opts=opts) |
Wraps invocations. packaging. publish to add baked - in docs folder. | def release(ctx, sdist=True, wheel=True, sign=True, dry_run=False, index=None):
"""
Wraps invocations.packaging.publish to add baked-in docs folder.
"""
# Build docs first. Use terribad workaround pending invoke #146
ctx.run("inv docs", pty=True, hide=False)
# Move the built docs into where Epyd... |
Normalize/ canonicalize self. gss_host depending on various factors. | def set_gss_host(self, gss_host, trust_dns=True, gssapi_requested=True):
"""
Normalize/canonicalize ``self.gss_host`` depending on various factors.
:param str gss_host:
The explicitly requested GSS-oriented hostname to connect to (i.e.
what the host's name is in the Kerb... |
Negotiate a new SSH2 session as a client. This is the first step after creating a new. Transport. A separate thread is created for protocol negotiation. | def start_client(self, event=None, timeout=None):
"""
Negotiate a new SSH2 session as a client. This is the first step after
creating a new `.Transport`. A separate thread is created for protocol
negotiation.
If an event is passed in, this method returns immediately. When
... |
( optional ) Load a file of prime moduli for use in doing group - exchange key negotiation in server mode. It s a rather obscure option and can be safely ignored. | def load_server_moduli(filename=None):
"""
(optional)
Load a file of prime moduli for use in doing group-exchange key
negotiation in server mode. It's a rather obscure option and can be
safely ignored.
In server mode, the remote client may request "group-exchange" key
... |
Close this session and any open channels that are tied to it. | def close(self):
"""
Close this session, and any open channels that are tied to it.
"""
if not self.active:
return
self.stop_thread()
for chan in list(self._channels.values()):
chan._unlink()
self.sock.close() |
Request a new channel to the server of type session. This is just an alias for calling open_channel with an argument of session. | def open_session(
self, window_size=None, max_packet_size=None, timeout=None
):
"""
Request a new channel to the server, of type ``"session"``. This is
just an alias for calling `open_channel` with an argument of
``"session"``.
.. note:: Modifying the the window and... |
Request a new channel to the server. Channels <. Channel > are socket - like objects used for the actual transfer of data across the session. You may only request a channel after negotiating encryption ( using connect or start_client ) and authenticating. | def open_channel(
self,
kind,
dest_addr=None,
src_addr=None,
window_size=None,
max_packet_size=None,
timeout=None,
):
"""
Request a new channel to the server. `Channels <.Channel>` are
socket-like objects used for the actual transfer of... |
Ask the server to forward TCP connections from a listening port on the server across this SSH session. | def request_port_forward(self, address, port, handler=None):
"""
Ask the server to forward TCP connections from a listening port on
the server, across this SSH session.
If a handler is given, that handler is called from a different thread
whenever a forwarded connection arrives.... |
Ask the server to cancel a previous port - forwarding request. No more connections to the given address & port will be forwarded across this ssh connection. | def cancel_port_forward(self, address, port):
"""
Ask the server to cancel a previous port-forwarding request. No more
connections to the given address & port will be forwarded across this
ssh connection.
:param str address: the address to stop forwarding
:param int por... |
Send a junk packet across the encrypted link. This is sometimes used to add noise to a connection to confuse would - be attackers. It can also be used as a keep - alive for long lived connections traversing firewalls. | def send_ignore(self, byte_count=None):
"""
Send a junk packet across the encrypted link. This is sometimes used
to add "noise" to a connection to confuse would-be attackers. It can
also be used as a keep-alive for long lived connections traversing
firewalls.
:param in... |
Return the next channel opened by the client over this transport in server mode. If no channel is opened before the given timeout None is returned. | def accept(self, timeout=None):
"""
Return the next channel opened by the client over this transport, in
server mode. If no channel is opened before the given timeout,
``None`` is returned.
:param int timeout:
seconds to wait for a channel, or ``None`` to wait forev... |
Negotiate an SSH2 session and optionally verify the server s host key and authenticate using a password or private key. This is a shortcut for start_client get_remote_server_key and Transport. auth_password or Transport. auth_publickey. Use those methods if you want more control. | def connect(
self,
hostkey=None,
username="",
password=None,
pkey=None,
gss_host=None,
gss_auth=False,
gss_kex=False,
gss_deleg_creds=True,
gss_trust_dns=True,
):
"""
Negotiate an SSH2 session, and optionally verify the ... |
Return any exception that happened during the last server request. This can be used to fetch more specific error information after using calls like start_client. The exception ( if any ) is cleared after this call. | def get_exception(self):
"""
Return any exception that happened during the last server request.
This can be used to fetch more specific error information after using
calls like `start_client`. The exception (if any) is cleared after
this call.
:return:
an ex... |
Set the handler class for a subsystem in server mode. If a request for this subsystem is made on an open ssh channel later this handler will be constructed and called -- see. SubsystemHandler for more detailed documentation. | def set_subsystem_handler(self, name, handler, *larg, **kwarg):
"""
Set the handler class for a subsystem in server mode. If a request
for this subsystem is made on an open ssh channel later, this handler
will be constructed and called -- see `.SubsystemHandler` for more
detaile... |
Authenticate to the server using a password. The username and password are sent over an encrypted link. | def auth_password(self, username, password, event=None, fallback=True):
"""
Authenticate to the server using a password. The username and password
are sent over an encrypted link.
If an ``event`` is passed in, this method will return immediately, and
the event will be triggered... |
Authenticate to the server using a private key. The key is used to sign data from the server so it must include the private part. | def auth_publickey(self, username, key, event=None):
"""
Authenticate to the server using a private key. The key is used to
sign data from the server, so it must include the private part.
If an ``event`` is passed in, this method will return immediately, and
the event will be t... |
Authenticate to the server interactively. A handler is used to answer arbitrary questions from the server. On many servers this is just a dumb wrapper around PAM. | def auth_interactive(self, username, handler, submethods=""):
"""
Authenticate to the server interactively. A handler is used to answer
arbitrary questions from the server. On many servers, this is just a
dumb wrapper around PAM.
This method will block until the authentication... |
Autenticate to the server interactively but dumber. Just print the prompt and/ or instructions to stdout and send back the response. This is good for situations where partial auth is achieved by key and then the user has to enter a 2fac token. | def auth_interactive_dumb(self, username, handler=None, submethods=""):
"""
Autenticate to the server interactively but dumber.
Just print the prompt and / or instructions to stdout and send back
the response. This is good for situations where partial auth is
achieved by key and ... |
Authenticate to the Server using GSS - API/ SSPI. | def auth_gssapi_with_mic(self, username, gss_host, gss_deleg_creds):
"""
Authenticate to the Server using GSS-API / SSPI.
:param str username: The username to authenticate as
:param str gss_host: The target host
:param bool gss_deleg_creds: Delegate credentials or not
:r... |
Set the channel for this transport s logging. The default is paramiko. transport but it can be set to anything you want. ( See the. logging module for more info. ) SSH Channels will log to a sub - channel of the one specified. | def set_log_channel(self, name):
"""
Set the channel for this transport's logging. The default is
``"paramiko.transport"`` but it can be set to anything you want. (See
the `.logging` module for more info.) SSH Channels will log to a
sub-channel of the one specified.
:p... |
you are holding the lock | def _next_channel(self):
"""you are holding the lock"""
chanid = self._channel_counter
while self._channels.get(chanid) is not None:
self._channel_counter = (self._channel_counter + 1) & 0xffffff
chanid = self._channel_counter
self._channel_counter = (self._channe... |
id is A - F for the various keys used by ssh | def _compute_key(self, id, nbytes):
"""id is 'A' - 'F' for the various keys used by ssh"""
m = Message()
m.add_mpint(self.K)
m.add_bytes(self.H)
m.add_byte(b(id))
m.add_bytes(self.session_id)
# Fallback to SHA1 for kex engines that fail to specify a hex
# ... |
Checks message type against current auth state. | def _ensure_authed(self, ptype, message):
"""
Checks message type against current auth state.
If server mode, and auth has not succeeded, and the message is of a
post-auth type (channel open or global request) an appropriate error
response Message is crafted and returned to call... |
switch on newly negotiated encryption parameters for outbound traffic | def _activate_outbound(self):
"""switch on newly negotiated encryption parameters for
outbound traffic"""
m = Message()
m.add_byte(cMSG_NEWKEYS)
self._send_message(m)
block_size = self._cipher_info[self.local_cipher]["block-size"]
if self.server_mode:
... |
Write out any data in the write buffer. This may do nothing if write buffering is not turned on. | def flush(self):
"""
Write out any data in the write buffer. This may do nothing if write
buffering is not turned on.
"""
self._write_all(self._wbuffer.getvalue())
self._wbuffer = BytesIO()
return |
Read up to len ( buff ) bytes into bytearray * buff * and return the number of bytes read. | def readinto(self, buff):
"""
Read up to ``len(buff)`` bytes into ``bytearray`` *buff* and return the
number of bytes read.
:returns:
The number of bytes read.
"""
data = self.read(len(buff))
buff[: len(data)] = data
return len(data) |
Read all remaining lines using readline and return them as a list. If the optional sizehint argument is present instead of reading up to EOF whole lines totalling approximately sizehint bytes ( possibly after rounding up to an internal buffer size ) are read. | def readlines(self, sizehint=None):
"""
Read all remaining lines using `readline` and return them as a list.
If the optional ``sizehint`` argument is present, instead of reading up
to EOF, whole lines totalling approximately sizehint bytes (possibly
after rounding up to an intern... |
Write data to the file. If write buffering is on ( bufsize was specified and non - zero ) some or all of the data may not actually be written yet. ( Use flush or close to force buffered data to be written out. ) | def write(self, data):
"""
Write data to the file. If write buffering is on (``bufsize`` was
specified and non-zero), some or all of the data may not actually be
written yet. (Use `flush` or `close` to force buffered data to be
written out.)
:param data: ``str``/``byte... |
Add a host key entry to the table. Any existing entry for a ( hostname keytype ) pair will be replaced. | def add(self, hostname, keytype, key):
"""
Add a host key entry to the table. Any existing entry for a
``(hostname, keytype)`` pair will be replaced.
:param str hostname: the hostname (or IP) to add
:param str keytype: key type (``"ssh-rsa"`` or ``"ssh-dss"``)
:param .P... |
Read a file of known SSH host keys in the format used by OpenSSH. This type of file unfortunately doesn t exist on Windows but on posix it will usually be stored in os. path. expanduser ( ~/. ssh/ known_hosts ). | def load(self, filename):
"""
Read a file of known SSH host keys, in the format used by OpenSSH.
This type of file unfortunately doesn't exist on Windows, but on
posix, it will usually be stored in
``os.path.expanduser("~/.ssh/known_hosts")``.
If this method is called mu... |
Find a hostkey entry for a given hostname or IP. If no entry is found None is returned. Otherwise a dictionary of keytype to key is returned. The keytype will be either ssh - rsa or ssh - dss. | def lookup(self, hostname):
"""
Find a hostkey entry for a given hostname or IP. If no entry is found,
``None`` is returned. Otherwise a dictionary of keytype to key is
returned. The keytype will be either ``"ssh-rsa"`` or ``"ssh-dss"``.
:param str hostname: the hostname (or ... |
Tests whether hostname string matches given SubDict entry. | def _hostname_matches(self, hostname, entry):
"""
Tests whether ``hostname`` string matches given SubDict ``entry``.
:returns bool:
"""
for h in entry.hostnames:
if (
h == hostname
or h.startswith("|1|")
and not hostnam... |
Parses the given line of text to find the names for the host the type of key and the key data. The line is expected to be in the format used by the OpenSSH known_hosts file. | def from_line(cls, line, lineno=None):
"""
Parses the given line of text to find the names for the host,
the type of key, and the key data. The line is expected to be in the
format used by the OpenSSH known_hosts file.
Lines are expected to not have leading or trailing whitespac... |
Communication with the Pageant process is done through a shared memory - mapped file. | def _query_pageant(msg):
"""
Communication with the Pageant process is done through a shared
memory-mapped file.
"""
hwnd = _get_pageant_window_object()
if not hwnd:
# Raise a failure to connect exception, pageant isn't running anymore!
return None
# create a name for the mm... |
Return the bytes ( as a str ) of this message that haven t already been parsed and returned. | def get_remainder(self):
"""
Return the bytes (as a `str`) of this message that haven't already been
parsed and returned.
"""
position = self.packet.tell()
remainder = self.packet.read()
self.packet.seek(position)
return remainder |
Returns the str bytes of this message that have been parsed and returned. The string passed into a message s constructor can be regenerated by concatenating get_so_far and get_remainder. | def get_so_far(self):
"""
Returns the `str` bytes of this message that have been parsed and
returned. The string passed into a message's constructor can be
regenerated by concatenating ``get_so_far`` and `get_remainder`.
"""
position = self.packet.tell()
self.rewi... |
Return the next n bytes of the message ( as a str ) without decomposing into an int decoded string etc. Just the raw bytes are returned. Returns a string of n zero bytes if there weren t n bytes remaining in the message. | def get_bytes(self, n):
"""
Return the next ``n`` bytes of the message (as a `str`), without
decomposing into an int, decoded string, etc. Just the raw bytes are
returned. Returns a string of ``n`` zero bytes if there weren't ``n``
bytes remaining in the message.
"""
... |
Add a boolean value to the stream. | def add_boolean(self, b):
"""
Add a boolean value to the stream.
:param bool b: boolean value to add
"""
if b:
self.packet.write(one_byte)
else:
self.packet.write(zero_byte)
return self |
Add an integer to the stream. | def add_adaptive_int(self, n):
"""
Add an integer to the stream.
:param int n: integer to add
"""
if n >= Message.big_int:
self.packet.write(max_byte)
self.add_string(util.deflate_long(n))
else:
self.packet.write(struct.pack(">I", n))
... |
Add a 64 - bit int to the stream. | def add_int64(self, n):
"""
Add a 64-bit int to the stream.
:param long n: long int to add
"""
self.packet.write(struct.pack(">Q", n))
return self |
returns a random # from 0 to N - 1 | def _roll_random(n):
"""returns a random # from 0 to N-1"""
bits = util.bit_length(n - 1)
byte_count = (bits + 7) // 8
hbyte_mask = pow(2, bits % 8) - 1
# so here's the plan:
# we fetch as many random bits as we'd need to fit N-1, and if the
# generated number is >= N, we try again. in the... |
: raises IOError: passed from any file operations that fail. | def read_file(self, filename):
"""
:raises IOError: passed from any file operations that fail.
"""
self.pack = {}
with open(filename, "r") as f:
for line in f:
line = line.strip()
if (len(line) == 0) or (line[0] == "#"):
... |
Generate a new private ECDSA key. This factory function can be used to generate a new host key or authentication key. | def generate(cls, curve=ec.SECP256R1(), progress_func=None, bits=None):
"""
Generate a new private ECDSA key. This factory function can be used to
generate a new host key or authentication key.
:param progress_func: Not used for this type of key.
:returns: A new private key (`.... |
Create a key object by reading a private key file. If the private key is encrypted and password is not None the given password will be used to decrypt the key ( otherwise. PasswordRequiredException is thrown ). Through the magic of Python this factory method will exist in all subclasses of PKey ( such as. RSAKey or. DS... | def from_private_key_file(cls, filename, password=None):
"""
Create a key object by reading a private key file. If the private
key is encrypted and ``password`` is not ``None``, the given password
will be used to decrypt the key (otherwise `.PasswordRequiredException`
is thrown)... |
Create a key object by reading a private key from a file ( or file - like ) object. If the private key is encrypted and password is not None the given password will be used to decrypt the key ( otherwise. PasswordRequiredException is thrown ). | def from_private_key(cls, file_obj, password=None):
"""
Create a key object by reading a private key from a file (or file-like)
object. If the private key is encrypted and ``password`` is not
``None``, the given password will be used to decrypt the key (otherwise
`.PasswordRequi... |
Write an SSH2 - format private key file in a form that can be read by paramiko or openssh. If no password is given the key is written in a trivially - encoded format ( base64 ) which is completely insecure. If a password is given DES - EDE3 - CBC is used. | def _write_private_key_file(self, filename, key, format, password=None):
"""
Write an SSH2-format private key file in a form that can be read by
paramiko or openssh. If no password is given, the key is written in
a trivially-encoded format (base64) which is completely insecure. If
... |
Perform message type - checking & optional certificate loading. | def _check_type_and_load_cert(self, msg, key_type, cert_type):
"""
Perform message type-checking & optional certificate loading.
This includes fast-forwarding cert ``msg`` objects past the nonce, so
that the subsequent fields are the key numbers; thus the caller may
expect to tr... |
Supplement the private key contents with data loaded from an OpenSSH public key (. pub ) or certificate ( - cert. pub ) file a string containing such a file or a. Message object. | def load_certificate(self, value):
"""
Supplement the private key contents with data loaded from an OpenSSH
public key (``.pub``) or certificate (``-cert.pub``) file, a string
containing such a file, or a `.Message` object.
The .pub contents adds no real value, since the private... |
Create a public blob from a - cert. pub - style file on disk. | def from_file(cls, filename):
"""
Create a public blob from a ``-cert.pub``-style file on disk.
"""
with open(filename) as f:
string = f.read()
return cls.from_string(string) |
Create a public blob from a - cert. pub - style string. | def from_string(cls, string):
"""
Create a public blob from a ``-cert.pub``-style string.
"""
fields = string.split(None, 2)
if len(fields) < 2:
msg = "Not enough fields for public blob: {}"
raise ValueError(msg.format(fields))
key_type = fields[0]... |
Create a public blob from a network. Message. | def from_message(cls, message):
"""
Create a public blob from a network `.Message`.
Specifically, a cert-bearing pubkey auth packet, because by definition
OpenSSH-style certificates 'are' their own network representation."
"""
type_ = message.get_text()
return cl... |
wraps a pipe into two pipe - like objects which are or d together to affect the real pipe. if either returned pipe is set the wrapped pipe is set. when both are cleared the wrapped pipe is cleared. | def make_or_pipe(pipe):
"""
wraps a pipe into two pipe-like objects which are "or"d together to
affect the real pipe. if either returned pipe is set, the wrapped pipe
is set. when both are cleared, the wrapped pipe is cleared.
"""
p1 = OrPipe(pipe)
p2 = OrPipe(pipe)
p1._partner = p2
... |
Return a pair of socket object and string address. | def get_connection(self):
"""
Return a pair of socket object and string address.
May block!
"""
conn = socket.socket(socket.AF_UNIX, socket.SOCK_STREAM)
try:
conn.bind(self._agent._get_filename())
conn.listen(1)
(r, addr) = conn.accept... |
Close the current connection and terminate the agent Should be called manually | def close(self):
"""
Close the current connection and terminate the agent
Should be called manually
"""
if hasattr(self, "thread"):
self.thread._exit = True
self.thread.join(1000)
if self._conn is not None:
self._conn.close() |
Terminate the agent clean the files close connections Should be called manually | def close(self):
"""
Terminate the agent, clean the files, close connections
Should be called manually
"""
os.remove(self._file)
os.rmdir(self._dir)
self.thread._exit = True
self.thread.join(1000)
self._close() |
Switch outbound data cipher. | def set_outbound_cipher(
self,
block_engine,
block_size,
mac_engine,
mac_size,
mac_key,
sdctr=False,
):
"""
Switch outbound data cipher.
"""
self.__block_engine_out = block_engine
self.__sdctr_out = sdctr
self.__... |
Switch inbound data cipher. | def set_inbound_cipher(
self, block_engine, block_size, mac_engine, mac_size, mac_key
):
"""
Switch inbound data cipher.
"""
self.__block_engine_in = block_engine
self.__block_size_in = block_size
self.__mac_engine_in = mac_engine
self.__mac_size_in = ... |
Turn on/ off the callback keepalive. If interval seconds pass with no data read from or written to the socket the callback will be executed and the timer will be reset. | def set_keepalive(self, interval, callback):
"""
Turn on/off the callback keepalive. If ``interval`` seconds pass with
no data read from or written to the socket, the callback will be
executed and the timer will be reset.
"""
self.__keepalive_interval = interval
... |
Tells Packetizer that the handshake process started. Starts a book keeping timer that can signal a timeout in the handshake process. | def start_handshake(self, timeout):
"""
Tells `Packetizer` that the handshake process started.
Starts a book keeping timer that can signal a timeout in the
handshake process.
:param float timeout: amount of seconds to wait before timing out
"""
if not self.__time... |
Checks if the handshake has timed out. | def handshake_timed_out(self):
"""
Checks if the handshake has timed out.
If `start_handshake` wasn't called before the call to this function,
the return value will always be `False`. If the handshake completed
before a timeout was reached, the return value will be `False`
... |
Tells Packetizer that the handshake has completed. | def complete_handshake(self):
"""
Tells `Packetizer` that the handshake has completed.
"""
if self.__timer:
self.__timer.cancel()
self.__timer_expired = False
self.__handshake_complete = True |
When a client closes a file this method is called on the handle. Normally you would use this method to close the underlying OS level file object ( s ). | def close(self):
"""
When a client closes a file, this method is called on the handle.
Normally you would use this method to close the underlying OS level
file object(s).
The default implementation checks for attributes on ``self`` named
``readfile`` and/or ``writefile``... |
Used by the SFTP server code to retrieve a cached directory listing. | def _get_next_files(self):
"""
Used by the SFTP server code to retrieve a cached directory
listing.
"""
fnlist = self.__files[:16]
self.__files = self.__files[16:]
return fnlist |
Given a password passphrase or other human - source key scramble it through a secure hash into some keyworthy bytes. This specific algorithm is used for encrypting/ decrypting private key files. | def generate_key_bytes(hash_alg, salt, key, nbytes):
"""
Given a password, passphrase, or other human-source key, scramble it
through a secure hash into some keyworthy bytes. This specific algorithm
is used for encrypting/decrypting private key files.
:param function hash_alg: A function which cre... |
send paramiko logs to a logfile if they re not already going somewhere | def log_to_file(filename, level=DEBUG):
"""send paramiko logs to a logfile,
if they're not already going somewhere"""
logger = logging.getLogger("paramiko")
if len(logger.handlers) > 0:
return
logger.setLevel(level)
f = open(filename, "a")
handler = logging.StreamHandler(f)
frm =... |
Write the content received from the SSH client to the standard input of the forked command. | def send(self, content):
"""
Write the content received from the SSH client to the standard
input of the forked command.
:param str content: string to be sent to the forked command
"""
try:
self.process.stdin.write(content)
except IOError as e:
... |
Read from the standard output of the forked program. | def recv(self, size):
"""
Read from the standard output of the forked program.
:param int size: how many chars should be read
:return: the string of bytes read, which may be shorter than requested
"""
try:
buffer = b""
start = time.time()
... |
Call FormatMessage with a system error number to retrieve the descriptive error message. | def format_system_message(errno):
"""
Call FormatMessage with a system error number to retrieve
the descriptive error message.
"""
# first some flags used by FormatMessageW
ALLOCATE_BUFFER = 0x100
FROM_SYSTEM = 0x1000
# Let FormatMessageW allocate the buffer (we'll free it below)
# ... |
Given a token get the token information for it. | def GetTokenInformation(token, information_class):
"""
Given a token, get the token information for it.
"""
data_size = ctypes.wintypes.DWORD()
ctypes.windll.advapi32.GetTokenInformation(
token, information_class.num, 0, 0, ctypes.byref(data_size)
)
data = ctypes.create_string_buffer... |
Return a TOKEN_USER for the owner of this process. | def get_current_user():
"""
Return a TOKEN_USER for the owner of this process.
"""
process = OpenProcessToken(
ctypes.windll.kernel32.GetCurrentProcess(), TokenAccess.TOKEN_QUERY
)
return GetTokenInformation(process, TOKEN_USER) |
Generate a new private DSS key. This factory function can be used to generate a new host key or authentication key. | def generate(bits=1024, progress_func=None):
"""
Generate a new private DSS key. This factory function can be used to
generate a new host key or authentication key.
:param int bits: number of bits the generated key should be.
:param progress_func: Unused
:return: new `.... |
Load host keys from a system ( read - only ) file. Host keys read with this method will not be saved back by save_host_keys. | def load_system_host_keys(self, filename=None):
"""
Load host keys from a system (read-only) file. Host keys read with
this method will not be saved back by `save_host_keys`.
This method can be called multiple times. Each new set of host keys
will be merged with the existing s... |
Load host keys from a local host - key file. Host keys read with this method will be checked after keys loaded via load_system_host_keys but will be saved back by save_host_keys ( so they can be modified ). The missing host key policy. AutoAddPolicy adds keys to this set and saves them when connecting to a previously -... | def load_host_keys(self, filename):
"""
Load host keys from a local host-key file. Host keys read with this
method will be checked after keys loaded via `load_system_host_keys`,
but will be saved back by `save_host_keys` (so they can be modified).
The missing host key policy `.A... |
Set policy to use when connecting to servers without a known host key. | def set_missing_host_key_policy(self, policy):
"""
Set policy to use when connecting to servers without a known host key.
Specifically:
* A **policy** is a "policy class" (or instance thereof), namely some
subclass of `.MissingHostKeyPolicy` such as `.RejectPolicy` (the
... |
Yield pairs of address families and addresses to try for connecting. | def _families_and_addresses(self, hostname, port):
"""
Yield pairs of address families and addresses to try for connecting.
:param str hostname: the server to connect to
:param int port: the server port to connect to
:returns: Yields an iterable of ``(family, address)`` tuples
... |
Connect to an SSH server and authenticate to it. The server s host key is checked against the system host keys ( see load_system_host_keys ) and any local host keys ( load_host_keys ). If the server s hostname is not found in either set of host keys the missing host key policy is used ( see set_missing_host_key_policy ... | def connect(
self,
hostname,
port=SSH_PORT,
username=None,
password=None,
pkey=None,
key_filename=None,
timeout=None,
allow_agent=True,
look_for_keys=True,
compress=False,
sock=None,
gss_auth=False,
gss_kex=F... |
Close this SSHClient and its underlying. Transport. | def close(self):
"""
Close this SSHClient and its underlying `.Transport`.
.. warning::
Failure to do this may, in some situations, cause your Python
interpreter to hang at shutdown (often due to race conditions).
It's good practice to `close` your client obj... |
Execute a command on the SSH server. A new. Channel is opened and the requested command is executed. The command s input and output streams are returned as Python file - like objects representing stdin stdout and stderr. | def exec_command(
self,
command,
bufsize=-1,
timeout=None,
get_pty=False,
environment=None,
):
"""
Execute a command on the SSH server. A new `.Channel` is opened and
the requested command is executed. The command's input and output
s... |
Start an interactive shell session on the SSH server. A new. Channel is opened and connected to a pseudo - terminal using the requested terminal type and size. | def invoke_shell(
self,
term="vt100",
width=80,
height=24,
width_pixels=0,
height_pixels=0,
environment=None,
):
"""
Start an interactive shell session on the SSH server. A new `.Channel`
is opened and connected to a pseudo-terminal us... |
Attempt to derive a. PKey from given string path filename: | def _key_from_filepath(self, filename, klass, password):
"""
Attempt to derive a `.PKey` from given string path ``filename``:
- If ``filename`` appears to be a cert, the matching private key is
loaded.
- Otherwise, the filename is assumed to be a private key, and the
... |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.