repo stringlengths 7 55 | path stringlengths 4 223 | func_name stringlengths 1 134 | original_string stringlengths 75 104k | language stringclasses 1 value | code stringlengths 75 104k | code_tokens listlengths 19 28.4k | docstring stringlengths 1 46.9k | docstring_tokens listlengths 1 1.97k | sha stringlengths 40 40 | url stringlengths 87 315 | partition stringclasses 1 value |
|---|---|---|---|---|---|---|---|---|---|---|---|
paramiko/paramiko | paramiko/buffered_pipe.py | BufferedPipe.set_event | def set_event(self, event):
"""
Set an event on this buffer. When data is ready to be read (or the
buffer has been closed), the event will be set. When no data is
ready, the event will be cleared.
:param threading.Event event: the event to set/clear
"""
self._lock.acquire()
try:
self._event = event
# Make sure the event starts in `set` state if we appear to already
# be closed; otherwise, if we start in `clear` state & are closed,
# nothing will ever call `.feed` and the event (& OS pipe, if we're
# wrapping one - see `Channel.fileno`) will permanently stay in
# `clear`, causing deadlock if e.g. `select`ed upon.
if self._closed or len(self._buffer) > 0:
event.set()
else:
event.clear()
finally:
self._lock.release() | python | def set_event(self, event):
"""
Set an event on this buffer. When data is ready to be read (or the
buffer has been closed), the event will be set. When no data is
ready, the event will be cleared.
:param threading.Event event: the event to set/clear
"""
self._lock.acquire()
try:
self._event = event
# Make sure the event starts in `set` state if we appear to already
# be closed; otherwise, if we start in `clear` state & are closed,
# nothing will ever call `.feed` and the event (& OS pipe, if we're
# wrapping one - see `Channel.fileno`) will permanently stay in
# `clear`, causing deadlock if e.g. `select`ed upon.
if self._closed or len(self._buffer) > 0:
event.set()
else:
event.clear()
finally:
self._lock.release() | [
"def",
"set_event",
"(",
"self",
",",
"event",
")",
":",
"self",
".",
"_lock",
".",
"acquire",
"(",
")",
"try",
":",
"self",
".",
"_event",
"=",
"event",
"# Make sure the event starts in `set` state if we appear to already",
"# be closed; otherwise, if we start in `clear` state & are closed,",
"# nothing will ever call `.feed` and the event (& OS pipe, if we're",
"# wrapping one - see `Channel.fileno`) will permanently stay in",
"# `clear`, causing deadlock if e.g. `select`ed upon.",
"if",
"self",
".",
"_closed",
"or",
"len",
"(",
"self",
".",
"_buffer",
")",
">",
"0",
":",
"event",
".",
"set",
"(",
")",
"else",
":",
"event",
".",
"clear",
"(",
")",
"finally",
":",
"self",
".",
"_lock",
".",
"release",
"(",
")"
] | Set an event on this buffer. When data is ready to be read (or the
buffer has been closed), the event will be set. When no data is
ready, the event will be cleared.
:param threading.Event event: the event to set/clear | [
"Set",
"an",
"event",
"on",
"this",
"buffer",
".",
"When",
"data",
"is",
"ready",
"to",
"be",
"read",
"(",
"or",
"the",
"buffer",
"has",
"been",
"closed",
")",
"the",
"event",
"will",
"be",
"set",
".",
"When",
"no",
"data",
"is",
"ready",
"the",
"event",
"will",
"be",
"cleared",
"."
] | cf7d49d66f3b1fbc8b0853518a54050182b3b5eb | https://github.com/paramiko/paramiko/blob/cf7d49d66f3b1fbc8b0853518a54050182b3b5eb/paramiko/buffered_pipe.py#L69-L90 | train |
paramiko/paramiko | paramiko/buffered_pipe.py | BufferedPipe.feed | def feed(self, data):
"""
Feed new data into this pipe. This method is assumed to be called
from a separate thread, so synchronization is done.
:param data: the data to add, as a ``str`` or ``bytes``
"""
self._lock.acquire()
try:
if self._event is not None:
self._event.set()
self._buffer_frombytes(b(data))
self._cv.notifyAll()
finally:
self._lock.release() | python | def feed(self, data):
"""
Feed new data into this pipe. This method is assumed to be called
from a separate thread, so synchronization is done.
:param data: the data to add, as a ``str`` or ``bytes``
"""
self._lock.acquire()
try:
if self._event is not None:
self._event.set()
self._buffer_frombytes(b(data))
self._cv.notifyAll()
finally:
self._lock.release() | [
"def",
"feed",
"(",
"self",
",",
"data",
")",
":",
"self",
".",
"_lock",
".",
"acquire",
"(",
")",
"try",
":",
"if",
"self",
".",
"_event",
"is",
"not",
"None",
":",
"self",
".",
"_event",
".",
"set",
"(",
")",
"self",
".",
"_buffer_frombytes",
"(",
"b",
"(",
"data",
")",
")",
"self",
".",
"_cv",
".",
"notifyAll",
"(",
")",
"finally",
":",
"self",
".",
"_lock",
".",
"release",
"(",
")"
] | Feed new data into this pipe. This method is assumed to be called
from a separate thread, so synchronization is done.
:param data: the data to add, as a ``str`` or ``bytes`` | [
"Feed",
"new",
"data",
"into",
"this",
"pipe",
".",
"This",
"method",
"is",
"assumed",
"to",
"be",
"called",
"from",
"a",
"separate",
"thread",
"so",
"synchronization",
"is",
"done",
"."
] | cf7d49d66f3b1fbc8b0853518a54050182b3b5eb | https://github.com/paramiko/paramiko/blob/cf7d49d66f3b1fbc8b0853518a54050182b3b5eb/paramiko/buffered_pipe.py#L92-L106 | train |
paramiko/paramiko | paramiko/buffered_pipe.py | BufferedPipe.read_ready | def read_ready(self):
"""
Returns true if data is buffered and ready to be read from this
feeder. A ``False`` result does not mean that the feeder has closed;
it means you may need to wait before more data arrives.
:return:
``True`` if a `read` call would immediately return at least one
byte; ``False`` otherwise.
"""
self._lock.acquire()
try:
if len(self._buffer) == 0:
return False
return True
finally:
self._lock.release() | python | def read_ready(self):
"""
Returns true if data is buffered and ready to be read from this
feeder. A ``False`` result does not mean that the feeder has closed;
it means you may need to wait before more data arrives.
:return:
``True`` if a `read` call would immediately return at least one
byte; ``False`` otherwise.
"""
self._lock.acquire()
try:
if len(self._buffer) == 0:
return False
return True
finally:
self._lock.release() | [
"def",
"read_ready",
"(",
"self",
")",
":",
"self",
".",
"_lock",
".",
"acquire",
"(",
")",
"try",
":",
"if",
"len",
"(",
"self",
".",
"_buffer",
")",
"==",
"0",
":",
"return",
"False",
"return",
"True",
"finally",
":",
"self",
".",
"_lock",
".",
"release",
"(",
")"
] | Returns true if data is buffered and ready to be read from this
feeder. A ``False`` result does not mean that the feeder has closed;
it means you may need to wait before more data arrives.
:return:
``True`` if a `read` call would immediately return at least one
byte; ``False`` otherwise. | [
"Returns",
"true",
"if",
"data",
"is",
"buffered",
"and",
"ready",
"to",
"be",
"read",
"from",
"this",
"feeder",
".",
"A",
"False",
"result",
"does",
"not",
"mean",
"that",
"the",
"feeder",
"has",
"closed",
";",
"it",
"means",
"you",
"may",
"need",
"to",
"wait",
"before",
"more",
"data",
"arrives",
"."
] | cf7d49d66f3b1fbc8b0853518a54050182b3b5eb | https://github.com/paramiko/paramiko/blob/cf7d49d66f3b1fbc8b0853518a54050182b3b5eb/paramiko/buffered_pipe.py#L108-L124 | train |
paramiko/paramiko | paramiko/buffered_pipe.py | BufferedPipe.read | def read(self, nbytes, timeout=None):
"""
Read data from the pipe. The return value is a string representing
the data received. The maximum amount of data to be received at once
is specified by ``nbytes``. If a string of length zero is returned,
the pipe has been closed.
The optional ``timeout`` argument can be a nonnegative float expressing
seconds, or ``None`` for no timeout. If a float is given, a
`.PipeTimeout` will be raised if the timeout period value has elapsed
before any data arrives.
:param int nbytes: maximum number of bytes to read
:param float timeout:
maximum seconds to wait (or ``None``, the default, to wait forever)
:return: the read data, as a ``str`` or ``bytes``
:raises:
`.PipeTimeout` -- if a timeout was specified and no data was ready
before that timeout
"""
out = bytes()
self._lock.acquire()
try:
if len(self._buffer) == 0:
if self._closed:
return out
# should we block?
if timeout == 0.0:
raise PipeTimeout()
# loop here in case we get woken up but a different thread has
# grabbed everything in the buffer.
while (len(self._buffer) == 0) and not self._closed:
then = time.time()
self._cv.wait(timeout)
if timeout is not None:
timeout -= time.time() - then
if timeout <= 0.0:
raise PipeTimeout()
# something's in the buffer and we have the lock!
if len(self._buffer) <= nbytes:
out = self._buffer_tobytes()
del self._buffer[:]
if (self._event is not None) and not self._closed:
self._event.clear()
else:
out = self._buffer_tobytes(nbytes)
del self._buffer[:nbytes]
finally:
self._lock.release()
return out | python | def read(self, nbytes, timeout=None):
"""
Read data from the pipe. The return value is a string representing
the data received. The maximum amount of data to be received at once
is specified by ``nbytes``. If a string of length zero is returned,
the pipe has been closed.
The optional ``timeout`` argument can be a nonnegative float expressing
seconds, or ``None`` for no timeout. If a float is given, a
`.PipeTimeout` will be raised if the timeout period value has elapsed
before any data arrives.
:param int nbytes: maximum number of bytes to read
:param float timeout:
maximum seconds to wait (or ``None``, the default, to wait forever)
:return: the read data, as a ``str`` or ``bytes``
:raises:
`.PipeTimeout` -- if a timeout was specified and no data was ready
before that timeout
"""
out = bytes()
self._lock.acquire()
try:
if len(self._buffer) == 0:
if self._closed:
return out
# should we block?
if timeout == 0.0:
raise PipeTimeout()
# loop here in case we get woken up but a different thread has
# grabbed everything in the buffer.
while (len(self._buffer) == 0) and not self._closed:
then = time.time()
self._cv.wait(timeout)
if timeout is not None:
timeout -= time.time() - then
if timeout <= 0.0:
raise PipeTimeout()
# something's in the buffer and we have the lock!
if len(self._buffer) <= nbytes:
out = self._buffer_tobytes()
del self._buffer[:]
if (self._event is not None) and not self._closed:
self._event.clear()
else:
out = self._buffer_tobytes(nbytes)
del self._buffer[:nbytes]
finally:
self._lock.release()
return out | [
"def",
"read",
"(",
"self",
",",
"nbytes",
",",
"timeout",
"=",
"None",
")",
":",
"out",
"=",
"bytes",
"(",
")",
"self",
".",
"_lock",
".",
"acquire",
"(",
")",
"try",
":",
"if",
"len",
"(",
"self",
".",
"_buffer",
")",
"==",
"0",
":",
"if",
"self",
".",
"_closed",
":",
"return",
"out",
"# should we block?",
"if",
"timeout",
"==",
"0.0",
":",
"raise",
"PipeTimeout",
"(",
")",
"# loop here in case we get woken up but a different thread has",
"# grabbed everything in the buffer.",
"while",
"(",
"len",
"(",
"self",
".",
"_buffer",
")",
"==",
"0",
")",
"and",
"not",
"self",
".",
"_closed",
":",
"then",
"=",
"time",
".",
"time",
"(",
")",
"self",
".",
"_cv",
".",
"wait",
"(",
"timeout",
")",
"if",
"timeout",
"is",
"not",
"None",
":",
"timeout",
"-=",
"time",
".",
"time",
"(",
")",
"-",
"then",
"if",
"timeout",
"<=",
"0.0",
":",
"raise",
"PipeTimeout",
"(",
")",
"# something's in the buffer and we have the lock!",
"if",
"len",
"(",
"self",
".",
"_buffer",
")",
"<=",
"nbytes",
":",
"out",
"=",
"self",
".",
"_buffer_tobytes",
"(",
")",
"del",
"self",
".",
"_buffer",
"[",
":",
"]",
"if",
"(",
"self",
".",
"_event",
"is",
"not",
"None",
")",
"and",
"not",
"self",
".",
"_closed",
":",
"self",
".",
"_event",
".",
"clear",
"(",
")",
"else",
":",
"out",
"=",
"self",
".",
"_buffer_tobytes",
"(",
"nbytes",
")",
"del",
"self",
".",
"_buffer",
"[",
":",
"nbytes",
"]",
"finally",
":",
"self",
".",
"_lock",
".",
"release",
"(",
")",
"return",
"out"
] | Read data from the pipe. The return value is a string representing
the data received. The maximum amount of data to be received at once
is specified by ``nbytes``. If a string of length zero is returned,
the pipe has been closed.
The optional ``timeout`` argument can be a nonnegative float expressing
seconds, or ``None`` for no timeout. If a float is given, a
`.PipeTimeout` will be raised if the timeout period value has elapsed
before any data arrives.
:param int nbytes: maximum number of bytes to read
:param float timeout:
maximum seconds to wait (or ``None``, the default, to wait forever)
:return: the read data, as a ``str`` or ``bytes``
:raises:
`.PipeTimeout` -- if a timeout was specified and no data was ready
before that timeout | [
"Read",
"data",
"from",
"the",
"pipe",
".",
"The",
"return",
"value",
"is",
"a",
"string",
"representing",
"the",
"data",
"received",
".",
"The",
"maximum",
"amount",
"of",
"data",
"to",
"be",
"received",
"at",
"once",
"is",
"specified",
"by",
"nbytes",
".",
"If",
"a",
"string",
"of",
"length",
"zero",
"is",
"returned",
"the",
"pipe",
"has",
"been",
"closed",
"."
] | cf7d49d66f3b1fbc8b0853518a54050182b3b5eb | https://github.com/paramiko/paramiko/blob/cf7d49d66f3b1fbc8b0853518a54050182b3b5eb/paramiko/buffered_pipe.py#L126-L178 | train |
paramiko/paramiko | paramiko/buffered_pipe.py | BufferedPipe.empty | def empty(self):
"""
Clear out the buffer and return all data that was in it.
:return:
any data that was in the buffer prior to clearing it out, as a
`str`
"""
self._lock.acquire()
try:
out = self._buffer_tobytes()
del self._buffer[:]
if (self._event is not None) and not self._closed:
self._event.clear()
return out
finally:
self._lock.release() | python | def empty(self):
"""
Clear out the buffer and return all data that was in it.
:return:
any data that was in the buffer prior to clearing it out, as a
`str`
"""
self._lock.acquire()
try:
out = self._buffer_tobytes()
del self._buffer[:]
if (self._event is not None) and not self._closed:
self._event.clear()
return out
finally:
self._lock.release() | [
"def",
"empty",
"(",
"self",
")",
":",
"self",
".",
"_lock",
".",
"acquire",
"(",
")",
"try",
":",
"out",
"=",
"self",
".",
"_buffer_tobytes",
"(",
")",
"del",
"self",
".",
"_buffer",
"[",
":",
"]",
"if",
"(",
"self",
".",
"_event",
"is",
"not",
"None",
")",
"and",
"not",
"self",
".",
"_closed",
":",
"self",
".",
"_event",
".",
"clear",
"(",
")",
"return",
"out",
"finally",
":",
"self",
".",
"_lock",
".",
"release",
"(",
")"
] | Clear out the buffer and return all data that was in it.
:return:
any data that was in the buffer prior to clearing it out, as a
`str` | [
"Clear",
"out",
"the",
"buffer",
"and",
"return",
"all",
"data",
"that",
"was",
"in",
"it",
"."
] | cf7d49d66f3b1fbc8b0853518a54050182b3b5eb | https://github.com/paramiko/paramiko/blob/cf7d49d66f3b1fbc8b0853518a54050182b3b5eb/paramiko/buffered_pipe.py#L180-L196 | train |
paramiko/paramiko | paramiko/buffered_pipe.py | BufferedPipe.close | def close(self):
"""
Close this pipe object. Future calls to `read` after the buffer
has been emptied will return immediately with an empty string.
"""
self._lock.acquire()
try:
self._closed = True
self._cv.notifyAll()
if self._event is not None:
self._event.set()
finally:
self._lock.release() | python | def close(self):
"""
Close this pipe object. Future calls to `read` after the buffer
has been emptied will return immediately with an empty string.
"""
self._lock.acquire()
try:
self._closed = True
self._cv.notifyAll()
if self._event is not None:
self._event.set()
finally:
self._lock.release() | [
"def",
"close",
"(",
"self",
")",
":",
"self",
".",
"_lock",
".",
"acquire",
"(",
")",
"try",
":",
"self",
".",
"_closed",
"=",
"True",
"self",
".",
"_cv",
".",
"notifyAll",
"(",
")",
"if",
"self",
".",
"_event",
"is",
"not",
"None",
":",
"self",
".",
"_event",
".",
"set",
"(",
")",
"finally",
":",
"self",
".",
"_lock",
".",
"release",
"(",
")"
] | Close this pipe object. Future calls to `read` after the buffer
has been emptied will return immediately with an empty string. | [
"Close",
"this",
"pipe",
"object",
".",
"Future",
"calls",
"to",
"read",
"after",
"the",
"buffer",
"has",
"been",
"emptied",
"will",
"return",
"immediately",
"with",
"an",
"empty",
"string",
"."
] | cf7d49d66f3b1fbc8b0853518a54050182b3b5eb | https://github.com/paramiko/paramiko/blob/cf7d49d66f3b1fbc8b0853518a54050182b3b5eb/paramiko/buffered_pipe.py#L198-L210 | train |
paramiko/paramiko | paramiko/config.py | SSHConfig.parse | def parse(self, file_obj):
"""
Read an OpenSSH config from the given file object.
:param file_obj: a file-like object to read the config file from
"""
host = {"host": ["*"], "config": {}}
for line in file_obj:
# Strip any leading or trailing whitespace from the line.
# Refer to https://github.com/paramiko/paramiko/issues/499
line = line.strip()
if not line or line.startswith("#"):
continue
match = re.match(self.SETTINGS_REGEX, line)
if not match:
raise Exception("Unparsable line {}".format(line))
key = match.group(1).lower()
value = match.group(2)
if key == "host":
self._config.append(host)
host = {"host": self._get_hosts(value), "config": {}}
elif key == "proxycommand" and value.lower() == "none":
# Store 'none' as None; prior to 3.x, it will get stripped out
# at the end (for compatibility with issue #415). After 3.x, it
# will simply not get stripped, leaving a nice explicit marker.
host["config"][key] = None
else:
if value.startswith('"') and value.endswith('"'):
value = value[1:-1]
# identityfile, localforward, remoteforward keys are special
# cases, since they are allowed to be specified multiple times
# and they should be tried in order of specification.
if key in ["identityfile", "localforward", "remoteforward"]:
if key in host["config"]:
host["config"][key].append(value)
else:
host["config"][key] = [value]
elif key not in host["config"]:
host["config"][key] = value
self._config.append(host) | python | def parse(self, file_obj):
"""
Read an OpenSSH config from the given file object.
:param file_obj: a file-like object to read the config file from
"""
host = {"host": ["*"], "config": {}}
for line in file_obj:
# Strip any leading or trailing whitespace from the line.
# Refer to https://github.com/paramiko/paramiko/issues/499
line = line.strip()
if not line or line.startswith("#"):
continue
match = re.match(self.SETTINGS_REGEX, line)
if not match:
raise Exception("Unparsable line {}".format(line))
key = match.group(1).lower()
value = match.group(2)
if key == "host":
self._config.append(host)
host = {"host": self._get_hosts(value), "config": {}}
elif key == "proxycommand" and value.lower() == "none":
# Store 'none' as None; prior to 3.x, it will get stripped out
# at the end (for compatibility with issue #415). After 3.x, it
# will simply not get stripped, leaving a nice explicit marker.
host["config"][key] = None
else:
if value.startswith('"') and value.endswith('"'):
value = value[1:-1]
# identityfile, localforward, remoteforward keys are special
# cases, since they are allowed to be specified multiple times
# and they should be tried in order of specification.
if key in ["identityfile", "localforward", "remoteforward"]:
if key in host["config"]:
host["config"][key].append(value)
else:
host["config"][key] = [value]
elif key not in host["config"]:
host["config"][key] = value
self._config.append(host) | [
"def",
"parse",
"(",
"self",
",",
"file_obj",
")",
":",
"host",
"=",
"{",
"\"host\"",
":",
"[",
"\"*\"",
"]",
",",
"\"config\"",
":",
"{",
"}",
"}",
"for",
"line",
"in",
"file_obj",
":",
"# Strip any leading or trailing whitespace from the line.",
"# Refer to https://github.com/paramiko/paramiko/issues/499",
"line",
"=",
"line",
".",
"strip",
"(",
")",
"if",
"not",
"line",
"or",
"line",
".",
"startswith",
"(",
"\"#\"",
")",
":",
"continue",
"match",
"=",
"re",
".",
"match",
"(",
"self",
".",
"SETTINGS_REGEX",
",",
"line",
")",
"if",
"not",
"match",
":",
"raise",
"Exception",
"(",
"\"Unparsable line {}\"",
".",
"format",
"(",
"line",
")",
")",
"key",
"=",
"match",
".",
"group",
"(",
"1",
")",
".",
"lower",
"(",
")",
"value",
"=",
"match",
".",
"group",
"(",
"2",
")",
"if",
"key",
"==",
"\"host\"",
":",
"self",
".",
"_config",
".",
"append",
"(",
"host",
")",
"host",
"=",
"{",
"\"host\"",
":",
"self",
".",
"_get_hosts",
"(",
"value",
")",
",",
"\"config\"",
":",
"{",
"}",
"}",
"elif",
"key",
"==",
"\"proxycommand\"",
"and",
"value",
".",
"lower",
"(",
")",
"==",
"\"none\"",
":",
"# Store 'none' as None; prior to 3.x, it will get stripped out",
"# at the end (for compatibility with issue #415). After 3.x, it",
"# will simply not get stripped, leaving a nice explicit marker.",
"host",
"[",
"\"config\"",
"]",
"[",
"key",
"]",
"=",
"None",
"else",
":",
"if",
"value",
".",
"startswith",
"(",
"'\"'",
")",
"and",
"value",
".",
"endswith",
"(",
"'\"'",
")",
":",
"value",
"=",
"value",
"[",
"1",
":",
"-",
"1",
"]",
"# identityfile, localforward, remoteforward keys are special",
"# cases, since they are allowed to be specified multiple times",
"# and they should be tried in order of specification.",
"if",
"key",
"in",
"[",
"\"identityfile\"",
",",
"\"localforward\"",
",",
"\"remoteforward\"",
"]",
":",
"if",
"key",
"in",
"host",
"[",
"\"config\"",
"]",
":",
"host",
"[",
"\"config\"",
"]",
"[",
"key",
"]",
".",
"append",
"(",
"value",
")",
"else",
":",
"host",
"[",
"\"config\"",
"]",
"[",
"key",
"]",
"=",
"[",
"value",
"]",
"elif",
"key",
"not",
"in",
"host",
"[",
"\"config\"",
"]",
":",
"host",
"[",
"\"config\"",
"]",
"[",
"key",
"]",
"=",
"value",
"self",
".",
"_config",
".",
"append",
"(",
"host",
")"
] | Read an OpenSSH config from the given file object.
:param file_obj: a file-like object to read the config file from | [
"Read",
"an",
"OpenSSH",
"config",
"from",
"the",
"given",
"file",
"object",
"."
] | cf7d49d66f3b1fbc8b0853518a54050182b3b5eb | https://github.com/paramiko/paramiko/blob/cf7d49d66f3b1fbc8b0853518a54050182b3b5eb/paramiko/config.py#L52-L94 | train |
paramiko/paramiko | paramiko/config.py | SSHConfig.lookup | def lookup(self, hostname):
"""
Return a dict (`SSHConfigDict`) of config options for a given hostname.
The host-matching rules of OpenSSH's ``ssh_config`` man page are used:
For each parameter, the first obtained value will be used. The
configuration files contain sections separated by ``Host``
specifications, and that section is only applied for hosts that match
one of the patterns given in the specification.
Since the first obtained value for each parameter is used, more host-
specific declarations should be given near the beginning of the file,
and general defaults at the end.
The keys in the returned dict are all normalized to lowercase (look for
``"port"``, not ``"Port"``. The values are processed according to the
rules for substitution variable expansion in ``ssh_config``.
Finally, please see the docs for `SSHConfigDict` for deeper info on
features such as optional type conversion methods, e.g.::
conf = my_config.lookup('myhost')
assert conf['passwordauthentication'] == 'yes'
assert conf.as_bool('passwordauthentication') is True
:param str hostname: the hostname to lookup
.. versionchanged:: 2.5
Returns `SSHConfigDict` objects instead of dict literals.
"""
matches = [
config
for config in self._config
if self._allowed(config["host"], hostname)
]
ret = SSHConfigDict()
for match in matches:
for key, value in match["config"].items():
if key not in ret:
# Create a copy of the original value,
# else it will reference the original list
# in self._config and update that value too
# when the extend() is being called.
ret[key] = value[:] if value is not None else value
elif key == "identityfile":
ret[key].extend(value)
ret = self._expand_variables(ret, hostname)
# TODO: remove in 3.x re #670
if "proxycommand" in ret and ret["proxycommand"] is None:
del ret["proxycommand"]
return ret | python | def lookup(self, hostname):
"""
Return a dict (`SSHConfigDict`) of config options for a given hostname.
The host-matching rules of OpenSSH's ``ssh_config`` man page are used:
For each parameter, the first obtained value will be used. The
configuration files contain sections separated by ``Host``
specifications, and that section is only applied for hosts that match
one of the patterns given in the specification.
Since the first obtained value for each parameter is used, more host-
specific declarations should be given near the beginning of the file,
and general defaults at the end.
The keys in the returned dict are all normalized to lowercase (look for
``"port"``, not ``"Port"``. The values are processed according to the
rules for substitution variable expansion in ``ssh_config``.
Finally, please see the docs for `SSHConfigDict` for deeper info on
features such as optional type conversion methods, e.g.::
conf = my_config.lookup('myhost')
assert conf['passwordauthentication'] == 'yes'
assert conf.as_bool('passwordauthentication') is True
:param str hostname: the hostname to lookup
.. versionchanged:: 2.5
Returns `SSHConfigDict` objects instead of dict literals.
"""
matches = [
config
for config in self._config
if self._allowed(config["host"], hostname)
]
ret = SSHConfigDict()
for match in matches:
for key, value in match["config"].items():
if key not in ret:
# Create a copy of the original value,
# else it will reference the original list
# in self._config and update that value too
# when the extend() is being called.
ret[key] = value[:] if value is not None else value
elif key == "identityfile":
ret[key].extend(value)
ret = self._expand_variables(ret, hostname)
# TODO: remove in 3.x re #670
if "proxycommand" in ret and ret["proxycommand"] is None:
del ret["proxycommand"]
return ret | [
"def",
"lookup",
"(",
"self",
",",
"hostname",
")",
":",
"matches",
"=",
"[",
"config",
"for",
"config",
"in",
"self",
".",
"_config",
"if",
"self",
".",
"_allowed",
"(",
"config",
"[",
"\"host\"",
"]",
",",
"hostname",
")",
"]",
"ret",
"=",
"SSHConfigDict",
"(",
")",
"for",
"match",
"in",
"matches",
":",
"for",
"key",
",",
"value",
"in",
"match",
"[",
"\"config\"",
"]",
".",
"items",
"(",
")",
":",
"if",
"key",
"not",
"in",
"ret",
":",
"# Create a copy of the original value,",
"# else it will reference the original list",
"# in self._config and update that value too",
"# when the extend() is being called.",
"ret",
"[",
"key",
"]",
"=",
"value",
"[",
":",
"]",
"if",
"value",
"is",
"not",
"None",
"else",
"value",
"elif",
"key",
"==",
"\"identityfile\"",
":",
"ret",
"[",
"key",
"]",
".",
"extend",
"(",
"value",
")",
"ret",
"=",
"self",
".",
"_expand_variables",
"(",
"ret",
",",
"hostname",
")",
"# TODO: remove in 3.x re #670",
"if",
"\"proxycommand\"",
"in",
"ret",
"and",
"ret",
"[",
"\"proxycommand\"",
"]",
"is",
"None",
":",
"del",
"ret",
"[",
"\"proxycommand\"",
"]",
"return",
"ret"
] | Return a dict (`SSHConfigDict`) of config options for a given hostname.
The host-matching rules of OpenSSH's ``ssh_config`` man page are used:
For each parameter, the first obtained value will be used. The
configuration files contain sections separated by ``Host``
specifications, and that section is only applied for hosts that match
one of the patterns given in the specification.
Since the first obtained value for each parameter is used, more host-
specific declarations should be given near the beginning of the file,
and general defaults at the end.
The keys in the returned dict are all normalized to lowercase (look for
``"port"``, not ``"Port"``. The values are processed according to the
rules for substitution variable expansion in ``ssh_config``.
Finally, please see the docs for `SSHConfigDict` for deeper info on
features such as optional type conversion methods, e.g.::
conf = my_config.lookup('myhost')
assert conf['passwordauthentication'] == 'yes'
assert conf.as_bool('passwordauthentication') is True
:param str hostname: the hostname to lookup
.. versionchanged:: 2.5
Returns `SSHConfigDict` objects instead of dict literals. | [
"Return",
"a",
"dict",
"(",
"SSHConfigDict",
")",
"of",
"config",
"options",
"for",
"a",
"given",
"hostname",
"."
] | cf7d49d66f3b1fbc8b0853518a54050182b3b5eb | https://github.com/paramiko/paramiko/blob/cf7d49d66f3b1fbc8b0853518a54050182b3b5eb/paramiko/config.py#L96-L147 | train |
paramiko/paramiko | paramiko/config.py | SSHConfig.get_hostnames | def get_hostnames(self):
"""
Return the set of literal hostnames defined in the SSH config (both
explicit hostnames and wildcard entries).
"""
hosts = set()
for entry in self._config:
hosts.update(entry["host"])
return hosts | python | def get_hostnames(self):
"""
Return the set of literal hostnames defined in the SSH config (both
explicit hostnames and wildcard entries).
"""
hosts = set()
for entry in self._config:
hosts.update(entry["host"])
return hosts | [
"def",
"get_hostnames",
"(",
"self",
")",
":",
"hosts",
"=",
"set",
"(",
")",
"for",
"entry",
"in",
"self",
".",
"_config",
":",
"hosts",
".",
"update",
"(",
"entry",
"[",
"\"host\"",
"]",
")",
"return",
"hosts"
] | Return the set of literal hostnames defined in the SSH config (both
explicit hostnames and wildcard entries). | [
"Return",
"the",
"set",
"of",
"literal",
"hostnames",
"defined",
"in",
"the",
"SSH",
"config",
"(",
"both",
"explicit",
"hostnames",
"and",
"wildcard",
"entries",
")",
"."
] | cf7d49d66f3b1fbc8b0853518a54050182b3b5eb | https://github.com/paramiko/paramiko/blob/cf7d49d66f3b1fbc8b0853518a54050182b3b5eb/paramiko/config.py#L149-L157 | train |
paramiko/paramiko | paramiko/config.py | SSHConfig._expand_variables | def _expand_variables(self, config, hostname):
"""
Return a dict of config options with expanded substitutions
for a given hostname.
Please refer to man ``ssh_config`` for the parameters that
are replaced.
:param dict config: the config for the hostname
:param str hostname: the hostname that the config belongs to
"""
if "hostname" in config:
config["hostname"] = config["hostname"].replace("%h", hostname)
else:
config["hostname"] = hostname
if "port" in config:
port = config["port"]
else:
port = SSH_PORT
user = os.getenv("USER")
if "user" in config:
remoteuser = config["user"]
else:
remoteuser = user
host = socket.gethostname().split(".")[0]
fqdn = LazyFqdn(config, host)
homedir = os.path.expanduser("~")
replacements = {
"controlpath": [
("%h", config["hostname"]),
("%l", fqdn),
("%L", host),
("%n", hostname),
("%p", port),
("%r", remoteuser),
("%u", user),
],
"identityfile": [
("~", homedir),
("%d", homedir),
("%h", config["hostname"]),
("%l", fqdn),
("%u", user),
("%r", remoteuser),
],
"proxycommand": [
("~", homedir),
("%h", config["hostname"]),
("%p", port),
("%r", remoteuser),
],
}
for k in config:
if config[k] is None:
continue
if k in replacements:
for find, replace in replacements[k]:
if isinstance(config[k], list):
for item in range(len(config[k])):
if find in config[k][item]:
config[k][item] = config[k][item].replace(
find, str(replace)
)
else:
if find in config[k]:
config[k] = config[k].replace(find, str(replace))
return config | python | def _expand_variables(self, config, hostname):
"""
Return a dict of config options with expanded substitutions
for a given hostname.
Please refer to man ``ssh_config`` for the parameters that
are replaced.
:param dict config: the config for the hostname
:param str hostname: the hostname that the config belongs to
"""
if "hostname" in config:
config["hostname"] = config["hostname"].replace("%h", hostname)
else:
config["hostname"] = hostname
if "port" in config:
port = config["port"]
else:
port = SSH_PORT
user = os.getenv("USER")
if "user" in config:
remoteuser = config["user"]
else:
remoteuser = user
host = socket.gethostname().split(".")[0]
fqdn = LazyFqdn(config, host)
homedir = os.path.expanduser("~")
replacements = {
"controlpath": [
("%h", config["hostname"]),
("%l", fqdn),
("%L", host),
("%n", hostname),
("%p", port),
("%r", remoteuser),
("%u", user),
],
"identityfile": [
("~", homedir),
("%d", homedir),
("%h", config["hostname"]),
("%l", fqdn),
("%u", user),
("%r", remoteuser),
],
"proxycommand": [
("~", homedir),
("%h", config["hostname"]),
("%p", port),
("%r", remoteuser),
],
}
for k in config:
if config[k] is None:
continue
if k in replacements:
for find, replace in replacements[k]:
if isinstance(config[k], list):
for item in range(len(config[k])):
if find in config[k][item]:
config[k][item] = config[k][item].replace(
find, str(replace)
)
else:
if find in config[k]:
config[k] = config[k].replace(find, str(replace))
return config | [
"def",
"_expand_variables",
"(",
"self",
",",
"config",
",",
"hostname",
")",
":",
"if",
"\"hostname\"",
"in",
"config",
":",
"config",
"[",
"\"hostname\"",
"]",
"=",
"config",
"[",
"\"hostname\"",
"]",
".",
"replace",
"(",
"\"%h\"",
",",
"hostname",
")",
"else",
":",
"config",
"[",
"\"hostname\"",
"]",
"=",
"hostname",
"if",
"\"port\"",
"in",
"config",
":",
"port",
"=",
"config",
"[",
"\"port\"",
"]",
"else",
":",
"port",
"=",
"SSH_PORT",
"user",
"=",
"os",
".",
"getenv",
"(",
"\"USER\"",
")",
"if",
"\"user\"",
"in",
"config",
":",
"remoteuser",
"=",
"config",
"[",
"\"user\"",
"]",
"else",
":",
"remoteuser",
"=",
"user",
"host",
"=",
"socket",
".",
"gethostname",
"(",
")",
".",
"split",
"(",
"\".\"",
")",
"[",
"0",
"]",
"fqdn",
"=",
"LazyFqdn",
"(",
"config",
",",
"host",
")",
"homedir",
"=",
"os",
".",
"path",
".",
"expanduser",
"(",
"\"~\"",
")",
"replacements",
"=",
"{",
"\"controlpath\"",
":",
"[",
"(",
"\"%h\"",
",",
"config",
"[",
"\"hostname\"",
"]",
")",
",",
"(",
"\"%l\"",
",",
"fqdn",
")",
",",
"(",
"\"%L\"",
",",
"host",
")",
",",
"(",
"\"%n\"",
",",
"hostname",
")",
",",
"(",
"\"%p\"",
",",
"port",
")",
",",
"(",
"\"%r\"",
",",
"remoteuser",
")",
",",
"(",
"\"%u\"",
",",
"user",
")",
",",
"]",
",",
"\"identityfile\"",
":",
"[",
"(",
"\"~\"",
",",
"homedir",
")",
",",
"(",
"\"%d\"",
",",
"homedir",
")",
",",
"(",
"\"%h\"",
",",
"config",
"[",
"\"hostname\"",
"]",
")",
",",
"(",
"\"%l\"",
",",
"fqdn",
")",
",",
"(",
"\"%u\"",
",",
"user",
")",
",",
"(",
"\"%r\"",
",",
"remoteuser",
")",
",",
"]",
",",
"\"proxycommand\"",
":",
"[",
"(",
"\"~\"",
",",
"homedir",
")",
",",
"(",
"\"%h\"",
",",
"config",
"[",
"\"hostname\"",
"]",
")",
",",
"(",
"\"%p\"",
",",
"port",
")",
",",
"(",
"\"%r\"",
",",
"remoteuser",
")",
",",
"]",
",",
"}",
"for",
"k",
"in",
"config",
":",
"if",
"config",
"[",
"k",
"]",
"is",
"None",
":",
"continue",
"if",
"k",
"in",
"replacements",
":",
"for",
"find",
",",
"replace",
"in",
"replacements",
"[",
"k",
"]",
":",
"if",
"isinstance",
"(",
"config",
"[",
"k",
"]",
",",
"list",
")",
":",
"for",
"item",
"in",
"range",
"(",
"len",
"(",
"config",
"[",
"k",
"]",
")",
")",
":",
"if",
"find",
"in",
"config",
"[",
"k",
"]",
"[",
"item",
"]",
":",
"config",
"[",
"k",
"]",
"[",
"item",
"]",
"=",
"config",
"[",
"k",
"]",
"[",
"item",
"]",
".",
"replace",
"(",
"find",
",",
"str",
"(",
"replace",
")",
")",
"else",
":",
"if",
"find",
"in",
"config",
"[",
"k",
"]",
":",
"config",
"[",
"k",
"]",
"=",
"config",
"[",
"k",
"]",
".",
"replace",
"(",
"find",
",",
"str",
"(",
"replace",
")",
")",
"return",
"config"
] | Return a dict of config options with expanded substitutions
for a given hostname.
Please refer to man ``ssh_config`` for the parameters that
are replaced.
:param dict config: the config for the hostname
:param str hostname: the hostname that the config belongs to | [
"Return",
"a",
"dict",
"of",
"config",
"options",
"with",
"expanded",
"substitutions",
"for",
"a",
"given",
"hostname",
"."
] | cf7d49d66f3b1fbc8b0853518a54050182b3b5eb | https://github.com/paramiko/paramiko/blob/cf7d49d66f3b1fbc8b0853518a54050182b3b5eb/paramiko/config.py#L168-L239 | train |
paramiko/paramiko | paramiko/config.py | SSHConfig._get_hosts | def _get_hosts(self, host):
"""
Return a list of host_names from host value.
"""
try:
return shlex.split(host)
except ValueError:
raise Exception("Unparsable host {}".format(host)) | python | def _get_hosts(self, host):
"""
Return a list of host_names from host value.
"""
try:
return shlex.split(host)
except ValueError:
raise Exception("Unparsable host {}".format(host)) | [
"def",
"_get_hosts",
"(",
"self",
",",
"host",
")",
":",
"try",
":",
"return",
"shlex",
".",
"split",
"(",
"host",
")",
"except",
"ValueError",
":",
"raise",
"Exception",
"(",
"\"Unparsable host {}\"",
".",
"format",
"(",
"host",
")",
")"
] | Return a list of host_names from host value. | [
"Return",
"a",
"list",
"of",
"host_names",
"from",
"host",
"value",
"."
] | cf7d49d66f3b1fbc8b0853518a54050182b3b5eb | https://github.com/paramiko/paramiko/blob/cf7d49d66f3b1fbc8b0853518a54050182b3b5eb/paramiko/config.py#L241-L248 | train |
paramiko/paramiko | paramiko/config.py | SSHConfigDict.as_bool | def as_bool(self, key):
"""
Express given key's value as a boolean type.
Typically, this is used for ``ssh_config``'s pseudo-boolean values
which are either ``"yes"`` or ``"no"``. In such cases, ``"yes"`` yields
``True`` and any other value becomes ``False``.
.. note::
If (for whatever reason) the stored value is already boolean in
nature, it's simply returned.
.. versionadded:: 2.5
"""
val = self[key]
if isinstance(val, bool):
return val
return val.lower() == "yes" | python | def as_bool(self, key):
"""
Express given key's value as a boolean type.
Typically, this is used for ``ssh_config``'s pseudo-boolean values
which are either ``"yes"`` or ``"no"``. In such cases, ``"yes"`` yields
``True`` and any other value becomes ``False``.
.. note::
If (for whatever reason) the stored value is already boolean in
nature, it's simply returned.
.. versionadded:: 2.5
"""
val = self[key]
if isinstance(val, bool):
return val
return val.lower() == "yes" | [
"def",
"as_bool",
"(",
"self",
",",
"key",
")",
":",
"val",
"=",
"self",
"[",
"key",
"]",
"if",
"isinstance",
"(",
"val",
",",
"bool",
")",
":",
"return",
"val",
"return",
"val",
".",
"lower",
"(",
")",
"==",
"\"yes\""
] | Express given key's value as a boolean type.
Typically, this is used for ``ssh_config``'s pseudo-boolean values
which are either ``"yes"`` or ``"no"``. In such cases, ``"yes"`` yields
``True`` and any other value becomes ``False``.
.. note::
If (for whatever reason) the stored value is already boolean in
nature, it's simply returned.
.. versionadded:: 2.5 | [
"Express",
"given",
"key",
"s",
"value",
"as",
"a",
"boolean",
"type",
"."
] | cf7d49d66f3b1fbc8b0853518a54050182b3b5eb | https://github.com/paramiko/paramiko/blob/cf7d49d66f3b1fbc8b0853518a54050182b3b5eb/paramiko/config.py#L344-L361 | train |
paramiko/paramiko | paramiko/server.py | ServerInterface.check_auth_gssapi_with_mic | def check_auth_gssapi_with_mic(
self, username, gss_authenticated=AUTH_FAILED, cc_file=None
):
"""
Authenticate the given user to the server if he is a valid krb5
principal.
:param str username: The username of the authenticating client
:param int gss_authenticated: The result of the krb5 authentication
:param str cc_filename: The krb5 client credentials cache filename
:return: ``AUTH_FAILED`` if the user is not authenticated otherwise
``AUTH_SUCCESSFUL``
:rtype: int
:note: Kerberos credential delegation is not supported.
:see: `.ssh_gss`
:note: : We are just checking in L{AuthHandler} that the given user is
a valid krb5 principal!
We don't check if the krb5 principal is allowed to log in on
the server, because there is no way to do that in python. So
if you develop your own SSH server with paramiko for a cetain
plattform like Linux, you should call C{krb5_kuserok()} in
your local kerberos library to make sure that the
krb5_principal has an account on the server and is allowed to
log in as a user.
:see: http://www.unix.com/man-page/all/3/krb5_kuserok/
"""
if gss_authenticated == AUTH_SUCCESSFUL:
return AUTH_SUCCESSFUL
return AUTH_FAILED | python | def check_auth_gssapi_with_mic(
self, username, gss_authenticated=AUTH_FAILED, cc_file=None
):
"""
Authenticate the given user to the server if he is a valid krb5
principal.
:param str username: The username of the authenticating client
:param int gss_authenticated: The result of the krb5 authentication
:param str cc_filename: The krb5 client credentials cache filename
:return: ``AUTH_FAILED`` if the user is not authenticated otherwise
``AUTH_SUCCESSFUL``
:rtype: int
:note: Kerberos credential delegation is not supported.
:see: `.ssh_gss`
:note: : We are just checking in L{AuthHandler} that the given user is
a valid krb5 principal!
We don't check if the krb5 principal is allowed to log in on
the server, because there is no way to do that in python. So
if you develop your own SSH server with paramiko for a cetain
plattform like Linux, you should call C{krb5_kuserok()} in
your local kerberos library to make sure that the
krb5_principal has an account on the server and is allowed to
log in as a user.
:see: http://www.unix.com/man-page/all/3/krb5_kuserok/
"""
if gss_authenticated == AUTH_SUCCESSFUL:
return AUTH_SUCCESSFUL
return AUTH_FAILED | [
"def",
"check_auth_gssapi_with_mic",
"(",
"self",
",",
"username",
",",
"gss_authenticated",
"=",
"AUTH_FAILED",
",",
"cc_file",
"=",
"None",
")",
":",
"if",
"gss_authenticated",
"==",
"AUTH_SUCCESSFUL",
":",
"return",
"AUTH_SUCCESSFUL",
"return",
"AUTH_FAILED"
] | Authenticate the given user to the server if he is a valid krb5
principal.
:param str username: The username of the authenticating client
:param int gss_authenticated: The result of the krb5 authentication
:param str cc_filename: The krb5 client credentials cache filename
:return: ``AUTH_FAILED`` if the user is not authenticated otherwise
``AUTH_SUCCESSFUL``
:rtype: int
:note: Kerberos credential delegation is not supported.
:see: `.ssh_gss`
:note: : We are just checking in L{AuthHandler} that the given user is
a valid krb5 principal!
We don't check if the krb5 principal is allowed to log in on
the server, because there is no way to do that in python. So
if you develop your own SSH server with paramiko for a cetain
plattform like Linux, you should call C{krb5_kuserok()} in
your local kerberos library to make sure that the
krb5_principal has an account on the server and is allowed to
log in as a user.
:see: http://www.unix.com/man-page/all/3/krb5_kuserok/ | [
"Authenticate",
"the",
"given",
"user",
"to",
"the",
"server",
"if",
"he",
"is",
"a",
"valid",
"krb5",
"principal",
"."
] | cf7d49d66f3b1fbc8b0853518a54050182b3b5eb | https://github.com/paramiko/paramiko/blob/cf7d49d66f3b1fbc8b0853518a54050182b3b5eb/paramiko/server.py#L239-L267 | train |
paramiko/paramiko | paramiko/server.py | ServerInterface.check_auth_gssapi_keyex | def check_auth_gssapi_keyex(
self, username, gss_authenticated=AUTH_FAILED, cc_file=None
):
"""
Authenticate the given user to the server if he is a valid krb5
principal and GSS-API Key Exchange was performed.
If GSS-API Key Exchange was not performed, this authentication method
won't be available.
:param str username: The username of the authenticating client
:param int gss_authenticated: The result of the krb5 authentication
:param str cc_filename: The krb5 client credentials cache filename
:return: ``AUTH_FAILED`` if the user is not authenticated otherwise
``AUTH_SUCCESSFUL``
:rtype: int
:note: Kerberos credential delegation is not supported.
:see: `.ssh_gss` `.kex_gss`
:note: : We are just checking in L{AuthHandler} that the given user is
a valid krb5 principal!
We don't check if the krb5 principal is allowed to log in on
the server, because there is no way to do that in python. So
if you develop your own SSH server with paramiko for a cetain
plattform like Linux, you should call C{krb5_kuserok()} in
your local kerberos library to make sure that the
krb5_principal has an account on the server and is allowed
to log in as a user.
:see: http://www.unix.com/man-page/all/3/krb5_kuserok/
"""
if gss_authenticated == AUTH_SUCCESSFUL:
return AUTH_SUCCESSFUL
return AUTH_FAILED | python | def check_auth_gssapi_keyex(
self, username, gss_authenticated=AUTH_FAILED, cc_file=None
):
"""
Authenticate the given user to the server if he is a valid krb5
principal and GSS-API Key Exchange was performed.
If GSS-API Key Exchange was not performed, this authentication method
won't be available.
:param str username: The username of the authenticating client
:param int gss_authenticated: The result of the krb5 authentication
:param str cc_filename: The krb5 client credentials cache filename
:return: ``AUTH_FAILED`` if the user is not authenticated otherwise
``AUTH_SUCCESSFUL``
:rtype: int
:note: Kerberos credential delegation is not supported.
:see: `.ssh_gss` `.kex_gss`
:note: : We are just checking in L{AuthHandler} that the given user is
a valid krb5 principal!
We don't check if the krb5 principal is allowed to log in on
the server, because there is no way to do that in python. So
if you develop your own SSH server with paramiko for a cetain
plattform like Linux, you should call C{krb5_kuserok()} in
your local kerberos library to make sure that the
krb5_principal has an account on the server and is allowed
to log in as a user.
:see: http://www.unix.com/man-page/all/3/krb5_kuserok/
"""
if gss_authenticated == AUTH_SUCCESSFUL:
return AUTH_SUCCESSFUL
return AUTH_FAILED | [
"def",
"check_auth_gssapi_keyex",
"(",
"self",
",",
"username",
",",
"gss_authenticated",
"=",
"AUTH_FAILED",
",",
"cc_file",
"=",
"None",
")",
":",
"if",
"gss_authenticated",
"==",
"AUTH_SUCCESSFUL",
":",
"return",
"AUTH_SUCCESSFUL",
"return",
"AUTH_FAILED"
] | Authenticate the given user to the server if he is a valid krb5
principal and GSS-API Key Exchange was performed.
If GSS-API Key Exchange was not performed, this authentication method
won't be available.
:param str username: The username of the authenticating client
:param int gss_authenticated: The result of the krb5 authentication
:param str cc_filename: The krb5 client credentials cache filename
:return: ``AUTH_FAILED`` if the user is not authenticated otherwise
``AUTH_SUCCESSFUL``
:rtype: int
:note: Kerberos credential delegation is not supported.
:see: `.ssh_gss` `.kex_gss`
:note: : We are just checking in L{AuthHandler} that the given user is
a valid krb5 principal!
We don't check if the krb5 principal is allowed to log in on
the server, because there is no way to do that in python. So
if you develop your own SSH server with paramiko for a cetain
plattform like Linux, you should call C{krb5_kuserok()} in
your local kerberos library to make sure that the
krb5_principal has an account on the server and is allowed
to log in as a user.
:see: http://www.unix.com/man-page/all/3/krb5_kuserok/ | [
"Authenticate",
"the",
"given",
"user",
"to",
"the",
"server",
"if",
"he",
"is",
"a",
"valid",
"krb5",
"principal",
"and",
"GSS",
"-",
"API",
"Key",
"Exchange",
"was",
"performed",
".",
"If",
"GSS",
"-",
"API",
"Key",
"Exchange",
"was",
"not",
"performed",
"this",
"authentication",
"method",
"won",
"t",
"be",
"available",
"."
] | cf7d49d66f3b1fbc8b0853518a54050182b3b5eb | https://github.com/paramiko/paramiko/blob/cf7d49d66f3b1fbc8b0853518a54050182b3b5eb/paramiko/server.py#L269-L299 | train |
paramiko/paramiko | paramiko/server.py | ServerInterface.check_channel_subsystem_request | def check_channel_subsystem_request(self, channel, name):
"""
Determine if a requested subsystem will be provided to the client on
the given channel. If this method returns ``True``, all future I/O
through this channel will be assumed to be connected to the requested
subsystem. An example of a subsystem is ``sftp``.
The default implementation checks for a subsystem handler assigned via
`.Transport.set_subsystem_handler`.
If one has been set, the handler is invoked and this method returns
``True``. Otherwise it returns ``False``.
.. note:: Because the default implementation uses the `.Transport` to
identify valid subsystems, you probably won't need to override this
method.
:param .Channel channel: the `.Channel` the pty request arrived on.
:param str name: name of the requested subsystem.
:return:
``True`` if this channel is now hooked up to the requested
subsystem; ``False`` if that subsystem can't or won't be provided.
"""
transport = channel.get_transport()
handler_class, larg, kwarg = transport._get_subsystem_handler(name)
if handler_class is None:
return False
handler = handler_class(channel, name, self, *larg, **kwarg)
handler.start()
return True | python | def check_channel_subsystem_request(self, channel, name):
"""
Determine if a requested subsystem will be provided to the client on
the given channel. If this method returns ``True``, all future I/O
through this channel will be assumed to be connected to the requested
subsystem. An example of a subsystem is ``sftp``.
The default implementation checks for a subsystem handler assigned via
`.Transport.set_subsystem_handler`.
If one has been set, the handler is invoked and this method returns
``True``. Otherwise it returns ``False``.
.. note:: Because the default implementation uses the `.Transport` to
identify valid subsystems, you probably won't need to override this
method.
:param .Channel channel: the `.Channel` the pty request arrived on.
:param str name: name of the requested subsystem.
:return:
``True`` if this channel is now hooked up to the requested
subsystem; ``False`` if that subsystem can't or won't be provided.
"""
transport = channel.get_transport()
handler_class, larg, kwarg = transport._get_subsystem_handler(name)
if handler_class is None:
return False
handler = handler_class(channel, name, self, *larg, **kwarg)
handler.start()
return True | [
"def",
"check_channel_subsystem_request",
"(",
"self",
",",
"channel",
",",
"name",
")",
":",
"transport",
"=",
"channel",
".",
"get_transport",
"(",
")",
"handler_class",
",",
"larg",
",",
"kwarg",
"=",
"transport",
".",
"_get_subsystem_handler",
"(",
"name",
")",
"if",
"handler_class",
"is",
"None",
":",
"return",
"False",
"handler",
"=",
"handler_class",
"(",
"channel",
",",
"name",
",",
"self",
",",
"*",
"larg",
",",
"*",
"*",
"kwarg",
")",
"handler",
".",
"start",
"(",
")",
"return",
"True"
] | Determine if a requested subsystem will be provided to the client on
the given channel. If this method returns ``True``, all future I/O
through this channel will be assumed to be connected to the requested
subsystem. An example of a subsystem is ``sftp``.
The default implementation checks for a subsystem handler assigned via
`.Transport.set_subsystem_handler`.
If one has been set, the handler is invoked and this method returns
``True``. Otherwise it returns ``False``.
.. note:: Because the default implementation uses the `.Transport` to
identify valid subsystems, you probably won't need to override this
method.
:param .Channel channel: the `.Channel` the pty request arrived on.
:param str name: name of the requested subsystem.
:return:
``True`` if this channel is now hooked up to the requested
subsystem; ``False`` if that subsystem can't or won't be provided. | [
"Determine",
"if",
"a",
"requested",
"subsystem",
"will",
"be",
"provided",
"to",
"the",
"client",
"on",
"the",
"given",
"channel",
".",
"If",
"this",
"method",
"returns",
"True",
"all",
"future",
"I",
"/",
"O",
"through",
"this",
"channel",
"will",
"be",
"assumed",
"to",
"be",
"connected",
"to",
"the",
"requested",
"subsystem",
".",
"An",
"example",
"of",
"a",
"subsystem",
"is",
"sftp",
"."
] | cf7d49d66f3b1fbc8b0853518a54050182b3b5eb | https://github.com/paramiko/paramiko/blob/cf7d49d66f3b1fbc8b0853518a54050182b3b5eb/paramiko/server.py#L435-L463 | train |
paramiko/paramiko | paramiko/server.py | InteractiveQuery.add_prompt | def add_prompt(self, prompt, echo=True):
"""
Add a prompt to this query. The prompt should be a (reasonably short)
string. Multiple prompts can be added to the same query.
:param str prompt: the user prompt
:param bool echo:
``True`` (default) if the user's response should be echoed;
``False`` if not (for a password or similar)
"""
self.prompts.append((prompt, echo)) | python | def add_prompt(self, prompt, echo=True):
"""
Add a prompt to this query. The prompt should be a (reasonably short)
string. Multiple prompts can be added to the same query.
:param str prompt: the user prompt
:param bool echo:
``True`` (default) if the user's response should be echoed;
``False`` if not (for a password or similar)
"""
self.prompts.append((prompt, echo)) | [
"def",
"add_prompt",
"(",
"self",
",",
"prompt",
",",
"echo",
"=",
"True",
")",
":",
"self",
".",
"prompts",
".",
"append",
"(",
"(",
"prompt",
",",
"echo",
")",
")"
] | Add a prompt to this query. The prompt should be a (reasonably short)
string. Multiple prompts can be added to the same query.
:param str prompt: the user prompt
:param bool echo:
``True`` (default) if the user's response should be echoed;
``False`` if not (for a password or similar) | [
"Add",
"a",
"prompt",
"to",
"this",
"query",
".",
"The",
"prompt",
"should",
"be",
"a",
"(",
"reasonably",
"short",
")",
"string",
".",
"Multiple",
"prompts",
"can",
"be",
"added",
"to",
"the",
"same",
"query",
"."
] | cf7d49d66f3b1fbc8b0853518a54050182b3b5eb | https://github.com/paramiko/paramiko/blob/cf7d49d66f3b1fbc8b0853518a54050182b3b5eb/paramiko/server.py#L623-L633 | train |
paramiko/paramiko | paramiko/ssh_gss.py | GSSAuth | def GSSAuth(auth_method, gss_deleg_creds=True):
"""
Provide SSH2 GSS-API / SSPI authentication.
:param str auth_method: The name of the SSH authentication mechanism
(gssapi-with-mic or gss-keyex)
:param bool gss_deleg_creds: Delegate client credentials or not.
We delegate credentials by default.
:return: Either an `._SSH_GSSAPI` (Unix) object or an
`_SSH_SSPI` (Windows) object
:raises: ``ImportError`` -- If no GSS-API / SSPI module could be imported.
:see: `RFC 4462 <http://www.ietf.org/rfc/rfc4462.txt>`_
:note: Check for the available API and return either an `._SSH_GSSAPI`
(MIT GSSAPI) object or an `._SSH_SSPI` (MS SSPI) object. If you
get python-gssapi working on Windows, python-gssapi
will be used and a `._SSH_GSSAPI` object will be returned.
If there is no supported API available,
``None`` will be returned.
"""
if _API == "MIT":
return _SSH_GSSAPI(auth_method, gss_deleg_creds)
elif _API == "SSPI" and os.name == "nt":
return _SSH_SSPI(auth_method, gss_deleg_creds)
else:
raise ImportError("Unable to import a GSS-API / SSPI module!") | python | def GSSAuth(auth_method, gss_deleg_creds=True):
"""
Provide SSH2 GSS-API / SSPI authentication.
:param str auth_method: The name of the SSH authentication mechanism
(gssapi-with-mic or gss-keyex)
:param bool gss_deleg_creds: Delegate client credentials or not.
We delegate credentials by default.
:return: Either an `._SSH_GSSAPI` (Unix) object or an
`_SSH_SSPI` (Windows) object
:raises: ``ImportError`` -- If no GSS-API / SSPI module could be imported.
:see: `RFC 4462 <http://www.ietf.org/rfc/rfc4462.txt>`_
:note: Check for the available API and return either an `._SSH_GSSAPI`
(MIT GSSAPI) object or an `._SSH_SSPI` (MS SSPI) object. If you
get python-gssapi working on Windows, python-gssapi
will be used and a `._SSH_GSSAPI` object will be returned.
If there is no supported API available,
``None`` will be returned.
"""
if _API == "MIT":
return _SSH_GSSAPI(auth_method, gss_deleg_creds)
elif _API == "SSPI" and os.name == "nt":
return _SSH_SSPI(auth_method, gss_deleg_creds)
else:
raise ImportError("Unable to import a GSS-API / SSPI module!") | [
"def",
"GSSAuth",
"(",
"auth_method",
",",
"gss_deleg_creds",
"=",
"True",
")",
":",
"if",
"_API",
"==",
"\"MIT\"",
":",
"return",
"_SSH_GSSAPI",
"(",
"auth_method",
",",
"gss_deleg_creds",
")",
"elif",
"_API",
"==",
"\"SSPI\"",
"and",
"os",
".",
"name",
"==",
"\"nt\"",
":",
"return",
"_SSH_SSPI",
"(",
"auth_method",
",",
"gss_deleg_creds",
")",
"else",
":",
"raise",
"ImportError",
"(",
"\"Unable to import a GSS-API / SSPI module!\"",
")"
] | Provide SSH2 GSS-API / SSPI authentication.
:param str auth_method: The name of the SSH authentication mechanism
(gssapi-with-mic or gss-keyex)
:param bool gss_deleg_creds: Delegate client credentials or not.
We delegate credentials by default.
:return: Either an `._SSH_GSSAPI` (Unix) object or an
`_SSH_SSPI` (Windows) object
:raises: ``ImportError`` -- If no GSS-API / SSPI module could be imported.
:see: `RFC 4462 <http://www.ietf.org/rfc/rfc4462.txt>`_
:note: Check for the available API and return either an `._SSH_GSSAPI`
(MIT GSSAPI) object or an `._SSH_SSPI` (MS SSPI) object. If you
get python-gssapi working on Windows, python-gssapi
will be used and a `._SSH_GSSAPI` object will be returned.
If there is no supported API available,
``None`` will be returned. | [
"Provide",
"SSH2",
"GSS",
"-",
"API",
"/",
"SSPI",
"authentication",
"."
] | cf7d49d66f3b1fbc8b0853518a54050182b3b5eb | https://github.com/paramiko/paramiko/blob/cf7d49d66f3b1fbc8b0853518a54050182b3b5eb/paramiko/ssh_gss.py#L68-L94 | train |
paramiko/paramiko | paramiko/ssh_gss.py | _SSH_GSSAuth.ssh_gss_oids | def ssh_gss_oids(self, mode="client"):
"""
This method returns a single OID, because we only support the
Kerberos V5 mechanism.
:param str mode: Client for client mode and server for server mode
:return: A byte sequence containing the number of supported
OIDs, the length of the OID and the actual OID encoded with
DER
:note: In server mode we just return the OID length and the DER encoded
OID.
"""
from pyasn1.type.univ import ObjectIdentifier
from pyasn1.codec.der import encoder
OIDs = self._make_uint32(1)
krb5_OID = encoder.encode(ObjectIdentifier(self._krb5_mech))
OID_len = self._make_uint32(len(krb5_OID))
if mode == "server":
return OID_len + krb5_OID
return OIDs + OID_len + krb5_OID | python | def ssh_gss_oids(self, mode="client"):
"""
This method returns a single OID, because we only support the
Kerberos V5 mechanism.
:param str mode: Client for client mode and server for server mode
:return: A byte sequence containing the number of supported
OIDs, the length of the OID and the actual OID encoded with
DER
:note: In server mode we just return the OID length and the DER encoded
OID.
"""
from pyasn1.type.univ import ObjectIdentifier
from pyasn1.codec.der import encoder
OIDs = self._make_uint32(1)
krb5_OID = encoder.encode(ObjectIdentifier(self._krb5_mech))
OID_len = self._make_uint32(len(krb5_OID))
if mode == "server":
return OID_len + krb5_OID
return OIDs + OID_len + krb5_OID | [
"def",
"ssh_gss_oids",
"(",
"self",
",",
"mode",
"=",
"\"client\"",
")",
":",
"from",
"pyasn1",
".",
"type",
".",
"univ",
"import",
"ObjectIdentifier",
"from",
"pyasn1",
".",
"codec",
".",
"der",
"import",
"encoder",
"OIDs",
"=",
"self",
".",
"_make_uint32",
"(",
"1",
")",
"krb5_OID",
"=",
"encoder",
".",
"encode",
"(",
"ObjectIdentifier",
"(",
"self",
".",
"_krb5_mech",
")",
")",
"OID_len",
"=",
"self",
".",
"_make_uint32",
"(",
"len",
"(",
"krb5_OID",
")",
")",
"if",
"mode",
"==",
"\"server\"",
":",
"return",
"OID_len",
"+",
"krb5_OID",
"return",
"OIDs",
"+",
"OID_len",
"+",
"krb5_OID"
] | This method returns a single OID, because we only support the
Kerberos V5 mechanism.
:param str mode: Client for client mode and server for server mode
:return: A byte sequence containing the number of supported
OIDs, the length of the OID and the actual OID encoded with
DER
:note: In server mode we just return the OID length and the DER encoded
OID. | [
"This",
"method",
"returns",
"a",
"single",
"OID",
"because",
"we",
"only",
"support",
"the",
"Kerberos",
"V5",
"mechanism",
"."
] | cf7d49d66f3b1fbc8b0853518a54050182b3b5eb | https://github.com/paramiko/paramiko/blob/cf7d49d66f3b1fbc8b0853518a54050182b3b5eb/paramiko/ssh_gss.py#L150-L170 | train |
paramiko/paramiko | paramiko/ssh_gss.py | _SSH_GSSAuth.ssh_check_mech | def ssh_check_mech(self, desired_mech):
"""
Check if the given OID is the Kerberos V5 OID (server mode).
:param str desired_mech: The desired GSS-API mechanism of the client
:return: ``True`` if the given OID is supported, otherwise C{False}
"""
from pyasn1.codec.der import decoder
mech, __ = decoder.decode(desired_mech)
if mech.__str__() != self._krb5_mech:
return False
return True | python | def ssh_check_mech(self, desired_mech):
"""
Check if the given OID is the Kerberos V5 OID (server mode).
:param str desired_mech: The desired GSS-API mechanism of the client
:return: ``True`` if the given OID is supported, otherwise C{False}
"""
from pyasn1.codec.der import decoder
mech, __ = decoder.decode(desired_mech)
if mech.__str__() != self._krb5_mech:
return False
return True | [
"def",
"ssh_check_mech",
"(",
"self",
",",
"desired_mech",
")",
":",
"from",
"pyasn1",
".",
"codec",
".",
"der",
"import",
"decoder",
"mech",
",",
"__",
"=",
"decoder",
".",
"decode",
"(",
"desired_mech",
")",
"if",
"mech",
".",
"__str__",
"(",
")",
"!=",
"self",
".",
"_krb5_mech",
":",
"return",
"False",
"return",
"True"
] | Check if the given OID is the Kerberos V5 OID (server mode).
:param str desired_mech: The desired GSS-API mechanism of the client
:return: ``True`` if the given OID is supported, otherwise C{False} | [
"Check",
"if",
"the",
"given",
"OID",
"is",
"the",
"Kerberos",
"V5",
"OID",
"(",
"server",
"mode",
")",
"."
] | cf7d49d66f3b1fbc8b0853518a54050182b3b5eb | https://github.com/paramiko/paramiko/blob/cf7d49d66f3b1fbc8b0853518a54050182b3b5eb/paramiko/ssh_gss.py#L172-L184 | train |
paramiko/paramiko | paramiko/ssh_gss.py | _SSH_GSSAuth._ssh_build_mic | def _ssh_build_mic(self, session_id, username, service, auth_method):
"""
Create the SSH2 MIC filed for gssapi-with-mic.
:param str session_id: The SSH session ID
:param str username: The name of the user who attempts to login
:param str service: The requested SSH service
:param str auth_method: The requested SSH authentication mechanism
:return: The MIC as defined in RFC 4462. The contents of the
MIC field are:
string session_identifier,
byte SSH_MSG_USERAUTH_REQUEST,
string user-name,
string service (ssh-connection),
string authentication-method
(gssapi-with-mic or gssapi-keyex)
"""
mic = self._make_uint32(len(session_id))
mic += session_id
mic += struct.pack("B", MSG_USERAUTH_REQUEST)
mic += self._make_uint32(len(username))
mic += username.encode()
mic += self._make_uint32(len(service))
mic += service.encode()
mic += self._make_uint32(len(auth_method))
mic += auth_method.encode()
return mic | python | def _ssh_build_mic(self, session_id, username, service, auth_method):
"""
Create the SSH2 MIC filed for gssapi-with-mic.
:param str session_id: The SSH session ID
:param str username: The name of the user who attempts to login
:param str service: The requested SSH service
:param str auth_method: The requested SSH authentication mechanism
:return: The MIC as defined in RFC 4462. The contents of the
MIC field are:
string session_identifier,
byte SSH_MSG_USERAUTH_REQUEST,
string user-name,
string service (ssh-connection),
string authentication-method
(gssapi-with-mic or gssapi-keyex)
"""
mic = self._make_uint32(len(session_id))
mic += session_id
mic += struct.pack("B", MSG_USERAUTH_REQUEST)
mic += self._make_uint32(len(username))
mic += username.encode()
mic += self._make_uint32(len(service))
mic += service.encode()
mic += self._make_uint32(len(auth_method))
mic += auth_method.encode()
return mic | [
"def",
"_ssh_build_mic",
"(",
"self",
",",
"session_id",
",",
"username",
",",
"service",
",",
"auth_method",
")",
":",
"mic",
"=",
"self",
".",
"_make_uint32",
"(",
"len",
"(",
"session_id",
")",
")",
"mic",
"+=",
"session_id",
"mic",
"+=",
"struct",
".",
"pack",
"(",
"\"B\"",
",",
"MSG_USERAUTH_REQUEST",
")",
"mic",
"+=",
"self",
".",
"_make_uint32",
"(",
"len",
"(",
"username",
")",
")",
"mic",
"+=",
"username",
".",
"encode",
"(",
")",
"mic",
"+=",
"self",
".",
"_make_uint32",
"(",
"len",
"(",
"service",
")",
")",
"mic",
"+=",
"service",
".",
"encode",
"(",
")",
"mic",
"+=",
"self",
".",
"_make_uint32",
"(",
"len",
"(",
"auth_method",
")",
")",
"mic",
"+=",
"auth_method",
".",
"encode",
"(",
")",
"return",
"mic"
] | Create the SSH2 MIC filed for gssapi-with-mic.
:param str session_id: The SSH session ID
:param str username: The name of the user who attempts to login
:param str service: The requested SSH service
:param str auth_method: The requested SSH authentication mechanism
:return: The MIC as defined in RFC 4462. The contents of the
MIC field are:
string session_identifier,
byte SSH_MSG_USERAUTH_REQUEST,
string user-name,
string service (ssh-connection),
string authentication-method
(gssapi-with-mic or gssapi-keyex) | [
"Create",
"the",
"SSH2",
"MIC",
"filed",
"for",
"gssapi",
"-",
"with",
"-",
"mic",
"."
] | cf7d49d66f3b1fbc8b0853518a54050182b3b5eb | https://github.com/paramiko/paramiko/blob/cf7d49d66f3b1fbc8b0853518a54050182b3b5eb/paramiko/ssh_gss.py#L197-L223 | train |
paramiko/paramiko | paramiko/ssh_gss.py | _SSH_GSSAPI.ssh_init_sec_context | def ssh_init_sec_context(
self, target, desired_mech=None, username=None, recv_token=None
):
"""
Initialize a GSS-API context.
:param str username: The name of the user who attempts to login
:param str target: The hostname of the target to connect to
:param str desired_mech: The negotiated GSS-API mechanism
("pseudo negotiated" mechanism, because we
support just the krb5 mechanism :-))
:param str recv_token: The GSS-API token received from the Server
:raises:
`.SSHException` -- Is raised if the desired mechanism of the client
is not supported
:return: A ``String`` if the GSS-API has returned a token or
``None`` if no token was returned
"""
from pyasn1.codec.der import decoder
self._username = username
self._gss_host = target
targ_name = gssapi.Name(
"host@" + self._gss_host, gssapi.C_NT_HOSTBASED_SERVICE
)
ctx = gssapi.Context()
ctx.flags = self._gss_flags
if desired_mech is None:
krb5_mech = gssapi.OID.mech_from_string(self._krb5_mech)
else:
mech, __ = decoder.decode(desired_mech)
if mech.__str__() != self._krb5_mech:
raise SSHException("Unsupported mechanism OID.")
else:
krb5_mech = gssapi.OID.mech_from_string(self._krb5_mech)
token = None
try:
if recv_token is None:
self._gss_ctxt = gssapi.InitContext(
peer_name=targ_name,
mech_type=krb5_mech,
req_flags=ctx.flags,
)
token = self._gss_ctxt.step(token)
else:
token = self._gss_ctxt.step(recv_token)
except gssapi.GSSException:
message = "{} Target: {}".format(sys.exc_info()[1], self._gss_host)
raise gssapi.GSSException(message)
self._gss_ctxt_status = self._gss_ctxt.established
return token | python | def ssh_init_sec_context(
self, target, desired_mech=None, username=None, recv_token=None
):
"""
Initialize a GSS-API context.
:param str username: The name of the user who attempts to login
:param str target: The hostname of the target to connect to
:param str desired_mech: The negotiated GSS-API mechanism
("pseudo negotiated" mechanism, because we
support just the krb5 mechanism :-))
:param str recv_token: The GSS-API token received from the Server
:raises:
`.SSHException` -- Is raised if the desired mechanism of the client
is not supported
:return: A ``String`` if the GSS-API has returned a token or
``None`` if no token was returned
"""
from pyasn1.codec.der import decoder
self._username = username
self._gss_host = target
targ_name = gssapi.Name(
"host@" + self._gss_host, gssapi.C_NT_HOSTBASED_SERVICE
)
ctx = gssapi.Context()
ctx.flags = self._gss_flags
if desired_mech is None:
krb5_mech = gssapi.OID.mech_from_string(self._krb5_mech)
else:
mech, __ = decoder.decode(desired_mech)
if mech.__str__() != self._krb5_mech:
raise SSHException("Unsupported mechanism OID.")
else:
krb5_mech = gssapi.OID.mech_from_string(self._krb5_mech)
token = None
try:
if recv_token is None:
self._gss_ctxt = gssapi.InitContext(
peer_name=targ_name,
mech_type=krb5_mech,
req_flags=ctx.flags,
)
token = self._gss_ctxt.step(token)
else:
token = self._gss_ctxt.step(recv_token)
except gssapi.GSSException:
message = "{} Target: {}".format(sys.exc_info()[1], self._gss_host)
raise gssapi.GSSException(message)
self._gss_ctxt_status = self._gss_ctxt.established
return token | [
"def",
"ssh_init_sec_context",
"(",
"self",
",",
"target",
",",
"desired_mech",
"=",
"None",
",",
"username",
"=",
"None",
",",
"recv_token",
"=",
"None",
")",
":",
"from",
"pyasn1",
".",
"codec",
".",
"der",
"import",
"decoder",
"self",
".",
"_username",
"=",
"username",
"self",
".",
"_gss_host",
"=",
"target",
"targ_name",
"=",
"gssapi",
".",
"Name",
"(",
"\"host@\"",
"+",
"self",
".",
"_gss_host",
",",
"gssapi",
".",
"C_NT_HOSTBASED_SERVICE",
")",
"ctx",
"=",
"gssapi",
".",
"Context",
"(",
")",
"ctx",
".",
"flags",
"=",
"self",
".",
"_gss_flags",
"if",
"desired_mech",
"is",
"None",
":",
"krb5_mech",
"=",
"gssapi",
".",
"OID",
".",
"mech_from_string",
"(",
"self",
".",
"_krb5_mech",
")",
"else",
":",
"mech",
",",
"__",
"=",
"decoder",
".",
"decode",
"(",
"desired_mech",
")",
"if",
"mech",
".",
"__str__",
"(",
")",
"!=",
"self",
".",
"_krb5_mech",
":",
"raise",
"SSHException",
"(",
"\"Unsupported mechanism OID.\"",
")",
"else",
":",
"krb5_mech",
"=",
"gssapi",
".",
"OID",
".",
"mech_from_string",
"(",
"self",
".",
"_krb5_mech",
")",
"token",
"=",
"None",
"try",
":",
"if",
"recv_token",
"is",
"None",
":",
"self",
".",
"_gss_ctxt",
"=",
"gssapi",
".",
"InitContext",
"(",
"peer_name",
"=",
"targ_name",
",",
"mech_type",
"=",
"krb5_mech",
",",
"req_flags",
"=",
"ctx",
".",
"flags",
",",
")",
"token",
"=",
"self",
".",
"_gss_ctxt",
".",
"step",
"(",
"token",
")",
"else",
":",
"token",
"=",
"self",
".",
"_gss_ctxt",
".",
"step",
"(",
"recv_token",
")",
"except",
"gssapi",
".",
"GSSException",
":",
"message",
"=",
"\"{} Target: {}\"",
".",
"format",
"(",
"sys",
".",
"exc_info",
"(",
")",
"[",
"1",
"]",
",",
"self",
".",
"_gss_host",
")",
"raise",
"gssapi",
".",
"GSSException",
"(",
"message",
")",
"self",
".",
"_gss_ctxt_status",
"=",
"self",
".",
"_gss_ctxt",
".",
"established",
"return",
"token"
] | Initialize a GSS-API context.
:param str username: The name of the user who attempts to login
:param str target: The hostname of the target to connect to
:param str desired_mech: The negotiated GSS-API mechanism
("pseudo negotiated" mechanism, because we
support just the krb5 mechanism :-))
:param str recv_token: The GSS-API token received from the Server
:raises:
`.SSHException` -- Is raised if the desired mechanism of the client
is not supported
:return: A ``String`` if the GSS-API has returned a token or
``None`` if no token was returned | [
"Initialize",
"a",
"GSS",
"-",
"API",
"context",
"."
] | cf7d49d66f3b1fbc8b0853518a54050182b3b5eb | https://github.com/paramiko/paramiko/blob/cf7d49d66f3b1fbc8b0853518a54050182b3b5eb/paramiko/ssh_gss.py#L255-L305 | train |
paramiko/paramiko | paramiko/ssh_gss.py | _SSH_GSSAPI.ssh_accept_sec_context | def ssh_accept_sec_context(self, hostname, recv_token, username=None):
"""
Accept a GSS-API context (server mode).
:param str hostname: The servers hostname
:param str username: The name of the user who attempts to login
:param str recv_token: The GSS-API Token received from the server,
if it's not the initial call.
:return: A ``String`` if the GSS-API has returned a token or ``None``
if no token was returned
"""
# hostname and username are not required for GSSAPI, but for SSPI
self._gss_host = hostname
self._username = username
if self._gss_srv_ctxt is None:
self._gss_srv_ctxt = gssapi.AcceptContext()
token = self._gss_srv_ctxt.step(recv_token)
self._gss_srv_ctxt_status = self._gss_srv_ctxt.established
return token | python | def ssh_accept_sec_context(self, hostname, recv_token, username=None):
"""
Accept a GSS-API context (server mode).
:param str hostname: The servers hostname
:param str username: The name of the user who attempts to login
:param str recv_token: The GSS-API Token received from the server,
if it's not the initial call.
:return: A ``String`` if the GSS-API has returned a token or ``None``
if no token was returned
"""
# hostname and username are not required for GSSAPI, but for SSPI
self._gss_host = hostname
self._username = username
if self._gss_srv_ctxt is None:
self._gss_srv_ctxt = gssapi.AcceptContext()
token = self._gss_srv_ctxt.step(recv_token)
self._gss_srv_ctxt_status = self._gss_srv_ctxt.established
return token | [
"def",
"ssh_accept_sec_context",
"(",
"self",
",",
"hostname",
",",
"recv_token",
",",
"username",
"=",
"None",
")",
":",
"# hostname and username are not required for GSSAPI, but for SSPI",
"self",
".",
"_gss_host",
"=",
"hostname",
"self",
".",
"_username",
"=",
"username",
"if",
"self",
".",
"_gss_srv_ctxt",
"is",
"None",
":",
"self",
".",
"_gss_srv_ctxt",
"=",
"gssapi",
".",
"AcceptContext",
"(",
")",
"token",
"=",
"self",
".",
"_gss_srv_ctxt",
".",
"step",
"(",
"recv_token",
")",
"self",
".",
"_gss_srv_ctxt_status",
"=",
"self",
".",
"_gss_srv_ctxt",
".",
"established",
"return",
"token"
] | Accept a GSS-API context (server mode).
:param str hostname: The servers hostname
:param str username: The name of the user who attempts to login
:param str recv_token: The GSS-API Token received from the server,
if it's not the initial call.
:return: A ``String`` if the GSS-API has returned a token or ``None``
if no token was returned | [
"Accept",
"a",
"GSS",
"-",
"API",
"context",
"(",
"server",
"mode",
")",
"."
] | cf7d49d66f3b1fbc8b0853518a54050182b3b5eb | https://github.com/paramiko/paramiko/blob/cf7d49d66f3b1fbc8b0853518a54050182b3b5eb/paramiko/ssh_gss.py#L334-L352 | train |
paramiko/paramiko | paramiko/ssh_gss.py | _SSH_SSPI.ssh_init_sec_context | def ssh_init_sec_context(
self, target, desired_mech=None, username=None, recv_token=None
):
"""
Initialize a SSPI context.
:param str username: The name of the user who attempts to login
:param str target: The FQDN of the target to connect to
:param str desired_mech: The negotiated SSPI mechanism
("pseudo negotiated" mechanism, because we
support just the krb5 mechanism :-))
:param recv_token: The SSPI token received from the Server
:raises:
`.SSHException` -- Is raised if the desired mechanism of the client
is not supported
:return: A ``String`` if the SSPI has returned a token or ``None`` if
no token was returned
"""
from pyasn1.codec.der import decoder
self._username = username
self._gss_host = target
error = 0
targ_name = "host/" + self._gss_host
if desired_mech is not None:
mech, __ = decoder.decode(desired_mech)
if mech.__str__() != self._krb5_mech:
raise SSHException("Unsupported mechanism OID.")
try:
if recv_token is None:
self._gss_ctxt = sspi.ClientAuth(
"Kerberos", scflags=self._gss_flags, targetspn=targ_name
)
error, token = self._gss_ctxt.authorize(recv_token)
token = token[0].Buffer
except pywintypes.error as e:
e.strerror += ", Target: {}".format(e, self._gss_host)
raise
if error == 0:
"""
if the status is GSS_COMPLETE (error = 0) the context is fully
established an we can set _gss_ctxt_status to True.
"""
self._gss_ctxt_status = True
token = None
"""
You won't get another token if the context is fully established,
so i set token to None instead of ""
"""
return token | python | def ssh_init_sec_context(
self, target, desired_mech=None, username=None, recv_token=None
):
"""
Initialize a SSPI context.
:param str username: The name of the user who attempts to login
:param str target: The FQDN of the target to connect to
:param str desired_mech: The negotiated SSPI mechanism
("pseudo negotiated" mechanism, because we
support just the krb5 mechanism :-))
:param recv_token: The SSPI token received from the Server
:raises:
`.SSHException` -- Is raised if the desired mechanism of the client
is not supported
:return: A ``String`` if the SSPI has returned a token or ``None`` if
no token was returned
"""
from pyasn1.codec.der import decoder
self._username = username
self._gss_host = target
error = 0
targ_name = "host/" + self._gss_host
if desired_mech is not None:
mech, __ = decoder.decode(desired_mech)
if mech.__str__() != self._krb5_mech:
raise SSHException("Unsupported mechanism OID.")
try:
if recv_token is None:
self._gss_ctxt = sspi.ClientAuth(
"Kerberos", scflags=self._gss_flags, targetspn=targ_name
)
error, token = self._gss_ctxt.authorize(recv_token)
token = token[0].Buffer
except pywintypes.error as e:
e.strerror += ", Target: {}".format(e, self._gss_host)
raise
if error == 0:
"""
if the status is GSS_COMPLETE (error = 0) the context is fully
established an we can set _gss_ctxt_status to True.
"""
self._gss_ctxt_status = True
token = None
"""
You won't get another token if the context is fully established,
so i set token to None instead of ""
"""
return token | [
"def",
"ssh_init_sec_context",
"(",
"self",
",",
"target",
",",
"desired_mech",
"=",
"None",
",",
"username",
"=",
"None",
",",
"recv_token",
"=",
"None",
")",
":",
"from",
"pyasn1",
".",
"codec",
".",
"der",
"import",
"decoder",
"self",
".",
"_username",
"=",
"username",
"self",
".",
"_gss_host",
"=",
"target",
"error",
"=",
"0",
"targ_name",
"=",
"\"host/\"",
"+",
"self",
".",
"_gss_host",
"if",
"desired_mech",
"is",
"not",
"None",
":",
"mech",
",",
"__",
"=",
"decoder",
".",
"decode",
"(",
"desired_mech",
")",
"if",
"mech",
".",
"__str__",
"(",
")",
"!=",
"self",
".",
"_krb5_mech",
":",
"raise",
"SSHException",
"(",
"\"Unsupported mechanism OID.\"",
")",
"try",
":",
"if",
"recv_token",
"is",
"None",
":",
"self",
".",
"_gss_ctxt",
"=",
"sspi",
".",
"ClientAuth",
"(",
"\"Kerberos\"",
",",
"scflags",
"=",
"self",
".",
"_gss_flags",
",",
"targetspn",
"=",
"targ_name",
")",
"error",
",",
"token",
"=",
"self",
".",
"_gss_ctxt",
".",
"authorize",
"(",
"recv_token",
")",
"token",
"=",
"token",
"[",
"0",
"]",
".",
"Buffer",
"except",
"pywintypes",
".",
"error",
"as",
"e",
":",
"e",
".",
"strerror",
"+=",
"\", Target: {}\"",
".",
"format",
"(",
"e",
",",
"self",
".",
"_gss_host",
")",
"raise",
"if",
"error",
"==",
"0",
":",
"\"\"\"\n if the status is GSS_COMPLETE (error = 0) the context is fully\n established an we can set _gss_ctxt_status to True.\n \"\"\"",
"self",
".",
"_gss_ctxt_status",
"=",
"True",
"token",
"=",
"None",
"\"\"\"\n You won't get another token if the context is fully established,\n so i set token to None instead of \"\"\n \"\"\"",
"return",
"token"
] | Initialize a SSPI context.
:param str username: The name of the user who attempts to login
:param str target: The FQDN of the target to connect to
:param str desired_mech: The negotiated SSPI mechanism
("pseudo negotiated" mechanism, because we
support just the krb5 mechanism :-))
:param recv_token: The SSPI token received from the Server
:raises:
`.SSHException` -- Is raised if the desired mechanism of the client
is not supported
:return: A ``String`` if the SSPI has returned a token or ``None`` if
no token was returned | [
"Initialize",
"a",
"SSPI",
"context",
"."
] | cf7d49d66f3b1fbc8b0853518a54050182b3b5eb | https://github.com/paramiko/paramiko/blob/cf7d49d66f3b1fbc8b0853518a54050182b3b5eb/paramiko/ssh_gss.py#L431-L481 | train |
paramiko/paramiko | paramiko/ssh_gss.py | _SSH_SSPI.ssh_get_mic | def ssh_get_mic(self, session_id, gss_kex=False):
"""
Create the MIC token for a SSH2 message.
:param str session_id: The SSH session ID
:param bool gss_kex: Generate the MIC for Key Exchange with SSPI or not
:return: gssapi-with-mic:
Returns the MIC token from SSPI for the message we created
with ``_ssh_build_mic``.
gssapi-keyex:
Returns the MIC token from SSPI with the SSH session ID as
message.
"""
self._session_id = session_id
if not gss_kex:
mic_field = self._ssh_build_mic(
self._session_id,
self._username,
self._service,
self._auth_method,
)
mic_token = self._gss_ctxt.sign(mic_field)
else:
# for key exchange with gssapi-keyex
mic_token = self._gss_srv_ctxt.sign(self._session_id)
return mic_token | python | def ssh_get_mic(self, session_id, gss_kex=False):
"""
Create the MIC token for a SSH2 message.
:param str session_id: The SSH session ID
:param bool gss_kex: Generate the MIC for Key Exchange with SSPI or not
:return: gssapi-with-mic:
Returns the MIC token from SSPI for the message we created
with ``_ssh_build_mic``.
gssapi-keyex:
Returns the MIC token from SSPI with the SSH session ID as
message.
"""
self._session_id = session_id
if not gss_kex:
mic_field = self._ssh_build_mic(
self._session_id,
self._username,
self._service,
self._auth_method,
)
mic_token = self._gss_ctxt.sign(mic_field)
else:
# for key exchange with gssapi-keyex
mic_token = self._gss_srv_ctxt.sign(self._session_id)
return mic_token | [
"def",
"ssh_get_mic",
"(",
"self",
",",
"session_id",
",",
"gss_kex",
"=",
"False",
")",
":",
"self",
".",
"_session_id",
"=",
"session_id",
"if",
"not",
"gss_kex",
":",
"mic_field",
"=",
"self",
".",
"_ssh_build_mic",
"(",
"self",
".",
"_session_id",
",",
"self",
".",
"_username",
",",
"self",
".",
"_service",
",",
"self",
".",
"_auth_method",
",",
")",
"mic_token",
"=",
"self",
".",
"_gss_ctxt",
".",
"sign",
"(",
"mic_field",
")",
"else",
":",
"# for key exchange with gssapi-keyex",
"mic_token",
"=",
"self",
".",
"_gss_srv_ctxt",
".",
"sign",
"(",
"self",
".",
"_session_id",
")",
"return",
"mic_token"
] | Create the MIC token for a SSH2 message.
:param str session_id: The SSH session ID
:param bool gss_kex: Generate the MIC for Key Exchange with SSPI or not
:return: gssapi-with-mic:
Returns the MIC token from SSPI for the message we created
with ``_ssh_build_mic``.
gssapi-keyex:
Returns the MIC token from SSPI with the SSH session ID as
message. | [
"Create",
"the",
"MIC",
"token",
"for",
"a",
"SSH2",
"message",
"."
] | cf7d49d66f3b1fbc8b0853518a54050182b3b5eb | https://github.com/paramiko/paramiko/blob/cf7d49d66f3b1fbc8b0853518a54050182b3b5eb/paramiko/ssh_gss.py#L483-L508 | train |
paramiko/paramiko | paramiko/ssh_gss.py | _SSH_SSPI.ssh_accept_sec_context | 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,
if it's not the initial call.
:return: A ``String`` if the SSPI has returned a token or ``None`` if
no token was returned
"""
self._gss_host = hostname
self._username = username
targ_name = "host/" + self._gss_host
self._gss_srv_ctxt = sspi.ServerAuth("Kerberos", spn=targ_name)
error, token = self._gss_srv_ctxt.authorize(recv_token)
token = token[0].Buffer
if error == 0:
self._gss_srv_ctxt_status = True
token = None
return token | python | 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,
if it's not the initial call.
:return: A ``String`` if the SSPI has returned a token or ``None`` if
no token was returned
"""
self._gss_host = hostname
self._username = username
targ_name = "host/" + self._gss_host
self._gss_srv_ctxt = sspi.ServerAuth("Kerberos", spn=targ_name)
error, token = self._gss_srv_ctxt.authorize(recv_token)
token = token[0].Buffer
if error == 0:
self._gss_srv_ctxt_status = True
token = None
return token | [
"def",
"ssh_accept_sec_context",
"(",
"self",
",",
"hostname",
",",
"username",
",",
"recv_token",
")",
":",
"self",
".",
"_gss_host",
"=",
"hostname",
"self",
".",
"_username",
"=",
"username",
"targ_name",
"=",
"\"host/\"",
"+",
"self",
".",
"_gss_host",
"self",
".",
"_gss_srv_ctxt",
"=",
"sspi",
".",
"ServerAuth",
"(",
"\"Kerberos\"",
",",
"spn",
"=",
"targ_name",
")",
"error",
",",
"token",
"=",
"self",
".",
"_gss_srv_ctxt",
".",
"authorize",
"(",
"recv_token",
")",
"token",
"=",
"token",
"[",
"0",
"]",
".",
"Buffer",
"if",
"error",
"==",
"0",
":",
"self",
".",
"_gss_srv_ctxt_status",
"=",
"True",
"token",
"=",
"None",
"return",
"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,
if it's not the initial call.
:return: A ``String`` if the SSPI has returned a token or ``None`` if
no token was returned | [
"Accept",
"a",
"SSPI",
"context",
"(",
"server",
"mode",
")",
"."
] | cf7d49d66f3b1fbc8b0853518a54050182b3b5eb | https://github.com/paramiko/paramiko/blob/cf7d49d66f3b1fbc8b0853518a54050182b3b5eb/paramiko/ssh_gss.py#L510-L530 | train |
paramiko/paramiko | paramiko/ssh_gss.py | _SSH_SSPI.ssh_check_mic | 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
:return: None if the MIC check was successful
:raises: ``sspi.error`` -- if the MIC check failed
"""
self._session_id = session_id
self._username = username
if username is not None:
# server mode
mic_field = self._ssh_build_mic(
self._session_id,
self._username,
self._service,
self._auth_method,
)
# Verifies data and its signature. If verification fails, an
# sspi.error will be raised.
self._gss_srv_ctxt.verify(mic_field, mic_token)
else:
# for key exchange with gssapi-keyex
# client mode
# Verifies data and its signature. If verification fails, an
# sspi.error will be raised.
self._gss_ctxt.verify(self._session_id, mic_token) | python | 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
:return: None if the MIC check was successful
:raises: ``sspi.error`` -- if the MIC check failed
"""
self._session_id = session_id
self._username = username
if username is not None:
# server mode
mic_field = self._ssh_build_mic(
self._session_id,
self._username,
self._service,
self._auth_method,
)
# Verifies data and its signature. If verification fails, an
# sspi.error will be raised.
self._gss_srv_ctxt.verify(mic_field, mic_token)
else:
# for key exchange with gssapi-keyex
# client mode
# Verifies data and its signature. If verification fails, an
# sspi.error will be raised.
self._gss_ctxt.verify(self._session_id, mic_token) | [
"def",
"ssh_check_mic",
"(",
"self",
",",
"mic_token",
",",
"session_id",
",",
"username",
"=",
"None",
")",
":",
"self",
".",
"_session_id",
"=",
"session_id",
"self",
".",
"_username",
"=",
"username",
"if",
"username",
"is",
"not",
"None",
":",
"# server mode",
"mic_field",
"=",
"self",
".",
"_ssh_build_mic",
"(",
"self",
".",
"_session_id",
",",
"self",
".",
"_username",
",",
"self",
".",
"_service",
",",
"self",
".",
"_auth_method",
",",
")",
"# Verifies data and its signature. If verification fails, an",
"# sspi.error will be raised.",
"self",
".",
"_gss_srv_ctxt",
".",
"verify",
"(",
"mic_field",
",",
"mic_token",
")",
"else",
":",
"# for key exchange with gssapi-keyex",
"# client mode",
"# Verifies data and its signature. If verification fails, an",
"# sspi.error will be raised.",
"self",
".",
"_gss_ctxt",
".",
"verify",
"(",
"self",
".",
"_session_id",
",",
"mic_token",
")"
] | 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
:return: None if the MIC check was successful
:raises: ``sspi.error`` -- if the MIC check failed | [
"Verify",
"the",
"MIC",
"token",
"for",
"a",
"SSH2",
"message",
"."
] | cf7d49d66f3b1fbc8b0853518a54050182b3b5eb | https://github.com/paramiko/paramiko/blob/cf7d49d66f3b1fbc8b0853518a54050182b3b5eb/paramiko/ssh_gss.py#L532-L560 | train |
paramiko/paramiko | paramiko/ssh_gss.py | _SSH_SSPI.credentials_delegated | 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
) | python | 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
) | [
"def",
"credentials_delegated",
"(",
"self",
")",
":",
"return",
"self",
".",
"_gss_flags",
"&",
"sspicon",
".",
"ISC_REQ_DELEGATE",
"and",
"(",
"self",
".",
"_gss_srv_ctxt_status",
"or",
"self",
".",
"_gss_flags",
")"
] | Checks if credentials are delegated (server mode).
:return: ``True`` if credentials are delegated, otherwise ``False`` | [
"Checks",
"if",
"credentials",
"are",
"delegated",
"(",
"server",
"mode",
")",
"."
] | cf7d49d66f3b1fbc8b0853518a54050182b3b5eb | https://github.com/paramiko/paramiko/blob/cf7d49d66f3b1fbc8b0853518a54050182b3b5eb/paramiko/ssh_gss.py#L563-L571 | train |
paramiko/paramiko | paramiko/sftp_client.py | SFTPClient.from_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 should work adequately for both files transfers and
interactive sessions.
:param .Transport t: an open `.Transport` which is already
authenticated
:param int window_size:
optional window size for the `.SFTPClient` session.
:param int max_packet_size:
optional max packet size for the `.SFTPClient` session..
:return:
a new `.SFTPClient` object, referring to an sftp session (channel)
across the transport
.. versionchanged:: 1.15
Added the ``window_size`` and ``max_packet_size`` arguments.
"""
chan = t.open_session(
window_size=window_size, max_packet_size=max_packet_size
)
if chan is None:
return None
chan.invoke_subsystem("sftp")
return cls(chan) | python | 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 should work adequately for both files transfers and
interactive sessions.
:param .Transport t: an open `.Transport` which is already
authenticated
:param int window_size:
optional window size for the `.SFTPClient` session.
:param int max_packet_size:
optional max packet size for the `.SFTPClient` session..
:return:
a new `.SFTPClient` object, referring to an sftp session (channel)
across the transport
.. versionchanged:: 1.15
Added the ``window_size`` and ``max_packet_size`` arguments.
"""
chan = t.open_session(
window_size=window_size, max_packet_size=max_packet_size
)
if chan is None:
return None
chan.invoke_subsystem("sftp")
return cls(chan) | [
"def",
"from_transport",
"(",
"cls",
",",
"t",
",",
"window_size",
"=",
"None",
",",
"max_packet_size",
"=",
"None",
")",
":",
"chan",
"=",
"t",
".",
"open_session",
"(",
"window_size",
"=",
"window_size",
",",
"max_packet_size",
"=",
"max_packet_size",
")",
"if",
"chan",
"is",
"None",
":",
"return",
"None",
"chan",
".",
"invoke_subsystem",
"(",
"\"sftp\"",
")",
"return",
"cls",
"(",
"chan",
")"
] | 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 should work adequately for both files transfers and
interactive sessions.
:param .Transport t: an open `.Transport` which is already
authenticated
:param int window_size:
optional window size for the `.SFTPClient` session.
:param int max_packet_size:
optional max packet size for the `.SFTPClient` session..
:return:
a new `.SFTPClient` object, referring to an sftp session (channel)
across the transport
.. versionchanged:: 1.15
Added the ``window_size`` and ``max_packet_size`` arguments. | [
"Create",
"an",
"SFTP",
"client",
"channel",
"from",
"an",
"open",
".",
"Transport",
"."
] | cf7d49d66f3b1fbc8b0853518a54050182b3b5eb | https://github.com/paramiko/paramiko/blob/cf7d49d66f3b1fbc8b0853518a54050182b3b5eb/paramiko/sftp_client.py#L141-L170 | train |
paramiko/paramiko | paramiko/sftp_client.py | SFTPClient.listdir_iter | 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_READDIR`` requests are made to the server. The default of 50
should suffice for most file listings as each request/response cycle
may contain multiple files (dependent on server implementation.)
.. versionadded:: 1.15
"""
path = self._adjust_cwd(path)
self._log(DEBUG, "listdir({!r})".format(path))
t, msg = self._request(CMD_OPENDIR, path)
if t != CMD_HANDLE:
raise SFTPError("Expected handle")
handle = msg.get_string()
nums = list()
while True:
try:
# Send out a bunch of readdir requests so that we can read the
# responses later on Section 6.7 of the SSH file transfer RFC
# explains this
# http://filezilla-project.org/specs/draft-ietf-secsh-filexfer-02.txt
for i in range(read_aheads):
num = self._async_request(type(None), CMD_READDIR, handle)
nums.append(num)
# For each of our sent requests
# Read and parse the corresponding packets
# If we're at the end of our queued requests, then fire off
# some more requests
# Exit the loop when we've reached the end of the directory
# handle
for num in nums:
t, pkt_data = self._read_packet()
msg = Message(pkt_data)
new_num = msg.get_int()
if num == new_num:
if t == CMD_STATUS:
self._convert_status(msg)
count = msg.get_int()
for i in range(count):
filename = msg.get_text()
longname = msg.get_text()
attr = SFTPAttributes._from_msg(
msg, filename, longname
)
if (filename != ".") and (filename != ".."):
yield attr
# If we've hit the end of our queued requests, reset nums.
nums = list()
except EOFError:
self._request(CMD_CLOSE, handle)
return | python | 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_READDIR`` requests are made to the server. The default of 50
should suffice for most file listings as each request/response cycle
may contain multiple files (dependent on server implementation.)
.. versionadded:: 1.15
"""
path = self._adjust_cwd(path)
self._log(DEBUG, "listdir({!r})".format(path))
t, msg = self._request(CMD_OPENDIR, path)
if t != CMD_HANDLE:
raise SFTPError("Expected handle")
handle = msg.get_string()
nums = list()
while True:
try:
# Send out a bunch of readdir requests so that we can read the
# responses later on Section 6.7 of the SSH file transfer RFC
# explains this
# http://filezilla-project.org/specs/draft-ietf-secsh-filexfer-02.txt
for i in range(read_aheads):
num = self._async_request(type(None), CMD_READDIR, handle)
nums.append(num)
# For each of our sent requests
# Read and parse the corresponding packets
# If we're at the end of our queued requests, then fire off
# some more requests
# Exit the loop when we've reached the end of the directory
# handle
for num in nums:
t, pkt_data = self._read_packet()
msg = Message(pkt_data)
new_num = msg.get_int()
if num == new_num:
if t == CMD_STATUS:
self._convert_status(msg)
count = msg.get_int()
for i in range(count):
filename = msg.get_text()
longname = msg.get_text()
attr = SFTPAttributes._from_msg(
msg, filename, longname
)
if (filename != ".") and (filename != ".."):
yield attr
# If we've hit the end of our queued requests, reset nums.
nums = list()
except EOFError:
self._request(CMD_CLOSE, handle)
return | [
"def",
"listdir_iter",
"(",
"self",
",",
"path",
"=",
"\".\"",
",",
"read_aheads",
"=",
"50",
")",
":",
"path",
"=",
"self",
".",
"_adjust_cwd",
"(",
"path",
")",
"self",
".",
"_log",
"(",
"DEBUG",
",",
"\"listdir({!r})\"",
".",
"format",
"(",
"path",
")",
")",
"t",
",",
"msg",
"=",
"self",
".",
"_request",
"(",
"CMD_OPENDIR",
",",
"path",
")",
"if",
"t",
"!=",
"CMD_HANDLE",
":",
"raise",
"SFTPError",
"(",
"\"Expected handle\"",
")",
"handle",
"=",
"msg",
".",
"get_string",
"(",
")",
"nums",
"=",
"list",
"(",
")",
"while",
"True",
":",
"try",
":",
"# Send out a bunch of readdir requests so that we can read the",
"# responses later on Section 6.7 of the SSH file transfer RFC",
"# explains this",
"# http://filezilla-project.org/specs/draft-ietf-secsh-filexfer-02.txt",
"for",
"i",
"in",
"range",
"(",
"read_aheads",
")",
":",
"num",
"=",
"self",
".",
"_async_request",
"(",
"type",
"(",
"None",
")",
",",
"CMD_READDIR",
",",
"handle",
")",
"nums",
".",
"append",
"(",
"num",
")",
"# For each of our sent requests",
"# Read and parse the corresponding packets",
"# If we're at the end of our queued requests, then fire off",
"# some more requests",
"# Exit the loop when we've reached the end of the directory",
"# handle",
"for",
"num",
"in",
"nums",
":",
"t",
",",
"pkt_data",
"=",
"self",
".",
"_read_packet",
"(",
")",
"msg",
"=",
"Message",
"(",
"pkt_data",
")",
"new_num",
"=",
"msg",
".",
"get_int",
"(",
")",
"if",
"num",
"==",
"new_num",
":",
"if",
"t",
"==",
"CMD_STATUS",
":",
"self",
".",
"_convert_status",
"(",
"msg",
")",
"count",
"=",
"msg",
".",
"get_int",
"(",
")",
"for",
"i",
"in",
"range",
"(",
"count",
")",
":",
"filename",
"=",
"msg",
".",
"get_text",
"(",
")",
"longname",
"=",
"msg",
".",
"get_text",
"(",
")",
"attr",
"=",
"SFTPAttributes",
".",
"_from_msg",
"(",
"msg",
",",
"filename",
",",
"longname",
")",
"if",
"(",
"filename",
"!=",
"\".\"",
")",
"and",
"(",
"filename",
"!=",
"\"..\"",
")",
":",
"yield",
"attr",
"# If we've hit the end of our queued requests, reset nums.",
"nums",
"=",
"list",
"(",
")",
"except",
"EOFError",
":",
"self",
".",
"_request",
"(",
"CMD_CLOSE",
",",
"handle",
")",
"return"
] | 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_READDIR`` requests are made to the server. The default of 50
should suffice for most file listings as each request/response cycle
may contain multiple files (dependent on server implementation.)
.. versionadded:: 1.15 | [
"Generator",
"version",
"of",
".",
"listdir_attr",
"."
] | cf7d49d66f3b1fbc8b0853518a54050182b3b5eb | https://github.com/paramiko/paramiko/blob/cf7d49d66f3b1fbc8b0853518a54050182b3b5eb/paramiko/sftp_client.py#L262-L324 | train |
paramiko/paramiko | paramiko/sftp_client.py | SFTPClient.rename | 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`.
:param str oldpath:
existing name of the file or folder
:param str newpath:
new name for the file or folder, must not exist already
:raises:
``IOError`` -- if ``newpath`` is a folder, or something else goes
wrong
"""
oldpath = self._adjust_cwd(oldpath)
newpath = self._adjust_cwd(newpath)
self._log(DEBUG, "rename({!r}, {!r})".format(oldpath, newpath))
self._request(CMD_RENAME, oldpath, newpath) | python | 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`.
:param str oldpath:
existing name of the file or folder
:param str newpath:
new name for the file or folder, must not exist already
:raises:
``IOError`` -- if ``newpath`` is a folder, or something else goes
wrong
"""
oldpath = self._adjust_cwd(oldpath)
newpath = self._adjust_cwd(newpath)
self._log(DEBUG, "rename({!r}, {!r})".format(oldpath, newpath))
self._request(CMD_RENAME, oldpath, newpath) | [
"def",
"rename",
"(",
"self",
",",
"oldpath",
",",
"newpath",
")",
":",
"oldpath",
"=",
"self",
".",
"_adjust_cwd",
"(",
"oldpath",
")",
"newpath",
"=",
"self",
".",
"_adjust_cwd",
"(",
"newpath",
")",
"self",
".",
"_log",
"(",
"DEBUG",
",",
"\"rename({!r}, {!r})\"",
".",
"format",
"(",
"oldpath",
",",
"newpath",
")",
")",
"self",
".",
"_request",
"(",
"CMD_RENAME",
",",
"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`.
:param str oldpath:
existing name of the file or folder
:param str newpath:
new name for the file or folder, must not exist already
:raises:
``IOError`` -- if ``newpath`` is a folder, or something else goes
wrong | [
"Rename",
"a",
"file",
"or",
"folder",
"from",
"oldpath",
"to",
"newpath",
"."
] | cf7d49d66f3b1fbc8b0853518a54050182b3b5eb | https://github.com/paramiko/paramiko/blob/cf7d49d66f3b1fbc8b0853518a54050182b3b5eb/paramiko/sftp_client.py#L402-L423 | train |
paramiko/paramiko | paramiko/sftp_client.py | SFTPClient.posix_rename | 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 already exists
:raises:
``IOError`` -- if ``newpath`` is a folder, posix-rename is not
supported by the server or something else goes wrong
:versionadded: 2.2
"""
oldpath = self._adjust_cwd(oldpath)
newpath = self._adjust_cwd(newpath)
self._log(DEBUG, "posix_rename({!r}, {!r})".format(oldpath, newpath))
self._request(
CMD_EXTENDED, "posix-rename@openssh.com", oldpath, newpath
) | python | 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 already exists
:raises:
``IOError`` -- if ``newpath`` is a folder, posix-rename is not
supported by the server or something else goes wrong
:versionadded: 2.2
"""
oldpath = self._adjust_cwd(oldpath)
newpath = self._adjust_cwd(newpath)
self._log(DEBUG, "posix_rename({!r}, {!r})".format(oldpath, newpath))
self._request(
CMD_EXTENDED, "posix-rename@openssh.com", oldpath, newpath
) | [
"def",
"posix_rename",
"(",
"self",
",",
"oldpath",
",",
"newpath",
")",
":",
"oldpath",
"=",
"self",
".",
"_adjust_cwd",
"(",
"oldpath",
")",
"newpath",
"=",
"self",
".",
"_adjust_cwd",
"(",
"newpath",
")",
"self",
".",
"_log",
"(",
"DEBUG",
",",
"\"posix_rename({!r}, {!r})\"",
".",
"format",
"(",
"oldpath",
",",
"newpath",
")",
")",
"self",
".",
"_request",
"(",
"CMD_EXTENDED",
",",
"\"posix-rename@openssh.com\"",
",",
"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 already exists
:raises:
``IOError`` -- if ``newpath`` is a folder, posix-rename is not
supported by the server or something else goes wrong
:versionadded: 2.2 | [
"Rename",
"a",
"file",
"or",
"folder",
"from",
"oldpath",
"to",
"newpath",
"following",
"posix",
"conventions",
"."
] | cf7d49d66f3b1fbc8b0853518a54050182b3b5eb | https://github.com/paramiko/paramiko/blob/cf7d49d66f3b1fbc8b0853518a54050182b3b5eb/paramiko/sftp_client.py#L425-L445 | train |
paramiko/paramiko | paramiko/sftp_client.py | SFTPClient.mkdir | 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
:param int mode: permissions (posix-style) for the newly-created folder
"""
path = self._adjust_cwd(path)
self._log(DEBUG, "mkdir({!r}, {!r})".format(path, mode))
attr = SFTPAttributes()
attr.st_mode = mode
self._request(CMD_MKDIR, path, attr) | python | 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
:param int mode: permissions (posix-style) for the newly-created folder
"""
path = self._adjust_cwd(path)
self._log(DEBUG, "mkdir({!r}, {!r})".format(path, mode))
attr = SFTPAttributes()
attr.st_mode = mode
self._request(CMD_MKDIR, path, attr) | [
"def",
"mkdir",
"(",
"self",
",",
"path",
",",
"mode",
"=",
"o777",
")",
":",
"path",
"=",
"self",
".",
"_adjust_cwd",
"(",
"path",
")",
"self",
".",
"_log",
"(",
"DEBUG",
",",
"\"mkdir({!r}, {!r})\"",
".",
"format",
"(",
"path",
",",
"mode",
")",
")",
"attr",
"=",
"SFTPAttributes",
"(",
")",
"attr",
".",
"st_mode",
"=",
"mode",
"self",
".",
"_request",
"(",
"CMD_MKDIR",
",",
"path",
",",
"attr",
")"
] | 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
:param int mode: permissions (posix-style) for the newly-created folder | [
"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",
"."
] | cf7d49d66f3b1fbc8b0853518a54050182b3b5eb | https://github.com/paramiko/paramiko/blob/cf7d49d66f3b1fbc8b0853518a54050182b3b5eb/paramiko/sftp_client.py#L447-L460 | train |
paramiko/paramiko | paramiko/sftp_client.py | SFTPClient.symlink | 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}, {!r})".format(source, dest))
source = b(source)
self._request(CMD_SYMLINK, source, dest) | python | 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}, {!r})".format(source, dest))
source = b(source)
self._request(CMD_SYMLINK, source, dest) | [
"def",
"symlink",
"(",
"self",
",",
"source",
",",
"dest",
")",
":",
"dest",
"=",
"self",
".",
"_adjust_cwd",
"(",
"dest",
")",
"self",
".",
"_log",
"(",
"DEBUG",
",",
"\"symlink({!r}, {!r})\"",
".",
"format",
"(",
"source",
",",
"dest",
")",
")",
"source",
"=",
"b",
"(",
"source",
")",
"self",
".",
"_request",
"(",
"CMD_SYMLINK",
",",
"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 | [
"Create",
"a",
"symbolic",
"link",
"to",
"the",
"source",
"path",
"at",
"destination",
"."
] | cf7d49d66f3b1fbc8b0853518a54050182b3b5eb | https://github.com/paramiko/paramiko/blob/cf7d49d66f3b1fbc8b0853518a54050182b3b5eb/paramiko/sftp_client.py#L516-L526 | train |
paramiko/paramiko | paramiko/sftp_client.py | SFTPClient.chown | 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 path: path of the file to change the owner and group of
:param int uid: new owner's uid
:param int gid: new group id
"""
path = self._adjust_cwd(path)
self._log(DEBUG, "chown({!r}, {!r}, {!r})".format(path, uid, gid))
attr = SFTPAttributes()
attr.st_uid, attr.st_gid = uid, gid
self._request(CMD_SETSTAT, path, attr) | python | 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 path: path of the file to change the owner and group of
:param int uid: new owner's uid
:param int gid: new group id
"""
path = self._adjust_cwd(path)
self._log(DEBUG, "chown({!r}, {!r}, {!r})".format(path, uid, gid))
attr = SFTPAttributes()
attr.st_uid, attr.st_gid = uid, gid
self._request(CMD_SETSTAT, path, attr) | [
"def",
"chown",
"(",
"self",
",",
"path",
",",
"uid",
",",
"gid",
")",
":",
"path",
"=",
"self",
".",
"_adjust_cwd",
"(",
"path",
")",
"self",
".",
"_log",
"(",
"DEBUG",
",",
"\"chown({!r}, {!r}, {!r})\"",
".",
"format",
"(",
"path",
",",
"uid",
",",
"gid",
")",
")",
"attr",
"=",
"SFTPAttributes",
"(",
")",
"attr",
".",
"st_uid",
",",
"attr",
".",
"st_gid",
"=",
"uid",
",",
"gid",
"self",
".",
"_request",
"(",
"CMD_SETSTAT",
",",
"path",
",",
"attr",
")"
] | 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 path: path of the file to change the owner and group of
:param int uid: new owner's uid
:param int gid: new group id | [
"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",
"."
] | cf7d49d66f3b1fbc8b0853518a54050182b3b5eb | https://github.com/paramiko/paramiko/blob/cf7d49d66f3b1fbc8b0853518a54050182b3b5eb/paramiko/sftp_client.py#L543-L558 | train |
paramiko/paramiko | paramiko/sftp_client.py | SFTPClient.utime | 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)``, which is used to set the
access and modified times, respectively. This bizarre API is mimicked
from Python for the sake of consistency -- I apologize.
:param str path: path of the file to modify
:param tuple times:
``None`` or a tuple of (access time, modified time) in standard
internet epoch time (seconds since 01 January 1970 GMT)
"""
path = self._adjust_cwd(path)
if times is None:
times = (time.time(), time.time())
self._log(DEBUG, "utime({!r}, {!r})".format(path, times))
attr = SFTPAttributes()
attr.st_atime, attr.st_mtime = times
self._request(CMD_SETSTAT, path, attr) | python | 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)``, which is used to set the
access and modified times, respectively. This bizarre API is mimicked
from Python for the sake of consistency -- I apologize.
:param str path: path of the file to modify
:param tuple times:
``None`` or a tuple of (access time, modified time) in standard
internet epoch time (seconds since 01 January 1970 GMT)
"""
path = self._adjust_cwd(path)
if times is None:
times = (time.time(), time.time())
self._log(DEBUG, "utime({!r}, {!r})".format(path, times))
attr = SFTPAttributes()
attr.st_atime, attr.st_mtime = times
self._request(CMD_SETSTAT, path, attr) | [
"def",
"utime",
"(",
"self",
",",
"path",
",",
"times",
")",
":",
"path",
"=",
"self",
".",
"_adjust_cwd",
"(",
"path",
")",
"if",
"times",
"is",
"None",
":",
"times",
"=",
"(",
"time",
".",
"time",
"(",
")",
",",
"time",
".",
"time",
"(",
")",
")",
"self",
".",
"_log",
"(",
"DEBUG",
",",
"\"utime({!r}, {!r})\"",
".",
"format",
"(",
"path",
",",
"times",
")",
")",
"attr",
"=",
"SFTPAttributes",
"(",
")",
"attr",
".",
"st_atime",
",",
"attr",
".",
"st_mtime",
"=",
"times",
"self",
".",
"_request",
"(",
"CMD_SETSTAT",
",",
"path",
",",
"attr",
")"
] | 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 mimicked
from Python for the sake of consistency -- I apologize.
:param str path: path of the file to modify
:param tuple times:
``None`` or a tuple of (access time, modified time) in standard
internet epoch time (seconds since 01 January 1970 GMT) | [
"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",
"mimicked",
"from",
"Python",
"for",
"the",
"sake",
"of",
"consistency",
"--",
"I",
"apologize",
"."
] | cf7d49d66f3b1fbc8b0853518a54050182b3b5eb | https://github.com/paramiko/paramiko/blob/cf7d49d66f3b1fbc8b0853518a54050182b3b5eb/paramiko/sftp_client.py#L560-L580 | train |
paramiko/paramiko | paramiko/sftp_client.py | SFTPClient.truncate | 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 new size of the file
"""
path = self._adjust_cwd(path)
self._log(DEBUG, "truncate({!r}, {!r})".format(path, size))
attr = SFTPAttributes()
attr.st_size = size
self._request(CMD_SETSTAT, path, attr) | python | 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 new size of the file
"""
path = self._adjust_cwd(path)
self._log(DEBUG, "truncate({!r}, {!r})".format(path, size))
attr = SFTPAttributes()
attr.st_size = size
self._request(CMD_SETSTAT, path, attr) | [
"def",
"truncate",
"(",
"self",
",",
"path",
",",
"size",
")",
":",
"path",
"=",
"self",
".",
"_adjust_cwd",
"(",
"path",
")",
"self",
".",
"_log",
"(",
"DEBUG",
",",
"\"truncate({!r}, {!r})\"",
".",
"format",
"(",
"path",
",",
"size",
")",
")",
"attr",
"=",
"SFTPAttributes",
"(",
")",
"attr",
".",
"st_size",
"=",
"size",
"self",
".",
"_request",
"(",
"CMD_SETSTAT",
",",
"path",
",",
"attr",
")"
] | 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 new size of the file | [
"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",
"."
] | cf7d49d66f3b1fbc8b0853518a54050182b3b5eb | https://github.com/paramiko/paramiko/blob/cf7d49d66f3b1fbc8b0853518a54050182b3b5eb/paramiko/sftp_client.py#L582-L595 | train |
paramiko/paramiko | paramiko/sftp_client.py | SFTPClient.putfo | 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.
:param fl: opened file or file-like object to copy
:param str remotepath: the destination path on the SFTP server
:param int file_size:
optional size parameter passed to callback. If none is specified,
size defaults to 0
:param callable callback:
optional callback function (form: ``func(int, int)``) that accepts
the bytes transferred so far and the total bytes to be transferred
(since 1.7.4)
:param bool confirm:
whether to do a stat() on the file afterwards to confirm the file
size (since 1.7.7)
:return:
an `.SFTPAttributes` object containing attributes about the given
file.
.. versionadded:: 1.10
"""
with self.file(remotepath, "wb") as fr:
fr.set_pipelined(True)
size = self._transfer_with_callback(
reader=fl, writer=fr, file_size=file_size, callback=callback
)
if confirm:
s = self.stat(remotepath)
if s.st_size != size:
raise IOError(
"size mismatch in put! {} != {}".format(s.st_size, size)
)
else:
s = SFTPAttributes()
return s | python | 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.
:param fl: opened file or file-like object to copy
:param str remotepath: the destination path on the SFTP server
:param int file_size:
optional size parameter passed to callback. If none is specified,
size defaults to 0
:param callable callback:
optional callback function (form: ``func(int, int)``) that accepts
the bytes transferred so far and the total bytes to be transferred
(since 1.7.4)
:param bool confirm:
whether to do a stat() on the file afterwards to confirm the file
size (since 1.7.7)
:return:
an `.SFTPAttributes` object containing attributes about the given
file.
.. versionadded:: 1.10
"""
with self.file(remotepath, "wb") as fr:
fr.set_pipelined(True)
size = self._transfer_with_callback(
reader=fl, writer=fr, file_size=file_size, callback=callback
)
if confirm:
s = self.stat(remotepath)
if s.st_size != size:
raise IOError(
"size mismatch in put! {} != {}".format(s.st_size, size)
)
else:
s = SFTPAttributes()
return s | [
"def",
"putfo",
"(",
"self",
",",
"fl",
",",
"remotepath",
",",
"file_size",
"=",
"0",
",",
"callback",
"=",
"None",
",",
"confirm",
"=",
"True",
")",
":",
"with",
"self",
".",
"file",
"(",
"remotepath",
",",
"\"wb\"",
")",
"as",
"fr",
":",
"fr",
".",
"set_pipelined",
"(",
"True",
")",
"size",
"=",
"self",
".",
"_transfer_with_callback",
"(",
"reader",
"=",
"fl",
",",
"writer",
"=",
"fr",
",",
"file_size",
"=",
"file_size",
",",
"callback",
"=",
"callback",
")",
"if",
"confirm",
":",
"s",
"=",
"self",
".",
"stat",
"(",
"remotepath",
")",
"if",
"s",
".",
"st_size",
"!=",
"size",
":",
"raise",
"IOError",
"(",
"\"size mismatch in put! {} != {}\"",
".",
"format",
"(",
"s",
".",
"st_size",
",",
"size",
")",
")",
"else",
":",
"s",
"=",
"SFTPAttributes",
"(",
")",
"return",
"s"
] | 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.
:param fl: opened file or file-like object to copy
:param str remotepath: the destination path on the SFTP server
:param int file_size:
optional size parameter passed to callback. If none is specified,
size defaults to 0
:param callable callback:
optional callback function (form: ``func(int, int)``) that accepts
the bytes transferred so far and the total bytes to be transferred
(since 1.7.4)
:param bool confirm:
whether to do a stat() on the file afterwards to confirm the file
size (since 1.7.7)
:return:
an `.SFTPAttributes` object containing attributes about the given
file.
.. versionadded:: 1.10 | [
"Copy",
"the",
"contents",
"of",
"an",
"open",
"file",
"object",
"(",
"fl",
")",
"to",
"the",
"SFTP",
"server",
"as",
"remotepath",
".",
"Any",
"exception",
"raised",
"by",
"operations",
"will",
"be",
"passed",
"through",
"."
] | cf7d49d66f3b1fbc8b0853518a54050182b3b5eb | https://github.com/paramiko/paramiko/blob/cf7d49d66f3b1fbc8b0853518a54050182b3b5eb/paramiko/sftp_client.py#L687-L727 | train |
paramiko/paramiko | paramiko/sftp_client.py | SFTPClient.put | 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 pipelining for speed.
:param str localpath: the local file to copy
:param str remotepath: the destination path on the SFTP server. Note
that the filename should be included. Only specifying a directory
may result in an error.
:param callable callback:
optional callback function (form: ``func(int, int)``) that accepts
the bytes transferred so far and the total bytes to be transferred
:param bool confirm:
whether to do a stat() on the file afterwards to confirm the file
size
:return: an `.SFTPAttributes` object containing attributes about the
given file
.. versionadded:: 1.4
.. versionchanged:: 1.7.4
``callback`` and rich attribute return value added.
.. versionchanged:: 1.7.7
``confirm`` param added.
"""
file_size = os.stat(localpath).st_size
with open(localpath, "rb") as fl:
return self.putfo(fl, remotepath, file_size, callback, confirm) | python | 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 pipelining for speed.
:param str localpath: the local file to copy
:param str remotepath: the destination path on the SFTP server. Note
that the filename should be included. Only specifying a directory
may result in an error.
:param callable callback:
optional callback function (form: ``func(int, int)``) that accepts
the bytes transferred so far and the total bytes to be transferred
:param bool confirm:
whether to do a stat() on the file afterwards to confirm the file
size
:return: an `.SFTPAttributes` object containing attributes about the
given file
.. versionadded:: 1.4
.. versionchanged:: 1.7.4
``callback`` and rich attribute return value added.
.. versionchanged:: 1.7.7
``confirm`` param added.
"""
file_size = os.stat(localpath).st_size
with open(localpath, "rb") as fl:
return self.putfo(fl, remotepath, file_size, callback, confirm) | [
"def",
"put",
"(",
"self",
",",
"localpath",
",",
"remotepath",
",",
"callback",
"=",
"None",
",",
"confirm",
"=",
"True",
")",
":",
"file_size",
"=",
"os",
".",
"stat",
"(",
"localpath",
")",
".",
"st_size",
"with",
"open",
"(",
"localpath",
",",
"\"rb\"",
")",
"as",
"fl",
":",
"return",
"self",
".",
"putfo",
"(",
"fl",
",",
"remotepath",
",",
"file_size",
",",
"callback",
",",
"confirm",
")"
] | 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 pipelining for speed.
:param str localpath: the local file to copy
:param str remotepath: the destination path on the SFTP server. Note
that the filename should be included. Only specifying a directory
may result in an error.
:param callable callback:
optional callback function (form: ``func(int, int)``) that accepts
the bytes transferred so far and the total bytes to be transferred
:param bool confirm:
whether to do a stat() on the file afterwards to confirm the file
size
:return: an `.SFTPAttributes` object containing attributes about the
given file
.. versionadded:: 1.4
.. versionchanged:: 1.7.4
``callback`` and rich attribute return value added.
.. versionchanged:: 1.7.7
``confirm`` param added. | [
"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",
"."
] | cf7d49d66f3b1fbc8b0853518a54050182b3b5eb | https://github.com/paramiko/paramiko/blob/cf7d49d66f3b1fbc8b0853518a54050182b3b5eb/paramiko/sftp_client.py#L729-L759 | train |
paramiko/paramiko | paramiko/sftp_client.py | SFTPClient.getfo | 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.
:param object remotepath: opened file or file-like object to copy to
:param str fl:
the destination path on the local host or open file object
:param callable callback:
optional callback function (form: ``func(int, int)``) that accepts
the bytes transferred so far and the total bytes to be transferred
:return: the `number <int>` of bytes written to the opened file object
.. versionadded:: 1.10
"""
file_size = self.stat(remotepath).st_size
with self.open(remotepath, "rb") as fr:
fr.prefetch(file_size)
return self._transfer_with_callback(
reader=fr, writer=fl, file_size=file_size, callback=callback
) | python | 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.
:param object remotepath: opened file or file-like object to copy to
:param str fl:
the destination path on the local host or open file object
:param callable callback:
optional callback function (form: ``func(int, int)``) that accepts
the bytes transferred so far and the total bytes to be transferred
:return: the `number <int>` of bytes written to the opened file object
.. versionadded:: 1.10
"""
file_size = self.stat(remotepath).st_size
with self.open(remotepath, "rb") as fr:
fr.prefetch(file_size)
return self._transfer_with_callback(
reader=fr, writer=fl, file_size=file_size, callback=callback
) | [
"def",
"getfo",
"(",
"self",
",",
"remotepath",
",",
"fl",
",",
"callback",
"=",
"None",
")",
":",
"file_size",
"=",
"self",
".",
"stat",
"(",
"remotepath",
")",
".",
"st_size",
"with",
"self",
".",
"open",
"(",
"remotepath",
",",
"\"rb\"",
")",
"as",
"fr",
":",
"fr",
".",
"prefetch",
"(",
"file_size",
")",
"return",
"self",
".",
"_transfer_with_callback",
"(",
"reader",
"=",
"fr",
",",
"writer",
"=",
"fl",
",",
"file_size",
"=",
"file_size",
",",
"callback",
"=",
"callback",
")"
] | 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.
:param object remotepath: opened file or file-like object to copy to
:param str fl:
the destination path on the local host or open file object
:param callable callback:
optional callback function (form: ``func(int, int)``) that accepts
the bytes transferred so far and the total bytes to be transferred
:return: the `number <int>` of bytes written to the opened file object
.. versionadded:: 1.10 | [
"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",
"."
] | cf7d49d66f3b1fbc8b0853518a54050182b3b5eb | https://github.com/paramiko/paramiko/blob/cf7d49d66f3b1fbc8b0853518a54050182b3b5eb/paramiko/sftp_client.py#L761-L783 | train |
paramiko/paramiko | paramiko/sftp_client.py | SFTPClient.get | 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 remotepath: the remote file to copy
:param str localpath: the destination path on the local host
:param callable callback:
optional callback function (form: ``func(int, int)``) that accepts
the bytes transferred so far and the total bytes to be transferred
.. versionadded:: 1.4
.. versionchanged:: 1.7.4
Added the ``callback`` param
"""
with open(localpath, "wb") as fl:
size = self.getfo(remotepath, fl, callback)
s = os.stat(localpath)
if s.st_size != size:
raise IOError(
"size mismatch in get! {} != {}".format(s.st_size, size)
) | python | 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 remotepath: the remote file to copy
:param str localpath: the destination path on the local host
:param callable callback:
optional callback function (form: ``func(int, int)``) that accepts
the bytes transferred so far and the total bytes to be transferred
.. versionadded:: 1.4
.. versionchanged:: 1.7.4
Added the ``callback`` param
"""
with open(localpath, "wb") as fl:
size = self.getfo(remotepath, fl, callback)
s = os.stat(localpath)
if s.st_size != size:
raise IOError(
"size mismatch in get! {} != {}".format(s.st_size, size)
) | [
"def",
"get",
"(",
"self",
",",
"remotepath",
",",
"localpath",
",",
"callback",
"=",
"None",
")",
":",
"with",
"open",
"(",
"localpath",
",",
"\"wb\"",
")",
"as",
"fl",
":",
"size",
"=",
"self",
".",
"getfo",
"(",
"remotepath",
",",
"fl",
",",
"callback",
")",
"s",
"=",
"os",
".",
"stat",
"(",
"localpath",
")",
"if",
"s",
".",
"st_size",
"!=",
"size",
":",
"raise",
"IOError",
"(",
"\"size mismatch in get! {} != {}\"",
".",
"format",
"(",
"s",
".",
"st_size",
",",
"size",
")",
")"
] | 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 remotepath: the remote file to copy
:param str localpath: the destination path on the local host
:param callable callback:
optional callback function (form: ``func(int, int)``) that accepts
the bytes transferred so far and the total bytes to be transferred
.. versionadded:: 1.4
.. versionchanged:: 1.7.4
Added the ``callback`` param | [
"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",
"."
] | cf7d49d66f3b1fbc8b0853518a54050182b3b5eb | https://github.com/paramiko/paramiko/blob/cf7d49d66f3b1fbc8b0853518a54050182b3b5eb/paramiko/sftp_client.py#L785-L807 | train |
paramiko/paramiko | paramiko/sftp_client.py | SFTPClient._convert_status | 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 == SFTP_NO_SUCH_FILE:
# clever idea from john a. meinel: map the error codes to errno
raise IOError(errno.ENOENT, text)
elif code == SFTP_PERMISSION_DENIED:
raise IOError(errno.EACCES, text)
else:
raise IOError(text) | python | 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 == SFTP_NO_SUCH_FILE:
# clever idea from john a. meinel: map the error codes to errno
raise IOError(errno.ENOENT, text)
elif code == SFTP_PERMISSION_DENIED:
raise IOError(errno.EACCES, text)
else:
raise IOError(text) | [
"def",
"_convert_status",
"(",
"self",
",",
"msg",
")",
":",
"code",
"=",
"msg",
".",
"get_int",
"(",
")",
"text",
"=",
"msg",
".",
"get_text",
"(",
")",
"if",
"code",
"==",
"SFTP_OK",
":",
"return",
"elif",
"code",
"==",
"SFTP_EOF",
":",
"raise",
"EOFError",
"(",
"text",
")",
"elif",
"code",
"==",
"SFTP_NO_SUCH_FILE",
":",
"# clever idea from john a. meinel: map the error codes to errno",
"raise",
"IOError",
"(",
"errno",
".",
"ENOENT",
",",
"text",
")",
"elif",
"code",
"==",
"SFTP_PERMISSION_DENIED",
":",
"raise",
"IOError",
"(",
"errno",
".",
"EACCES",
",",
"text",
")",
"else",
":",
"raise",
"IOError",
"(",
"text",
")"
] | Raises EOFError or IOError on error status; otherwise does nothing. | [
"Raises",
"EOFError",
"or",
"IOError",
"on",
"error",
"status",
";",
"otherwise",
"does",
"nothing",
"."
] | cf7d49d66f3b1fbc8b0853518a54050182b3b5eb | https://github.com/paramiko/paramiko/blob/cf7d49d66f3b1fbc8b0853518a54050182b3b5eb/paramiko/sftp_client.py#L882-L898 | train |
paramiko/paramiko | paramiko/sftp_client.py | SFTPClient._adjust_cwd | 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
return path
if self._cwd == b_slash:
return self._cwd + path
return self._cwd + b_slash + path | python | 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
return path
if self._cwd == b_slash:
return self._cwd + path
return self._cwd + b_slash + path | [
"def",
"_adjust_cwd",
"(",
"self",
",",
"path",
")",
":",
"path",
"=",
"b",
"(",
"path",
")",
"if",
"self",
".",
"_cwd",
"is",
"None",
":",
"return",
"path",
"if",
"len",
"(",
"path",
")",
"and",
"path",
"[",
"0",
":",
"1",
"]",
"==",
"b_slash",
":",
"# absolute path",
"return",
"path",
"if",
"self",
".",
"_cwd",
"==",
"b_slash",
":",
"return",
"self",
".",
"_cwd",
"+",
"path",
"return",
"self",
".",
"_cwd",
"+",
"b_slash",
"+",
"path"
] | Return an adjusted path if we're emulating a "current working
directory" for the server. | [
"Return",
"an",
"adjusted",
"path",
"if",
"we",
"re",
"emulating",
"a",
"current",
"working",
"directory",
"for",
"the",
"server",
"."
] | cf7d49d66f3b1fbc8b0853518a54050182b3b5eb | https://github.com/paramiko/paramiko/blob/cf7d49d66f3b1fbc8b0853518a54050182b3b5eb/paramiko/sftp_client.py#L900-L913 | train |
paramiko/paramiko | tasks.py | coverage | def coverage(ctx, opts=""):
"""
Execute all tests (normal and slow) with coverage enabled.
"""
return test(ctx, coverage=True, include_slow=True, opts=opts) | python | def coverage(ctx, opts=""):
"""
Execute all tests (normal and slow) with coverage enabled.
"""
return test(ctx, coverage=True, include_slow=True, opts=opts) | [
"def",
"coverage",
"(",
"ctx",
",",
"opts",
"=",
"\"\"",
")",
":",
"return",
"test",
"(",
"ctx",
",",
"coverage",
"=",
"True",
",",
"include_slow",
"=",
"True",
",",
"opts",
"=",
"opts",
")"
] | Execute all tests (normal and slow) with coverage enabled. | [
"Execute",
"all",
"tests",
"(",
"normal",
"and",
"slow",
")",
"with",
"coverage",
"enabled",
"."
] | cf7d49d66f3b1fbc8b0853518a54050182b3b5eb | https://github.com/paramiko/paramiko/blob/cf7d49d66f3b1fbc8b0853518a54050182b3b5eb/tasks.py#L78-L82 | train |
paramiko/paramiko | tasks.py | guard | 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) | python | 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) | [
"def",
"guard",
"(",
"ctx",
",",
"opts",
"=",
"\"\"",
")",
":",
"# 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",
")"
] | Execute all tests and then watch for changes, re-running. | [
"Execute",
"all",
"tests",
"and",
"then",
"watch",
"for",
"changes",
"re",
"-",
"running",
"."
] | cf7d49d66f3b1fbc8b0853518a54050182b3b5eb | https://github.com/paramiko/paramiko/blob/cf7d49d66f3b1fbc8b0853518a54050182b3b5eb/tasks.py#L86-L91 | train |
paramiko/paramiko | tasks.py | release | 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 Epydocs used to live
target = "docs"
rmtree(target, ignore_errors=True)
# TODO: make it easier to yank out this config val from the docs coll
copytree("sites/docs/_build", target)
# Publish
publish(
ctx, sdist=sdist, wheel=wheel, sign=sign, dry_run=dry_run, index=index
)
# Remind
print(
"\n\nDon't forget to update RTD's versions page for new minor "
"releases!"
) | python | 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 Epydocs used to live
target = "docs"
rmtree(target, ignore_errors=True)
# TODO: make it easier to yank out this config val from the docs coll
copytree("sites/docs/_build", target)
# Publish
publish(
ctx, sdist=sdist, wheel=wheel, sign=sign, dry_run=dry_run, index=index
)
# Remind
print(
"\n\nDon't forget to update RTD's versions page for new minor "
"releases!"
) | [
"def",
"release",
"(",
"ctx",
",",
"sdist",
"=",
"True",
",",
"wheel",
"=",
"True",
",",
"sign",
"=",
"True",
",",
"dry_run",
"=",
"False",
",",
"index",
"=",
"None",
")",
":",
"# Build docs first. Use terribad workaround pending invoke #146",
"ctx",
".",
"run",
"(",
"\"inv docs\"",
",",
"pty",
"=",
"True",
",",
"hide",
"=",
"False",
")",
"# Move the built docs into where Epydocs used to live",
"target",
"=",
"\"docs\"",
"rmtree",
"(",
"target",
",",
"ignore_errors",
"=",
"True",
")",
"# TODO: make it easier to yank out this config val from the docs coll",
"copytree",
"(",
"\"sites/docs/_build\"",
",",
"target",
")",
"# Publish",
"publish",
"(",
"ctx",
",",
"sdist",
"=",
"sdist",
",",
"wheel",
"=",
"wheel",
",",
"sign",
"=",
"sign",
",",
"dry_run",
"=",
"dry_run",
",",
"index",
"=",
"index",
")",
"# Remind",
"print",
"(",
"\"\\n\\nDon't forget to update RTD's versions page for new minor \"",
"\"releases!\"",
")"
] | Wraps invocations.packaging.publish to add baked-in docs folder. | [
"Wraps",
"invocations",
".",
"packaging",
".",
"publish",
"to",
"add",
"baked",
"-",
"in",
"docs",
"folder",
"."
] | cf7d49d66f3b1fbc8b0853518a54050182b3b5eb | https://github.com/paramiko/paramiko/blob/cf7d49d66f3b1fbc8b0853518a54050182b3b5eb/tasks.py#L98-L117 | train |
paramiko/paramiko | paramiko/transport.py | Transport.set_gss_host | 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 Kerberos database.) Defaults to
``self.hostname`` (which will be the 'real' target hostname and/or
host portion of given socket object.)
:param bool trust_dns:
Indicates whether or not DNS is trusted; if true, DNS will be used
to canonicalize the GSS hostname (which again will either be
``gss_host`` or the transport's default hostname.)
(Defaults to True due to backwards compatibility.)
:param bool gssapi_requested:
Whether GSSAPI key exchange or authentication was even requested.
If not, this is a no-op and nothing happens
(and ``self.gss_host`` is not set.)
(Defaults to True due to backwards compatibility.)
:returns: ``None``.
"""
# No GSSAPI in play == nothing to do
if not gssapi_requested:
return
# Obtain the correct host first - did user request a GSS-specific name
# to use that is distinct from the actual SSH target hostname?
if gss_host is None:
gss_host = self.hostname
# Finally, canonicalize via DNS if DNS is trusted.
if trust_dns and gss_host is not None:
gss_host = socket.getfqdn(gss_host)
# And set attribute for reference later.
self.gss_host = gss_host | python | 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 Kerberos database.) Defaults to
``self.hostname`` (which will be the 'real' target hostname and/or
host portion of given socket object.)
:param bool trust_dns:
Indicates whether or not DNS is trusted; if true, DNS will be used
to canonicalize the GSS hostname (which again will either be
``gss_host`` or the transport's default hostname.)
(Defaults to True due to backwards compatibility.)
:param bool gssapi_requested:
Whether GSSAPI key exchange or authentication was even requested.
If not, this is a no-op and nothing happens
(and ``self.gss_host`` is not set.)
(Defaults to True due to backwards compatibility.)
:returns: ``None``.
"""
# No GSSAPI in play == nothing to do
if not gssapi_requested:
return
# Obtain the correct host first - did user request a GSS-specific name
# to use that is distinct from the actual SSH target hostname?
if gss_host is None:
gss_host = self.hostname
# Finally, canonicalize via DNS if DNS is trusted.
if trust_dns and gss_host is not None:
gss_host = socket.getfqdn(gss_host)
# And set attribute for reference later.
self.gss_host = gss_host | [
"def",
"set_gss_host",
"(",
"self",
",",
"gss_host",
",",
"trust_dns",
"=",
"True",
",",
"gssapi_requested",
"=",
"True",
")",
":",
"# No GSSAPI in play == nothing to do",
"if",
"not",
"gssapi_requested",
":",
"return",
"# Obtain the correct host first - did user request a GSS-specific name",
"# to use that is distinct from the actual SSH target hostname?",
"if",
"gss_host",
"is",
"None",
":",
"gss_host",
"=",
"self",
".",
"hostname",
"# Finally, canonicalize via DNS if DNS is trusted.",
"if",
"trust_dns",
"and",
"gss_host",
"is",
"not",
"None",
":",
"gss_host",
"=",
"socket",
".",
"getfqdn",
"(",
"gss_host",
")",
"# And set attribute for reference later.",
"self",
".",
"gss_host",
"=",
"gss_host"
] | 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 Kerberos database.) Defaults to
``self.hostname`` (which will be the 'real' target hostname and/or
host portion of given socket object.)
:param bool trust_dns:
Indicates whether or not DNS is trusted; if true, DNS will be used
to canonicalize the GSS hostname (which again will either be
``gss_host`` or the transport's default hostname.)
(Defaults to True due to backwards compatibility.)
:param bool gssapi_requested:
Whether GSSAPI key exchange or authentication was even requested.
If not, this is a no-op and nothing happens
(and ``self.gss_host`` is not set.)
(Defaults to True due to backwards compatibility.)
:returns: ``None``. | [
"Normalize",
"/",
"canonicalize",
"self",
".",
"gss_host",
"depending",
"on",
"various",
"factors",
"."
] | cf7d49d66f3b1fbc8b0853518a54050182b3b5eb | https://github.com/paramiko/paramiko/blob/cf7d49d66f3b1fbc8b0853518a54050182b3b5eb/paramiko/transport.py#L502-L534 | train |
paramiko/paramiko | paramiko/transport.py | Transport.start_client | 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
negotiation is done (successful or not), the given ``Event`` will
be triggered. On failure, `is_active` will return ``False``.
(Since 1.4) If ``event`` is ``None``, this method will not return until
negotiation is done. On success, the method returns normally.
Otherwise an SSHException is raised.
After a successful negotiation, you will usually want to authenticate,
calling `auth_password <Transport.auth_password>` or
`auth_publickey <Transport.auth_publickey>`.
.. note:: `connect` is a simpler method for connecting as a client.
.. note::
After calling this method (or `start_server` or `connect`), you
should no longer directly read from or write to the original socket
object.
:param .threading.Event event:
an event to trigger when negotiation is complete (optional)
:param float timeout:
a timeout, in seconds, for SSH2 session negotiation (optional)
:raises:
`.SSHException` -- if negotiation fails (and no ``event`` was
passed in)
"""
self.active = True
if event is not None:
# async, return immediately and let the app poll for completion
self.completion_event = event
self.start()
return
# synchronous, wait for a result
self.completion_event = event = threading.Event()
self.start()
max_time = time.time() + timeout if timeout is not None else None
while True:
event.wait(0.1)
if not self.active:
e = self.get_exception()
if e is not None:
raise e
raise SSHException("Negotiation failed.")
if event.is_set() or (
timeout is not None and time.time() >= max_time
):
break | python | 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
negotiation is done (successful or not), the given ``Event`` will
be triggered. On failure, `is_active` will return ``False``.
(Since 1.4) If ``event`` is ``None``, this method will not return until
negotiation is done. On success, the method returns normally.
Otherwise an SSHException is raised.
After a successful negotiation, you will usually want to authenticate,
calling `auth_password <Transport.auth_password>` or
`auth_publickey <Transport.auth_publickey>`.
.. note:: `connect` is a simpler method for connecting as a client.
.. note::
After calling this method (or `start_server` or `connect`), you
should no longer directly read from or write to the original socket
object.
:param .threading.Event event:
an event to trigger when negotiation is complete (optional)
:param float timeout:
a timeout, in seconds, for SSH2 session negotiation (optional)
:raises:
`.SSHException` -- if negotiation fails (and no ``event`` was
passed in)
"""
self.active = True
if event is not None:
# async, return immediately and let the app poll for completion
self.completion_event = event
self.start()
return
# synchronous, wait for a result
self.completion_event = event = threading.Event()
self.start()
max_time = time.time() + timeout if timeout is not None else None
while True:
event.wait(0.1)
if not self.active:
e = self.get_exception()
if e is not None:
raise e
raise SSHException("Negotiation failed.")
if event.is_set() or (
timeout is not None and time.time() >= max_time
):
break | [
"def",
"start_client",
"(",
"self",
",",
"event",
"=",
"None",
",",
"timeout",
"=",
"None",
")",
":",
"self",
".",
"active",
"=",
"True",
"if",
"event",
"is",
"not",
"None",
":",
"# async, return immediately and let the app poll for completion",
"self",
".",
"completion_event",
"=",
"event",
"self",
".",
"start",
"(",
")",
"return",
"# synchronous, wait for a result",
"self",
".",
"completion_event",
"=",
"event",
"=",
"threading",
".",
"Event",
"(",
")",
"self",
".",
"start",
"(",
")",
"max_time",
"=",
"time",
".",
"time",
"(",
")",
"+",
"timeout",
"if",
"timeout",
"is",
"not",
"None",
"else",
"None",
"while",
"True",
":",
"event",
".",
"wait",
"(",
"0.1",
")",
"if",
"not",
"self",
".",
"active",
":",
"e",
"=",
"self",
".",
"get_exception",
"(",
")",
"if",
"e",
"is",
"not",
"None",
":",
"raise",
"e",
"raise",
"SSHException",
"(",
"\"Negotiation failed.\"",
")",
"if",
"event",
".",
"is_set",
"(",
")",
"or",
"(",
"timeout",
"is",
"not",
"None",
"and",
"time",
".",
"time",
"(",
")",
">=",
"max_time",
")",
":",
"break"
] | 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
negotiation is done (successful or not), the given ``Event`` will
be triggered. On failure, `is_active` will return ``False``.
(Since 1.4) If ``event`` is ``None``, this method will not return until
negotiation is done. On success, the method returns normally.
Otherwise an SSHException is raised.
After a successful negotiation, you will usually want to authenticate,
calling `auth_password <Transport.auth_password>` or
`auth_publickey <Transport.auth_publickey>`.
.. note:: `connect` is a simpler method for connecting as a client.
.. note::
After calling this method (or `start_server` or `connect`), you
should no longer directly read from or write to the original socket
object.
:param .threading.Event event:
an event to trigger when negotiation is complete (optional)
:param float timeout:
a timeout, in seconds, for SSH2 session negotiation (optional)
:raises:
`.SSHException` -- if negotiation fails (and no ``event`` was
passed in) | [
"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",
"."
] | cf7d49d66f3b1fbc8b0853518a54050182b3b5eb | https://github.com/paramiko/paramiko/blob/cf7d49d66f3b1fbc8b0853518a54050182b3b5eb/paramiko/transport.py#L536-L592 | train |
paramiko/paramiko | paramiko/transport.py | Transport.load_server_moduli | 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
negotiation, which asks the server to send a random prime number that
fits certain criteria. These primes are pretty difficult to compute,
so they can't be generated on demand. But many systems contain a file
of suitable primes (usually named something like ``/etc/ssh/moduli``).
If you call `load_server_moduli` and it returns ``True``, then this
file of primes has been loaded and we will support "group-exchange" in
server mode. Otherwise server mode will just claim that it doesn't
support that method of key negotiation.
:param str filename:
optional path to the moduli file, if you happen to know that it's
not in a standard location.
:return:
True if a moduli file was successfully loaded; False otherwise.
.. note:: This has no effect when used in client mode.
"""
Transport._modulus_pack = ModulusPack()
# places to look for the openssh "moduli" file
file_list = ["/etc/ssh/moduli", "/usr/local/etc/moduli"]
if filename is not None:
file_list.insert(0, filename)
for fn in file_list:
try:
Transport._modulus_pack.read_file(fn)
return True
except IOError:
pass
# none succeeded
Transport._modulus_pack = None
return False | python | 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
negotiation, which asks the server to send a random prime number that
fits certain criteria. These primes are pretty difficult to compute,
so they can't be generated on demand. But many systems contain a file
of suitable primes (usually named something like ``/etc/ssh/moduli``).
If you call `load_server_moduli` and it returns ``True``, then this
file of primes has been loaded and we will support "group-exchange" in
server mode. Otherwise server mode will just claim that it doesn't
support that method of key negotiation.
:param str filename:
optional path to the moduli file, if you happen to know that it's
not in a standard location.
:return:
True if a moduli file was successfully loaded; False otherwise.
.. note:: This has no effect when used in client mode.
"""
Transport._modulus_pack = ModulusPack()
# places to look for the openssh "moduli" file
file_list = ["/etc/ssh/moduli", "/usr/local/etc/moduli"]
if filename is not None:
file_list.insert(0, filename)
for fn in file_list:
try:
Transport._modulus_pack.read_file(fn)
return True
except IOError:
pass
# none succeeded
Transport._modulus_pack = None
return False | [
"def",
"load_server_moduli",
"(",
"filename",
"=",
"None",
")",
":",
"Transport",
".",
"_modulus_pack",
"=",
"ModulusPack",
"(",
")",
"# places to look for the openssh \"moduli\" file",
"file_list",
"=",
"[",
"\"/etc/ssh/moduli\"",
",",
"\"/usr/local/etc/moduli\"",
"]",
"if",
"filename",
"is",
"not",
"None",
":",
"file_list",
".",
"insert",
"(",
"0",
",",
"filename",
")",
"for",
"fn",
"in",
"file_list",
":",
"try",
":",
"Transport",
".",
"_modulus_pack",
".",
"read_file",
"(",
"fn",
")",
"return",
"True",
"except",
"IOError",
":",
"pass",
"# none succeeded",
"Transport",
".",
"_modulus_pack",
"=",
"None",
"return",
"False"
] | (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
negotiation, which asks the server to send a random prime number that
fits certain criteria. These primes are pretty difficult to compute,
so they can't be generated on demand. But many systems contain a file
of suitable primes (usually named something like ``/etc/ssh/moduli``).
If you call `load_server_moduli` and it returns ``True``, then this
file of primes has been loaded and we will support "group-exchange" in
server mode. Otherwise server mode will just claim that it doesn't
support that method of key negotiation.
:param str filename:
optional path to the moduli file, if you happen to know that it's
not in a standard location.
:return:
True if a moduli file was successfully loaded; False otherwise.
.. note:: This has no effect when used in client mode. | [
"(",
"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",
"."
] | cf7d49d66f3b1fbc8b0853518a54050182b3b5eb | https://github.com/paramiko/paramiko/blob/cf7d49d66f3b1fbc8b0853518a54050182b3b5eb/paramiko/transport.py#L696-L734 | train |
paramiko/paramiko | paramiko/transport.py | Transport.close | 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() | python | 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() | [
"def",
"close",
"(",
"self",
")",
":",
"if",
"not",
"self",
".",
"active",
":",
"return",
"self",
".",
"stop_thread",
"(",
")",
"for",
"chan",
"in",
"list",
"(",
"self",
".",
"_channels",
".",
"values",
"(",
")",
")",
":",
"chan",
".",
"_unlink",
"(",
")",
"self",
".",
"sock",
".",
"close",
"(",
")"
] | Close this session, and any open channels that are tied to it. | [
"Close",
"this",
"session",
"and",
"any",
"open",
"channels",
"that",
"are",
"tied",
"to",
"it",
"."
] | cf7d49d66f3b1fbc8b0853518a54050182b3b5eb | https://github.com/paramiko/paramiko/blob/cf7d49d66f3b1fbc8b0853518a54050182b3b5eb/paramiko/transport.py#L736-L745 | train |
paramiko/paramiko | paramiko/transport.py | Transport.open_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 packet sizes might have adverse
effects on the session created. The default values are the same
as in the OpenSSH code base and have been battle tested.
:param int window_size:
optional window size for this session.
:param int max_packet_size:
optional max packet size for this session.
:return: a new `.Channel`
:raises:
`.SSHException` -- if the request is rejected or the session ends
prematurely
.. versionchanged:: 1.13.4/1.14.3/1.15.3
Added the ``timeout`` argument.
.. versionchanged:: 1.15
Added the ``window_size`` and ``max_packet_size`` arguments.
"""
return self.open_channel(
"session",
window_size=window_size,
max_packet_size=max_packet_size,
timeout=timeout,
) | python | 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 packet sizes might have adverse
effects on the session created. The default values are the same
as in the OpenSSH code base and have been battle tested.
:param int window_size:
optional window size for this session.
:param int max_packet_size:
optional max packet size for this session.
:return: a new `.Channel`
:raises:
`.SSHException` -- if the request is rejected or the session ends
prematurely
.. versionchanged:: 1.13.4/1.14.3/1.15.3
Added the ``timeout`` argument.
.. versionchanged:: 1.15
Added the ``window_size`` and ``max_packet_size`` arguments.
"""
return self.open_channel(
"session",
window_size=window_size,
max_packet_size=max_packet_size,
timeout=timeout,
) | [
"def",
"open_session",
"(",
"self",
",",
"window_size",
"=",
"None",
",",
"max_packet_size",
"=",
"None",
",",
"timeout",
"=",
"None",
")",
":",
"return",
"self",
".",
"open_channel",
"(",
"\"session\"",
",",
"window_size",
"=",
"window_size",
",",
"max_packet_size",
"=",
"max_packet_size",
",",
"timeout",
"=",
"timeout",
",",
")"
] | 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 packet sizes might have adverse
effects on the session created. The default values are the same
as in the OpenSSH code base and have been battle tested.
:param int window_size:
optional window size for this session.
:param int max_packet_size:
optional max packet size for this session.
:return: a new `.Channel`
:raises:
`.SSHException` -- if the request is rejected or the session ends
prematurely
.. versionchanged:: 1.13.4/1.14.3/1.15.3
Added the ``timeout`` argument.
.. versionchanged:: 1.15
Added the ``window_size`` and ``max_packet_size`` arguments. | [
"Request",
"a",
"new",
"channel",
"to",
"the",
"server",
"of",
"type",
"session",
".",
"This",
"is",
"just",
"an",
"alias",
"for",
"calling",
"open_channel",
"with",
"an",
"argument",
"of",
"session",
"."
] | cf7d49d66f3b1fbc8b0853518a54050182b3b5eb | https://github.com/paramiko/paramiko/blob/cf7d49d66f3b1fbc8b0853518a54050182b3b5eb/paramiko/transport.py#L774-L807 | train |
paramiko/paramiko | paramiko/transport.py | Transport.open_channel | 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 data across the
session. You may only request a channel after negotiating encryption
(using `connect` or `start_client`) and authenticating.
.. note:: Modifying the the window and packet sizes might have adverse
effects on the channel created. The default values are the same
as in the OpenSSH code base and have been battle tested.
:param str kind:
the kind of channel requested (usually ``"session"``,
``"forwarded-tcpip"``, ``"direct-tcpip"``, or ``"x11"``)
:param tuple dest_addr:
the destination address (address + port tuple) of this port
forwarding, if ``kind`` is ``"forwarded-tcpip"`` or
``"direct-tcpip"`` (ignored for other channel types)
:param src_addr: the source address of this port forwarding, if
``kind`` is ``"forwarded-tcpip"``, ``"direct-tcpip"``, or ``"x11"``
:param int window_size:
optional window size for this session.
:param int max_packet_size:
optional max packet size for this session.
:param float timeout:
optional timeout opening a channel, default 3600s (1h)
:return: a new `.Channel` on success
:raises:
`.SSHException` -- if the request is rejected, the session ends
prematurely or there is a timeout openning a channel
.. versionchanged:: 1.15
Added the ``window_size`` and ``max_packet_size`` arguments.
"""
if not self.active:
raise SSHException("SSH session not active")
timeout = 3600 if timeout is None else timeout
self.lock.acquire()
try:
window_size = self._sanitize_window_size(window_size)
max_packet_size = self._sanitize_packet_size(max_packet_size)
chanid = self._next_channel()
m = Message()
m.add_byte(cMSG_CHANNEL_OPEN)
m.add_string(kind)
m.add_int(chanid)
m.add_int(window_size)
m.add_int(max_packet_size)
if (kind == "forwarded-tcpip") or (kind == "direct-tcpip"):
m.add_string(dest_addr[0])
m.add_int(dest_addr[1])
m.add_string(src_addr[0])
m.add_int(src_addr[1])
elif kind == "x11":
m.add_string(src_addr[0])
m.add_int(src_addr[1])
chan = Channel(chanid)
self._channels.put(chanid, chan)
self.channel_events[chanid] = event = threading.Event()
self.channels_seen[chanid] = True
chan._set_transport(self)
chan._set_window(window_size, max_packet_size)
finally:
self.lock.release()
self._send_user_message(m)
start_ts = time.time()
while True:
event.wait(0.1)
if not self.active:
e = self.get_exception()
if e is None:
e = SSHException("Unable to open channel.")
raise e
if event.is_set():
break
elif start_ts + timeout < time.time():
raise SSHException("Timeout opening channel.")
chan = self._channels.get(chanid)
if chan is not None:
return chan
e = self.get_exception()
if e is None:
e = SSHException("Unable to open channel.")
raise e | python | 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 data across the
session. You may only request a channel after negotiating encryption
(using `connect` or `start_client`) and authenticating.
.. note:: Modifying the the window and packet sizes might have adverse
effects on the channel created. The default values are the same
as in the OpenSSH code base and have been battle tested.
:param str kind:
the kind of channel requested (usually ``"session"``,
``"forwarded-tcpip"``, ``"direct-tcpip"``, or ``"x11"``)
:param tuple dest_addr:
the destination address (address + port tuple) of this port
forwarding, if ``kind`` is ``"forwarded-tcpip"`` or
``"direct-tcpip"`` (ignored for other channel types)
:param src_addr: the source address of this port forwarding, if
``kind`` is ``"forwarded-tcpip"``, ``"direct-tcpip"``, or ``"x11"``
:param int window_size:
optional window size for this session.
:param int max_packet_size:
optional max packet size for this session.
:param float timeout:
optional timeout opening a channel, default 3600s (1h)
:return: a new `.Channel` on success
:raises:
`.SSHException` -- if the request is rejected, the session ends
prematurely or there is a timeout openning a channel
.. versionchanged:: 1.15
Added the ``window_size`` and ``max_packet_size`` arguments.
"""
if not self.active:
raise SSHException("SSH session not active")
timeout = 3600 if timeout is None else timeout
self.lock.acquire()
try:
window_size = self._sanitize_window_size(window_size)
max_packet_size = self._sanitize_packet_size(max_packet_size)
chanid = self._next_channel()
m = Message()
m.add_byte(cMSG_CHANNEL_OPEN)
m.add_string(kind)
m.add_int(chanid)
m.add_int(window_size)
m.add_int(max_packet_size)
if (kind == "forwarded-tcpip") or (kind == "direct-tcpip"):
m.add_string(dest_addr[0])
m.add_int(dest_addr[1])
m.add_string(src_addr[0])
m.add_int(src_addr[1])
elif kind == "x11":
m.add_string(src_addr[0])
m.add_int(src_addr[1])
chan = Channel(chanid)
self._channels.put(chanid, chan)
self.channel_events[chanid] = event = threading.Event()
self.channels_seen[chanid] = True
chan._set_transport(self)
chan._set_window(window_size, max_packet_size)
finally:
self.lock.release()
self._send_user_message(m)
start_ts = time.time()
while True:
event.wait(0.1)
if not self.active:
e = self.get_exception()
if e is None:
e = SSHException("Unable to open channel.")
raise e
if event.is_set():
break
elif start_ts + timeout < time.time():
raise SSHException("Timeout opening channel.")
chan = self._channels.get(chanid)
if chan is not None:
return chan
e = self.get_exception()
if e is None:
e = SSHException("Unable to open channel.")
raise e | [
"def",
"open_channel",
"(",
"self",
",",
"kind",
",",
"dest_addr",
"=",
"None",
",",
"src_addr",
"=",
"None",
",",
"window_size",
"=",
"None",
",",
"max_packet_size",
"=",
"None",
",",
"timeout",
"=",
"None",
",",
")",
":",
"if",
"not",
"self",
".",
"active",
":",
"raise",
"SSHException",
"(",
"\"SSH session not active\"",
")",
"timeout",
"=",
"3600",
"if",
"timeout",
"is",
"None",
"else",
"timeout",
"self",
".",
"lock",
".",
"acquire",
"(",
")",
"try",
":",
"window_size",
"=",
"self",
".",
"_sanitize_window_size",
"(",
"window_size",
")",
"max_packet_size",
"=",
"self",
".",
"_sanitize_packet_size",
"(",
"max_packet_size",
")",
"chanid",
"=",
"self",
".",
"_next_channel",
"(",
")",
"m",
"=",
"Message",
"(",
")",
"m",
".",
"add_byte",
"(",
"cMSG_CHANNEL_OPEN",
")",
"m",
".",
"add_string",
"(",
"kind",
")",
"m",
".",
"add_int",
"(",
"chanid",
")",
"m",
".",
"add_int",
"(",
"window_size",
")",
"m",
".",
"add_int",
"(",
"max_packet_size",
")",
"if",
"(",
"kind",
"==",
"\"forwarded-tcpip\"",
")",
"or",
"(",
"kind",
"==",
"\"direct-tcpip\"",
")",
":",
"m",
".",
"add_string",
"(",
"dest_addr",
"[",
"0",
"]",
")",
"m",
".",
"add_int",
"(",
"dest_addr",
"[",
"1",
"]",
")",
"m",
".",
"add_string",
"(",
"src_addr",
"[",
"0",
"]",
")",
"m",
".",
"add_int",
"(",
"src_addr",
"[",
"1",
"]",
")",
"elif",
"kind",
"==",
"\"x11\"",
":",
"m",
".",
"add_string",
"(",
"src_addr",
"[",
"0",
"]",
")",
"m",
".",
"add_int",
"(",
"src_addr",
"[",
"1",
"]",
")",
"chan",
"=",
"Channel",
"(",
"chanid",
")",
"self",
".",
"_channels",
".",
"put",
"(",
"chanid",
",",
"chan",
")",
"self",
".",
"channel_events",
"[",
"chanid",
"]",
"=",
"event",
"=",
"threading",
".",
"Event",
"(",
")",
"self",
".",
"channels_seen",
"[",
"chanid",
"]",
"=",
"True",
"chan",
".",
"_set_transport",
"(",
"self",
")",
"chan",
".",
"_set_window",
"(",
"window_size",
",",
"max_packet_size",
")",
"finally",
":",
"self",
".",
"lock",
".",
"release",
"(",
")",
"self",
".",
"_send_user_message",
"(",
"m",
")",
"start_ts",
"=",
"time",
".",
"time",
"(",
")",
"while",
"True",
":",
"event",
".",
"wait",
"(",
"0.1",
")",
"if",
"not",
"self",
".",
"active",
":",
"e",
"=",
"self",
".",
"get_exception",
"(",
")",
"if",
"e",
"is",
"None",
":",
"e",
"=",
"SSHException",
"(",
"\"Unable to open channel.\"",
")",
"raise",
"e",
"if",
"event",
".",
"is_set",
"(",
")",
":",
"break",
"elif",
"start_ts",
"+",
"timeout",
"<",
"time",
".",
"time",
"(",
")",
":",
"raise",
"SSHException",
"(",
"\"Timeout opening channel.\"",
")",
"chan",
"=",
"self",
".",
"_channels",
".",
"get",
"(",
"chanid",
")",
"if",
"chan",
"is",
"not",
"None",
":",
"return",
"chan",
"e",
"=",
"self",
".",
"get_exception",
"(",
")",
"if",
"e",
"is",
"None",
":",
"e",
"=",
"SSHException",
"(",
"\"Unable to open channel.\"",
")",
"raise",
"e"
] | 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.
.. note:: Modifying the the window and packet sizes might have adverse
effects on the channel created. The default values are the same
as in the OpenSSH code base and have been battle tested.
:param str kind:
the kind of channel requested (usually ``"session"``,
``"forwarded-tcpip"``, ``"direct-tcpip"``, or ``"x11"``)
:param tuple dest_addr:
the destination address (address + port tuple) of this port
forwarding, if ``kind`` is ``"forwarded-tcpip"`` or
``"direct-tcpip"`` (ignored for other channel types)
:param src_addr: the source address of this port forwarding, if
``kind`` is ``"forwarded-tcpip"``, ``"direct-tcpip"``, or ``"x11"``
:param int window_size:
optional window size for this session.
:param int max_packet_size:
optional max packet size for this session.
:param float timeout:
optional timeout opening a channel, default 3600s (1h)
:return: a new `.Channel` on success
:raises:
`.SSHException` -- if the request is rejected, the session ends
prematurely or there is a timeout openning a channel
.. versionchanged:: 1.15
Added the ``window_size`` and ``max_packet_size`` arguments. | [
"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",
"."
] | cf7d49d66f3b1fbc8b0853518a54050182b3b5eb | https://github.com/paramiko/paramiko/blob/cf7d49d66f3b1fbc8b0853518a54050182b3b5eb/paramiko/transport.py#L851-L944 | train |
paramiko/paramiko | paramiko/transport.py | Transport.request_port_forward | 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. The handler parameters are::
handler(
channel,
(origin_addr, origin_port),
(server_addr, server_port),
)
where ``server_addr`` and ``server_port`` are the address and port that
the server was listening on.
If no handler is set, the default behavior is to send new incoming
forwarded connections into the accept queue, to be picked up via
`accept`.
:param str address: the address to bind when forwarding
:param int port:
the port to forward, or 0 to ask the server to allocate any port
:param callable handler:
optional handler for incoming forwarded connections, of the form
``func(Channel, (str, int), (str, int))``.
:return: the port number (`int`) allocated by the server
:raises:
`.SSHException` -- if the server refused the TCP forward request
"""
if not self.active:
raise SSHException("SSH session not active")
port = int(port)
response = self.global_request(
"tcpip-forward", (address, port), wait=True
)
if response is None:
raise SSHException("TCP forwarding request denied")
if port == 0:
port = response.get_int()
if handler is None:
def default_handler(channel, src_addr, dest_addr_port):
# src_addr, src_port = src_addr_port
# dest_addr, dest_port = dest_addr_port
self._queue_incoming_channel(channel)
handler = default_handler
self._tcp_handler = handler
return port | python | 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. The handler parameters are::
handler(
channel,
(origin_addr, origin_port),
(server_addr, server_port),
)
where ``server_addr`` and ``server_port`` are the address and port that
the server was listening on.
If no handler is set, the default behavior is to send new incoming
forwarded connections into the accept queue, to be picked up via
`accept`.
:param str address: the address to bind when forwarding
:param int port:
the port to forward, or 0 to ask the server to allocate any port
:param callable handler:
optional handler for incoming forwarded connections, of the form
``func(Channel, (str, int), (str, int))``.
:return: the port number (`int`) allocated by the server
:raises:
`.SSHException` -- if the server refused the TCP forward request
"""
if not self.active:
raise SSHException("SSH session not active")
port = int(port)
response = self.global_request(
"tcpip-forward", (address, port), wait=True
)
if response is None:
raise SSHException("TCP forwarding request denied")
if port == 0:
port = response.get_int()
if handler is None:
def default_handler(channel, src_addr, dest_addr_port):
# src_addr, src_port = src_addr_port
# dest_addr, dest_port = dest_addr_port
self._queue_incoming_channel(channel)
handler = default_handler
self._tcp_handler = handler
return port | [
"def",
"request_port_forward",
"(",
"self",
",",
"address",
",",
"port",
",",
"handler",
"=",
"None",
")",
":",
"if",
"not",
"self",
".",
"active",
":",
"raise",
"SSHException",
"(",
"\"SSH session not active\"",
")",
"port",
"=",
"int",
"(",
"port",
")",
"response",
"=",
"self",
".",
"global_request",
"(",
"\"tcpip-forward\"",
",",
"(",
"address",
",",
"port",
")",
",",
"wait",
"=",
"True",
")",
"if",
"response",
"is",
"None",
":",
"raise",
"SSHException",
"(",
"\"TCP forwarding request denied\"",
")",
"if",
"port",
"==",
"0",
":",
"port",
"=",
"response",
".",
"get_int",
"(",
")",
"if",
"handler",
"is",
"None",
":",
"def",
"default_handler",
"(",
"channel",
",",
"src_addr",
",",
"dest_addr_port",
")",
":",
"# src_addr, src_port = src_addr_port",
"# dest_addr, dest_port = dest_addr_port",
"self",
".",
"_queue_incoming_channel",
"(",
"channel",
")",
"handler",
"=",
"default_handler",
"self",
".",
"_tcp_handler",
"=",
"handler",
"return",
"port"
] | 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. The handler parameters are::
handler(
channel,
(origin_addr, origin_port),
(server_addr, server_port),
)
where ``server_addr`` and ``server_port`` are the address and port that
the server was listening on.
If no handler is set, the default behavior is to send new incoming
forwarded connections into the accept queue, to be picked up via
`accept`.
:param str address: the address to bind when forwarding
:param int port:
the port to forward, or 0 to ask the server to allocate any port
:param callable handler:
optional handler for incoming forwarded connections, of the form
``func(Channel, (str, int), (str, int))``.
:return: the port number (`int`) allocated by the server
:raises:
`.SSHException` -- if the server refused the TCP forward request | [
"Ask",
"the",
"server",
"to",
"forward",
"TCP",
"connections",
"from",
"a",
"listening",
"port",
"on",
"the",
"server",
"across",
"this",
"SSH",
"session",
"."
] | cf7d49d66f3b1fbc8b0853518a54050182b3b5eb | https://github.com/paramiko/paramiko/blob/cf7d49d66f3b1fbc8b0853518a54050182b3b5eb/paramiko/transport.py#L946-L998 | train |
paramiko/paramiko | paramiko/transport.py | Transport.cancel_port_forward | 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 port: the port to stop forwarding
"""
if not self.active:
return
self._tcp_handler = None
self.global_request("cancel-tcpip-forward", (address, port), wait=True) | python | 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 port: the port to stop forwarding
"""
if not self.active:
return
self._tcp_handler = None
self.global_request("cancel-tcpip-forward", (address, port), wait=True) | [
"def",
"cancel_port_forward",
"(",
"self",
",",
"address",
",",
"port",
")",
":",
"if",
"not",
"self",
".",
"active",
":",
"return",
"self",
".",
"_tcp_handler",
"=",
"None",
"self",
".",
"global_request",
"(",
"\"cancel-tcpip-forward\"",
",",
"(",
"address",
",",
"port",
")",
",",
"wait",
"=",
"True",
")"
] | 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 port: the port to stop forwarding | [
"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",
"."
] | cf7d49d66f3b1fbc8b0853518a54050182b3b5eb | https://github.com/paramiko/paramiko/blob/cf7d49d66f3b1fbc8b0853518a54050182b3b5eb/paramiko/transport.py#L1000-L1012 | train |
paramiko/paramiko | paramiko/transport.py | Transport.send_ignore | 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 int byte_count:
the number of random bytes to send in the payload of the ignored
packet -- defaults to a random number from 10 to 41.
"""
m = Message()
m.add_byte(cMSG_IGNORE)
if byte_count is None:
byte_count = (byte_ord(os.urandom(1)) % 32) + 10
m.add_bytes(os.urandom(byte_count))
self._send_user_message(m) | python | 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 int byte_count:
the number of random bytes to send in the payload of the ignored
packet -- defaults to a random number from 10 to 41.
"""
m = Message()
m.add_byte(cMSG_IGNORE)
if byte_count is None:
byte_count = (byte_ord(os.urandom(1)) % 32) + 10
m.add_bytes(os.urandom(byte_count))
self._send_user_message(m) | [
"def",
"send_ignore",
"(",
"self",
",",
"byte_count",
"=",
"None",
")",
":",
"m",
"=",
"Message",
"(",
")",
"m",
".",
"add_byte",
"(",
"cMSG_IGNORE",
")",
"if",
"byte_count",
"is",
"None",
":",
"byte_count",
"=",
"(",
"byte_ord",
"(",
"os",
".",
"urandom",
"(",
"1",
")",
")",
"%",
"32",
")",
"+",
"10",
"m",
".",
"add_bytes",
"(",
"os",
".",
"urandom",
"(",
"byte_count",
")",
")",
"self",
".",
"_send_user_message",
"(",
"m",
")"
] | 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 int byte_count:
the number of random bytes to send in the payload of the ignored
packet -- defaults to a random number from 10 to 41. | [
"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",
"."
] | cf7d49d66f3b1fbc8b0853518a54050182b3b5eb | https://github.com/paramiko/paramiko/blob/cf7d49d66f3b1fbc8b0853518a54050182b3b5eb/paramiko/transport.py#L1026-L1042 | train |
paramiko/paramiko | paramiko/transport.py | Transport.accept | 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 forever
:return: a new `.Channel` opened by the client
"""
self.lock.acquire()
try:
if len(self.server_accepts) > 0:
chan = self.server_accepts.pop(0)
else:
self.server_accept_cv.wait(timeout)
if len(self.server_accepts) > 0:
chan = self.server_accepts.pop(0)
else:
# timeout
chan = None
finally:
self.lock.release()
return chan | python | 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 forever
:return: a new `.Channel` opened by the client
"""
self.lock.acquire()
try:
if len(self.server_accepts) > 0:
chan = self.server_accepts.pop(0)
else:
self.server_accept_cv.wait(timeout)
if len(self.server_accepts) > 0:
chan = self.server_accepts.pop(0)
else:
# timeout
chan = None
finally:
self.lock.release()
return chan | [
"def",
"accept",
"(",
"self",
",",
"timeout",
"=",
"None",
")",
":",
"self",
".",
"lock",
".",
"acquire",
"(",
")",
"try",
":",
"if",
"len",
"(",
"self",
".",
"server_accepts",
")",
">",
"0",
":",
"chan",
"=",
"self",
".",
"server_accepts",
".",
"pop",
"(",
"0",
")",
"else",
":",
"self",
".",
"server_accept_cv",
".",
"wait",
"(",
"timeout",
")",
"if",
"len",
"(",
"self",
".",
"server_accepts",
")",
">",
"0",
":",
"chan",
"=",
"self",
".",
"server_accepts",
".",
"pop",
"(",
"0",
")",
"else",
":",
"# timeout",
"chan",
"=",
"None",
"finally",
":",
"self",
".",
"lock",
".",
"release",
"(",
")",
"return",
"chan"
] | 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 forever
:return: a new `.Channel` opened by the client | [
"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",
"."
] | cf7d49d66f3b1fbc8b0853518a54050182b3b5eb | https://github.com/paramiko/paramiko/blob/cf7d49d66f3b1fbc8b0853518a54050182b3b5eb/paramiko/transport.py#L1124-L1147 | train |
paramiko/paramiko | paramiko/transport.py | Transport.connect | 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 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.
You can use this method immediately after creating a Transport to
negotiate encryption with a server. If it fails, an exception will be
thrown. On success, the method will return cleanly, and an encrypted
session exists. You may immediately call `open_channel` or
`open_session` to get a `.Channel` object, which is used for data
transfer.
.. note::
If you fail to supply a password or private key, this method may
succeed, but a subsequent `open_channel` or `open_session` call may
fail because you haven't authenticated yet.
:param .PKey hostkey:
the host key expected from the server, or ``None`` if you don't
want to do host key verification.
:param str username: the username to authenticate as.
:param str password:
a password to use for authentication, if you want to use password
authentication; otherwise ``None``.
:param .PKey pkey:
a private key to use for authentication, if you want to use private
key authentication; otherwise ``None``.
:param str gss_host:
The target's name in the kerberos database. Default: hostname
:param bool gss_auth:
``True`` if you want to use GSS-API authentication.
:param bool gss_kex:
Perform GSS-API Key Exchange and user authentication.
:param bool gss_deleg_creds:
Whether to delegate GSS-API client credentials.
:param gss_trust_dns:
Indicates whether or not the DNS is trusted to securely
canonicalize the name of the host being connected to (default
``True``).
:raises: `.SSHException` -- if the SSH2 negotiation fails, the host key
supplied by the server is incorrect, or authentication fails.
.. versionchanged:: 2.3
Added the ``gss_trust_dns`` argument.
"""
if hostkey is not None:
self._preferred_keys = [hostkey.get_name()]
self.set_gss_host(
gss_host=gss_host,
trust_dns=gss_trust_dns,
gssapi_requested=gss_kex or gss_auth,
)
self.start_client()
# check host key if we were given one
# If GSS-API Key Exchange was performed, we are not required to check
# the host key.
if (hostkey is not None) and not gss_kex:
key = self.get_remote_server_key()
if (
key.get_name() != hostkey.get_name()
or key.asbytes() != hostkey.asbytes()
):
self._log(DEBUG, "Bad host key from server")
self._log(
DEBUG,
"Expected: {}: {}".format(
hostkey.get_name(), repr(hostkey.asbytes())
),
)
self._log(
DEBUG,
"Got : {}: {}".format(
key.get_name(), repr(key.asbytes())
),
)
raise SSHException("Bad host key from server")
self._log(
DEBUG, "Host key verified ({})".format(hostkey.get_name())
)
if (pkey is not None) or (password is not None) or gss_auth or gss_kex:
if gss_auth:
self._log(
DEBUG, "Attempting GSS-API auth... (gssapi-with-mic)"
) # noqa
self.auth_gssapi_with_mic(
username, self.gss_host, gss_deleg_creds
)
elif gss_kex:
self._log(DEBUG, "Attempting GSS-API auth... (gssapi-keyex)")
self.auth_gssapi_keyex(username)
elif pkey is not None:
self._log(DEBUG, "Attempting public-key auth...")
self.auth_publickey(username, pkey)
else:
self._log(DEBUG, "Attempting password auth...")
self.auth_password(username, password)
return | python | 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 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.
You can use this method immediately after creating a Transport to
negotiate encryption with a server. If it fails, an exception will be
thrown. On success, the method will return cleanly, and an encrypted
session exists. You may immediately call `open_channel` or
`open_session` to get a `.Channel` object, which is used for data
transfer.
.. note::
If you fail to supply a password or private key, this method may
succeed, but a subsequent `open_channel` or `open_session` call may
fail because you haven't authenticated yet.
:param .PKey hostkey:
the host key expected from the server, or ``None`` if you don't
want to do host key verification.
:param str username: the username to authenticate as.
:param str password:
a password to use for authentication, if you want to use password
authentication; otherwise ``None``.
:param .PKey pkey:
a private key to use for authentication, if you want to use private
key authentication; otherwise ``None``.
:param str gss_host:
The target's name in the kerberos database. Default: hostname
:param bool gss_auth:
``True`` if you want to use GSS-API authentication.
:param bool gss_kex:
Perform GSS-API Key Exchange and user authentication.
:param bool gss_deleg_creds:
Whether to delegate GSS-API client credentials.
:param gss_trust_dns:
Indicates whether or not the DNS is trusted to securely
canonicalize the name of the host being connected to (default
``True``).
:raises: `.SSHException` -- if the SSH2 negotiation fails, the host key
supplied by the server is incorrect, or authentication fails.
.. versionchanged:: 2.3
Added the ``gss_trust_dns`` argument.
"""
if hostkey is not None:
self._preferred_keys = [hostkey.get_name()]
self.set_gss_host(
gss_host=gss_host,
trust_dns=gss_trust_dns,
gssapi_requested=gss_kex or gss_auth,
)
self.start_client()
# check host key if we were given one
# If GSS-API Key Exchange was performed, we are not required to check
# the host key.
if (hostkey is not None) and not gss_kex:
key = self.get_remote_server_key()
if (
key.get_name() != hostkey.get_name()
or key.asbytes() != hostkey.asbytes()
):
self._log(DEBUG, "Bad host key from server")
self._log(
DEBUG,
"Expected: {}: {}".format(
hostkey.get_name(), repr(hostkey.asbytes())
),
)
self._log(
DEBUG,
"Got : {}: {}".format(
key.get_name(), repr(key.asbytes())
),
)
raise SSHException("Bad host key from server")
self._log(
DEBUG, "Host key verified ({})".format(hostkey.get_name())
)
if (pkey is not None) or (password is not None) or gss_auth or gss_kex:
if gss_auth:
self._log(
DEBUG, "Attempting GSS-API auth... (gssapi-with-mic)"
) # noqa
self.auth_gssapi_with_mic(
username, self.gss_host, gss_deleg_creds
)
elif gss_kex:
self._log(DEBUG, "Attempting GSS-API auth... (gssapi-keyex)")
self.auth_gssapi_keyex(username)
elif pkey is not None:
self._log(DEBUG, "Attempting public-key auth...")
self.auth_publickey(username, pkey)
else:
self._log(DEBUG, "Attempting password auth...")
self.auth_password(username, password)
return | [
"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",
",",
")",
":",
"if",
"hostkey",
"is",
"not",
"None",
":",
"self",
".",
"_preferred_keys",
"=",
"[",
"hostkey",
".",
"get_name",
"(",
")",
"]",
"self",
".",
"set_gss_host",
"(",
"gss_host",
"=",
"gss_host",
",",
"trust_dns",
"=",
"gss_trust_dns",
",",
"gssapi_requested",
"=",
"gss_kex",
"or",
"gss_auth",
",",
")",
"self",
".",
"start_client",
"(",
")",
"# check host key if we were given one",
"# If GSS-API Key Exchange was performed, we are not required to check",
"# the host key.",
"if",
"(",
"hostkey",
"is",
"not",
"None",
")",
"and",
"not",
"gss_kex",
":",
"key",
"=",
"self",
".",
"get_remote_server_key",
"(",
")",
"if",
"(",
"key",
".",
"get_name",
"(",
")",
"!=",
"hostkey",
".",
"get_name",
"(",
")",
"or",
"key",
".",
"asbytes",
"(",
")",
"!=",
"hostkey",
".",
"asbytes",
"(",
")",
")",
":",
"self",
".",
"_log",
"(",
"DEBUG",
",",
"\"Bad host key from server\"",
")",
"self",
".",
"_log",
"(",
"DEBUG",
",",
"\"Expected: {}: {}\"",
".",
"format",
"(",
"hostkey",
".",
"get_name",
"(",
")",
",",
"repr",
"(",
"hostkey",
".",
"asbytes",
"(",
")",
")",
")",
",",
")",
"self",
".",
"_log",
"(",
"DEBUG",
",",
"\"Got : {}: {}\"",
".",
"format",
"(",
"key",
".",
"get_name",
"(",
")",
",",
"repr",
"(",
"key",
".",
"asbytes",
"(",
")",
")",
")",
",",
")",
"raise",
"SSHException",
"(",
"\"Bad host key from server\"",
")",
"self",
".",
"_log",
"(",
"DEBUG",
",",
"\"Host key verified ({})\"",
".",
"format",
"(",
"hostkey",
".",
"get_name",
"(",
")",
")",
")",
"if",
"(",
"pkey",
"is",
"not",
"None",
")",
"or",
"(",
"password",
"is",
"not",
"None",
")",
"or",
"gss_auth",
"or",
"gss_kex",
":",
"if",
"gss_auth",
":",
"self",
".",
"_log",
"(",
"DEBUG",
",",
"\"Attempting GSS-API auth... (gssapi-with-mic)\"",
")",
"# noqa",
"self",
".",
"auth_gssapi_with_mic",
"(",
"username",
",",
"self",
".",
"gss_host",
",",
"gss_deleg_creds",
")",
"elif",
"gss_kex",
":",
"self",
".",
"_log",
"(",
"DEBUG",
",",
"\"Attempting GSS-API auth... (gssapi-keyex)\"",
")",
"self",
".",
"auth_gssapi_keyex",
"(",
"username",
")",
"elif",
"pkey",
"is",
"not",
"None",
":",
"self",
".",
"_log",
"(",
"DEBUG",
",",
"\"Attempting public-key auth...\"",
")",
"self",
".",
"auth_publickey",
"(",
"username",
",",
"pkey",
")",
"else",
":",
"self",
".",
"_log",
"(",
"DEBUG",
",",
"\"Attempting password auth...\"",
")",
"self",
".",
"auth_password",
"(",
"username",
",",
"password",
")",
"return"
] | 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.
You can use this method immediately after creating a Transport to
negotiate encryption with a server. If it fails, an exception will be
thrown. On success, the method will return cleanly, and an encrypted
session exists. You may immediately call `open_channel` or
`open_session` to get a `.Channel` object, which is used for data
transfer.
.. note::
If you fail to supply a password or private key, this method may
succeed, but a subsequent `open_channel` or `open_session` call may
fail because you haven't authenticated yet.
:param .PKey hostkey:
the host key expected from the server, or ``None`` if you don't
want to do host key verification.
:param str username: the username to authenticate as.
:param str password:
a password to use for authentication, if you want to use password
authentication; otherwise ``None``.
:param .PKey pkey:
a private key to use for authentication, if you want to use private
key authentication; otherwise ``None``.
:param str gss_host:
The target's name in the kerberos database. Default: hostname
:param bool gss_auth:
``True`` if you want to use GSS-API authentication.
:param bool gss_kex:
Perform GSS-API Key Exchange and user authentication.
:param bool gss_deleg_creds:
Whether to delegate GSS-API client credentials.
:param gss_trust_dns:
Indicates whether or not the DNS is trusted to securely
canonicalize the name of the host being connected to (default
``True``).
:raises: `.SSHException` -- if the SSH2 negotiation fails, the host key
supplied by the server is incorrect, or authentication fails.
.. versionchanged:: 2.3
Added the ``gss_trust_dns`` argument. | [
"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",
"."
] | cf7d49d66f3b1fbc8b0853518a54050182b3b5eb | https://github.com/paramiko/paramiko/blob/cf7d49d66f3b1fbc8b0853518a54050182b3b5eb/paramiko/transport.py#L1149-L1265 | train |
paramiko/paramiko | paramiko/transport.py | Transport.get_exception | 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 exception, or ``None`` if there is no stored exception.
.. versionadded:: 1.1
"""
self.lock.acquire()
try:
e = self.saved_exception
self.saved_exception = None
return e
finally:
self.lock.release() | python | 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 exception, or ``None`` if there is no stored exception.
.. versionadded:: 1.1
"""
self.lock.acquire()
try:
e = self.saved_exception
self.saved_exception = None
return e
finally:
self.lock.release() | [
"def",
"get_exception",
"(",
"self",
")",
":",
"self",
".",
"lock",
".",
"acquire",
"(",
")",
"try",
":",
"e",
"=",
"self",
".",
"saved_exception",
"self",
".",
"saved_exception",
"=",
"None",
"return",
"e",
"finally",
":",
"self",
".",
"lock",
".",
"release",
"(",
")"
] | 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 exception, or ``None`` if there is no stored exception.
.. versionadded:: 1.1 | [
"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",
"."
] | cf7d49d66f3b1fbc8b0853518a54050182b3b5eb | https://github.com/paramiko/paramiko/blob/cf7d49d66f3b1fbc8b0853518a54050182b3b5eb/paramiko/transport.py#L1267-L1285 | train |
paramiko/paramiko | paramiko/transport.py | Transport.set_subsystem_handler | 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
detailed documentation.
Any extra parameters (including keyword arguments) are saved and
passed to the `.SubsystemHandler` constructor later.
:param str name: name of the subsystem.
:param handler:
subclass of `.SubsystemHandler` that handles this subsystem.
"""
try:
self.lock.acquire()
self.subsystem_table[name] = (handler, larg, kwarg)
finally:
self.lock.release() | python | 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
detailed documentation.
Any extra parameters (including keyword arguments) are saved and
passed to the `.SubsystemHandler` constructor later.
:param str name: name of the subsystem.
:param handler:
subclass of `.SubsystemHandler` that handles this subsystem.
"""
try:
self.lock.acquire()
self.subsystem_table[name] = (handler, larg, kwarg)
finally:
self.lock.release() | [
"def",
"set_subsystem_handler",
"(",
"self",
",",
"name",
",",
"handler",
",",
"*",
"larg",
",",
"*",
"*",
"kwarg",
")",
":",
"try",
":",
"self",
".",
"lock",
".",
"acquire",
"(",
")",
"self",
".",
"subsystem_table",
"[",
"name",
"]",
"=",
"(",
"handler",
",",
"larg",
",",
"kwarg",
")",
"finally",
":",
"self",
".",
"lock",
".",
"release",
"(",
")"
] | 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.
Any extra parameters (including keyword arguments) are saved and
passed to the `.SubsystemHandler` constructor later.
:param str name: name of the subsystem.
:param handler:
subclass of `.SubsystemHandler` that handles this subsystem. | [
"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",
"."
] | cf7d49d66f3b1fbc8b0853518a54050182b3b5eb | https://github.com/paramiko/paramiko/blob/cf7d49d66f3b1fbc8b0853518a54050182b3b5eb/paramiko/transport.py#L1287-L1305 | train |
paramiko/paramiko | paramiko/transport.py | Transport.auth_password | 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 once authentication succeeds or fails. On
success, `is_authenticated` will return ``True``. On failure, you may
use `get_exception` to get more detailed error information.
Since 1.1, if no event is passed, this method will block until the
authentication succeeds or fails. On failure, an exception is raised.
Otherwise, the method simply returns.
Since 1.5, if no event is passed and ``fallback`` is ``True`` (the
default), if the server doesn't support plain password authentication
but does support so-called "keyboard-interactive" mode, an attempt
will be made to authenticate using this interactive mode. If it fails,
the normal exception will be thrown as if the attempt had never been
made. This is useful for some recent Gentoo and Debian distributions,
which turn off plain password authentication in a misguided belief
that interactive authentication is "more secure". (It's not.)
If the server requires multi-step authentication (which is very rare),
this method will return a list of auth types permissible for the next
step. Otherwise, in the normal case, an empty list is returned.
:param str username: the username to authenticate as
:param basestring password: the password to authenticate with
:param .threading.Event event:
an event to trigger when the authentication attempt is complete
(whether it was successful or not)
:param bool fallback:
``True`` if an attempt at an automated "interactive" password auth
should be made if the server doesn't support normal password auth
:return:
list of auth types permissible for the next stage of
authentication (normally empty)
:raises:
`.BadAuthenticationType` -- if password authentication isn't
allowed by the server for this user (and no event was passed in)
:raises:
`.AuthenticationException` -- if the authentication failed (and no
event was passed in)
:raises: `.SSHException` -- if there was a network error
"""
if (not self.active) or (not self.initial_kex_done):
# we should never try to send the password unless we're on a secure
# link
raise SSHException("No existing session")
if event is None:
my_event = threading.Event()
else:
my_event = event
self.auth_handler = AuthHandler(self)
self.auth_handler.auth_password(username, password, my_event)
if event is not None:
# caller wants to wait for event themselves
return []
try:
return self.auth_handler.wait_for_response(my_event)
except BadAuthenticationType as e:
# if password auth isn't allowed, but keyboard-interactive *is*,
# try to fudge it
if not fallback or ("keyboard-interactive" not in e.allowed_types):
raise
try:
def handler(title, instructions, fields):
if len(fields) > 1:
raise SSHException("Fallback authentication failed.")
if len(fields) == 0:
# for some reason, at least on os x, a 2nd request will
# be made with zero fields requested. maybe it's just
# to try to fake out automated scripting of the exact
# type we're doing here. *shrug* :)
return []
return [password]
return self.auth_interactive(username, handler)
except SSHException:
# attempt failed; just raise the original exception
raise e | python | 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 once authentication succeeds or fails. On
success, `is_authenticated` will return ``True``. On failure, you may
use `get_exception` to get more detailed error information.
Since 1.1, if no event is passed, this method will block until the
authentication succeeds or fails. On failure, an exception is raised.
Otherwise, the method simply returns.
Since 1.5, if no event is passed and ``fallback`` is ``True`` (the
default), if the server doesn't support plain password authentication
but does support so-called "keyboard-interactive" mode, an attempt
will be made to authenticate using this interactive mode. If it fails,
the normal exception will be thrown as if the attempt had never been
made. This is useful for some recent Gentoo and Debian distributions,
which turn off plain password authentication in a misguided belief
that interactive authentication is "more secure". (It's not.)
If the server requires multi-step authentication (which is very rare),
this method will return a list of auth types permissible for the next
step. Otherwise, in the normal case, an empty list is returned.
:param str username: the username to authenticate as
:param basestring password: the password to authenticate with
:param .threading.Event event:
an event to trigger when the authentication attempt is complete
(whether it was successful or not)
:param bool fallback:
``True`` if an attempt at an automated "interactive" password auth
should be made if the server doesn't support normal password auth
:return:
list of auth types permissible for the next stage of
authentication (normally empty)
:raises:
`.BadAuthenticationType` -- if password authentication isn't
allowed by the server for this user (and no event was passed in)
:raises:
`.AuthenticationException` -- if the authentication failed (and no
event was passed in)
:raises: `.SSHException` -- if there was a network error
"""
if (not self.active) or (not self.initial_kex_done):
# we should never try to send the password unless we're on a secure
# link
raise SSHException("No existing session")
if event is None:
my_event = threading.Event()
else:
my_event = event
self.auth_handler = AuthHandler(self)
self.auth_handler.auth_password(username, password, my_event)
if event is not None:
# caller wants to wait for event themselves
return []
try:
return self.auth_handler.wait_for_response(my_event)
except BadAuthenticationType as e:
# if password auth isn't allowed, but keyboard-interactive *is*,
# try to fudge it
if not fallback or ("keyboard-interactive" not in e.allowed_types):
raise
try:
def handler(title, instructions, fields):
if len(fields) > 1:
raise SSHException("Fallback authentication failed.")
if len(fields) == 0:
# for some reason, at least on os x, a 2nd request will
# be made with zero fields requested. maybe it's just
# to try to fake out automated scripting of the exact
# type we're doing here. *shrug* :)
return []
return [password]
return self.auth_interactive(username, handler)
except SSHException:
# attempt failed; just raise the original exception
raise e | [
"def",
"auth_password",
"(",
"self",
",",
"username",
",",
"password",
",",
"event",
"=",
"None",
",",
"fallback",
"=",
"True",
")",
":",
"if",
"(",
"not",
"self",
".",
"active",
")",
"or",
"(",
"not",
"self",
".",
"initial_kex_done",
")",
":",
"# we should never try to send the password unless we're on a secure",
"# link",
"raise",
"SSHException",
"(",
"\"No existing session\"",
")",
"if",
"event",
"is",
"None",
":",
"my_event",
"=",
"threading",
".",
"Event",
"(",
")",
"else",
":",
"my_event",
"=",
"event",
"self",
".",
"auth_handler",
"=",
"AuthHandler",
"(",
"self",
")",
"self",
".",
"auth_handler",
".",
"auth_password",
"(",
"username",
",",
"password",
",",
"my_event",
")",
"if",
"event",
"is",
"not",
"None",
":",
"# caller wants to wait for event themselves",
"return",
"[",
"]",
"try",
":",
"return",
"self",
".",
"auth_handler",
".",
"wait_for_response",
"(",
"my_event",
")",
"except",
"BadAuthenticationType",
"as",
"e",
":",
"# if password auth isn't allowed, but keyboard-interactive *is*,",
"# try to fudge it",
"if",
"not",
"fallback",
"or",
"(",
"\"keyboard-interactive\"",
"not",
"in",
"e",
".",
"allowed_types",
")",
":",
"raise",
"try",
":",
"def",
"handler",
"(",
"title",
",",
"instructions",
",",
"fields",
")",
":",
"if",
"len",
"(",
"fields",
")",
">",
"1",
":",
"raise",
"SSHException",
"(",
"\"Fallback authentication failed.\"",
")",
"if",
"len",
"(",
"fields",
")",
"==",
"0",
":",
"# for some reason, at least on os x, a 2nd request will",
"# be made with zero fields requested. maybe it's just",
"# to try to fake out automated scripting of the exact",
"# type we're doing here. *shrug* :)",
"return",
"[",
"]",
"return",
"[",
"password",
"]",
"return",
"self",
".",
"auth_interactive",
"(",
"username",
",",
"handler",
")",
"except",
"SSHException",
":",
"# attempt failed; just raise the original exception",
"raise",
"e"
] | 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 once authentication succeeds or fails. On
success, `is_authenticated` will return ``True``. On failure, you may
use `get_exception` to get more detailed error information.
Since 1.1, if no event is passed, this method will block until the
authentication succeeds or fails. On failure, an exception is raised.
Otherwise, the method simply returns.
Since 1.5, if no event is passed and ``fallback`` is ``True`` (the
default), if the server doesn't support plain password authentication
but does support so-called "keyboard-interactive" mode, an attempt
will be made to authenticate using this interactive mode. If it fails,
the normal exception will be thrown as if the attempt had never been
made. This is useful for some recent Gentoo and Debian distributions,
which turn off plain password authentication in a misguided belief
that interactive authentication is "more secure". (It's not.)
If the server requires multi-step authentication (which is very rare),
this method will return a list of auth types permissible for the next
step. Otherwise, in the normal case, an empty list is returned.
:param str username: the username to authenticate as
:param basestring password: the password to authenticate with
:param .threading.Event event:
an event to trigger when the authentication attempt is complete
(whether it was successful or not)
:param bool fallback:
``True`` if an attempt at an automated "interactive" password auth
should be made if the server doesn't support normal password auth
:return:
list of auth types permissible for the next stage of
authentication (normally empty)
:raises:
`.BadAuthenticationType` -- if password authentication isn't
allowed by the server for this user (and no event was passed in)
:raises:
`.AuthenticationException` -- if the authentication failed (and no
event was passed in)
:raises: `.SSHException` -- if there was a network error | [
"Authenticate",
"to",
"the",
"server",
"using",
"a",
"password",
".",
"The",
"username",
"and",
"password",
"are",
"sent",
"over",
"an",
"encrypted",
"link",
"."
] | cf7d49d66f3b1fbc8b0853518a54050182b3b5eb | https://github.com/paramiko/paramiko/blob/cf7d49d66f3b1fbc8b0853518a54050182b3b5eb/paramiko/transport.py#L1375-L1458 | train |
paramiko/paramiko | paramiko/transport.py | Transport.auth_publickey | 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 triggered once authentication succeeds or fails. On
success, `is_authenticated` will return ``True``. On failure, you may
use `get_exception` to get more detailed error information.
Since 1.1, if no event is passed, this method will block until the
authentication succeeds or fails. On failure, an exception is raised.
Otherwise, the method simply returns.
If the server requires multi-step authentication (which is very rare),
this method will return a list of auth types permissible for the next
step. Otherwise, in the normal case, an empty list is returned.
:param str username: the username to authenticate as
:param .PKey key: the private key to authenticate with
:param .threading.Event event:
an event to trigger when the authentication attempt is complete
(whether it was successful or not)
:return:
list of auth types permissible for the next stage of
authentication (normally empty)
:raises:
`.BadAuthenticationType` -- if public-key authentication isn't
allowed by the server for this user (and no event was passed in)
:raises:
`.AuthenticationException` -- if the authentication failed (and no
event was passed in)
:raises: `.SSHException` -- if there was a network error
"""
if (not self.active) or (not self.initial_kex_done):
# we should never try to authenticate unless we're on a secure link
raise SSHException("No existing session")
if event is None:
my_event = threading.Event()
else:
my_event = event
self.auth_handler = AuthHandler(self)
self.auth_handler.auth_publickey(username, key, my_event)
if event is not None:
# caller wants to wait for event themselves
return []
return self.auth_handler.wait_for_response(my_event) | python | 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 triggered once authentication succeeds or fails. On
success, `is_authenticated` will return ``True``. On failure, you may
use `get_exception` to get more detailed error information.
Since 1.1, if no event is passed, this method will block until the
authentication succeeds or fails. On failure, an exception is raised.
Otherwise, the method simply returns.
If the server requires multi-step authentication (which is very rare),
this method will return a list of auth types permissible for the next
step. Otherwise, in the normal case, an empty list is returned.
:param str username: the username to authenticate as
:param .PKey key: the private key to authenticate with
:param .threading.Event event:
an event to trigger when the authentication attempt is complete
(whether it was successful or not)
:return:
list of auth types permissible for the next stage of
authentication (normally empty)
:raises:
`.BadAuthenticationType` -- if public-key authentication isn't
allowed by the server for this user (and no event was passed in)
:raises:
`.AuthenticationException` -- if the authentication failed (and no
event was passed in)
:raises: `.SSHException` -- if there was a network error
"""
if (not self.active) or (not self.initial_kex_done):
# we should never try to authenticate unless we're on a secure link
raise SSHException("No existing session")
if event is None:
my_event = threading.Event()
else:
my_event = event
self.auth_handler = AuthHandler(self)
self.auth_handler.auth_publickey(username, key, my_event)
if event is not None:
# caller wants to wait for event themselves
return []
return self.auth_handler.wait_for_response(my_event) | [
"def",
"auth_publickey",
"(",
"self",
",",
"username",
",",
"key",
",",
"event",
"=",
"None",
")",
":",
"if",
"(",
"not",
"self",
".",
"active",
")",
"or",
"(",
"not",
"self",
".",
"initial_kex_done",
")",
":",
"# we should never try to authenticate unless we're on a secure link",
"raise",
"SSHException",
"(",
"\"No existing session\"",
")",
"if",
"event",
"is",
"None",
":",
"my_event",
"=",
"threading",
".",
"Event",
"(",
")",
"else",
":",
"my_event",
"=",
"event",
"self",
".",
"auth_handler",
"=",
"AuthHandler",
"(",
"self",
")",
"self",
".",
"auth_handler",
".",
"auth_publickey",
"(",
"username",
",",
"key",
",",
"my_event",
")",
"if",
"event",
"is",
"not",
"None",
":",
"# caller wants to wait for event themselves",
"return",
"[",
"]",
"return",
"self",
".",
"auth_handler",
".",
"wait_for_response",
"(",
"my_event",
")"
] | 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 triggered once authentication succeeds or fails. On
success, `is_authenticated` will return ``True``. On failure, you may
use `get_exception` to get more detailed error information.
Since 1.1, if no event is passed, this method will block until the
authentication succeeds or fails. On failure, an exception is raised.
Otherwise, the method simply returns.
If the server requires multi-step authentication (which is very rare),
this method will return a list of auth types permissible for the next
step. Otherwise, in the normal case, an empty list is returned.
:param str username: the username to authenticate as
:param .PKey key: the private key to authenticate with
:param .threading.Event event:
an event to trigger when the authentication attempt is complete
(whether it was successful or not)
:return:
list of auth types permissible for the next stage of
authentication (normally empty)
:raises:
`.BadAuthenticationType` -- if public-key authentication isn't
allowed by the server for this user (and no event was passed in)
:raises:
`.AuthenticationException` -- if the authentication failed (and no
event was passed in)
:raises: `.SSHException` -- if there was a network error | [
"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",
"."
] | cf7d49d66f3b1fbc8b0853518a54050182b3b5eb | https://github.com/paramiko/paramiko/blob/cf7d49d66f3b1fbc8b0853518a54050182b3b5eb/paramiko/transport.py#L1460-L1507 | train |
paramiko/paramiko | paramiko/transport.py | Transport.auth_interactive | 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 succeeds or fails,
peroidically calling the handler asynchronously to get answers to
authentication questions. The handler may be called more than once
if the server continues to ask questions.
The handler is expected to be a callable that will handle calls of the
form: ``handler(title, instructions, prompt_list)``. The ``title`` is
meant to be a dialog-window title, and the ``instructions`` are user
instructions (both are strings). ``prompt_list`` will be a list of
prompts, each prompt being a tuple of ``(str, bool)``. The string is
the prompt and the boolean indicates whether the user text should be
echoed.
A sample call would thus be:
``handler('title', 'instructions', [('Password:', False)])``.
The handler should return a list or tuple of answers to the server's
questions.
If the server requires multi-step authentication (which is very rare),
this method will return a list of auth types permissible for the next
step. Otherwise, in the normal case, an empty list is returned.
:param str username: the username to authenticate as
:param callable handler: a handler for responding to server questions
:param str submethods: a string list of desired submethods (optional)
:return:
list of auth types permissible for the next stage of
authentication (normally empty).
:raises: `.BadAuthenticationType` -- if public-key authentication isn't
allowed by the server for this user
:raises: `.AuthenticationException` -- if the authentication failed
:raises: `.SSHException` -- if there was a network error
.. versionadded:: 1.5
"""
if (not self.active) or (not self.initial_kex_done):
# we should never try to authenticate unless we're on a secure link
raise SSHException("No existing session")
my_event = threading.Event()
self.auth_handler = AuthHandler(self)
self.auth_handler.auth_interactive(
username, handler, my_event, submethods
)
return self.auth_handler.wait_for_response(my_event) | python | 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 succeeds or fails,
peroidically calling the handler asynchronously to get answers to
authentication questions. The handler may be called more than once
if the server continues to ask questions.
The handler is expected to be a callable that will handle calls of the
form: ``handler(title, instructions, prompt_list)``. The ``title`` is
meant to be a dialog-window title, and the ``instructions`` are user
instructions (both are strings). ``prompt_list`` will be a list of
prompts, each prompt being a tuple of ``(str, bool)``. The string is
the prompt and the boolean indicates whether the user text should be
echoed.
A sample call would thus be:
``handler('title', 'instructions', [('Password:', False)])``.
The handler should return a list or tuple of answers to the server's
questions.
If the server requires multi-step authentication (which is very rare),
this method will return a list of auth types permissible for the next
step. Otherwise, in the normal case, an empty list is returned.
:param str username: the username to authenticate as
:param callable handler: a handler for responding to server questions
:param str submethods: a string list of desired submethods (optional)
:return:
list of auth types permissible for the next stage of
authentication (normally empty).
:raises: `.BadAuthenticationType` -- if public-key authentication isn't
allowed by the server for this user
:raises: `.AuthenticationException` -- if the authentication failed
:raises: `.SSHException` -- if there was a network error
.. versionadded:: 1.5
"""
if (not self.active) or (not self.initial_kex_done):
# we should never try to authenticate unless we're on a secure link
raise SSHException("No existing session")
my_event = threading.Event()
self.auth_handler = AuthHandler(self)
self.auth_handler.auth_interactive(
username, handler, my_event, submethods
)
return self.auth_handler.wait_for_response(my_event) | [
"def",
"auth_interactive",
"(",
"self",
",",
"username",
",",
"handler",
",",
"submethods",
"=",
"\"\"",
")",
":",
"if",
"(",
"not",
"self",
".",
"active",
")",
"or",
"(",
"not",
"self",
".",
"initial_kex_done",
")",
":",
"# we should never try to authenticate unless we're on a secure link",
"raise",
"SSHException",
"(",
"\"No existing session\"",
")",
"my_event",
"=",
"threading",
".",
"Event",
"(",
")",
"self",
".",
"auth_handler",
"=",
"AuthHandler",
"(",
"self",
")",
"self",
".",
"auth_handler",
".",
"auth_interactive",
"(",
"username",
",",
"handler",
",",
"my_event",
",",
"submethods",
")",
"return",
"self",
".",
"auth_handler",
".",
"wait_for_response",
"(",
"my_event",
")"
] | 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 succeeds or fails,
peroidically calling the handler asynchronously to get answers to
authentication questions. The handler may be called more than once
if the server continues to ask questions.
The handler is expected to be a callable that will handle calls of the
form: ``handler(title, instructions, prompt_list)``. The ``title`` is
meant to be a dialog-window title, and the ``instructions`` are user
instructions (both are strings). ``prompt_list`` will be a list of
prompts, each prompt being a tuple of ``(str, bool)``. The string is
the prompt and the boolean indicates whether the user text should be
echoed.
A sample call would thus be:
``handler('title', 'instructions', [('Password:', False)])``.
The handler should return a list or tuple of answers to the server's
questions.
If the server requires multi-step authentication (which is very rare),
this method will return a list of auth types permissible for the next
step. Otherwise, in the normal case, an empty list is returned.
:param str username: the username to authenticate as
:param callable handler: a handler for responding to server questions
:param str submethods: a string list of desired submethods (optional)
:return:
list of auth types permissible for the next stage of
authentication (normally empty).
:raises: `.BadAuthenticationType` -- if public-key authentication isn't
allowed by the server for this user
:raises: `.AuthenticationException` -- if the authentication failed
:raises: `.SSHException` -- if there was a network error
.. versionadded:: 1.5 | [
"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",
"."
] | cf7d49d66f3b1fbc8b0853518a54050182b3b5eb | https://github.com/paramiko/paramiko/blob/cf7d49d66f3b1fbc8b0853518a54050182b3b5eb/paramiko/transport.py#L1509-L1560 | train |
paramiko/paramiko | paramiko/transport.py | Transport.auth_interactive_dumb | 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 then the user has to enter a 2fac token.
"""
if not handler:
def handler(title, instructions, prompt_list):
answers = []
if title:
print(title.strip())
if instructions:
print(instructions.strip())
for prompt, show_input in prompt_list:
print(prompt.strip(), end=" ")
answers.append(input())
return answers
return self.auth_interactive(username, handler, submethods) | python | 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 then the user has to enter a 2fac token.
"""
if not handler:
def handler(title, instructions, prompt_list):
answers = []
if title:
print(title.strip())
if instructions:
print(instructions.strip())
for prompt, show_input in prompt_list:
print(prompt.strip(), end=" ")
answers.append(input())
return answers
return self.auth_interactive(username, handler, submethods) | [
"def",
"auth_interactive_dumb",
"(",
"self",
",",
"username",
",",
"handler",
"=",
"None",
",",
"submethods",
"=",
"\"\"",
")",
":",
"if",
"not",
"handler",
":",
"def",
"handler",
"(",
"title",
",",
"instructions",
",",
"prompt_list",
")",
":",
"answers",
"=",
"[",
"]",
"if",
"title",
":",
"print",
"(",
"title",
".",
"strip",
"(",
")",
")",
"if",
"instructions",
":",
"print",
"(",
"instructions",
".",
"strip",
"(",
")",
")",
"for",
"prompt",
",",
"show_input",
"in",
"prompt_list",
":",
"print",
"(",
"prompt",
".",
"strip",
"(",
")",
",",
"end",
"=",
"\" \"",
")",
"answers",
".",
"append",
"(",
"input",
"(",
")",
")",
"return",
"answers",
"return",
"self",
".",
"auth_interactive",
"(",
"username",
",",
"handler",
",",
"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 then the user has to enter a 2fac token. | [
"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",
"."
] | cf7d49d66f3b1fbc8b0853518a54050182b3b5eb | https://github.com/paramiko/paramiko/blob/cf7d49d66f3b1fbc8b0853518a54050182b3b5eb/paramiko/transport.py#L1562-L1583 | train |
paramiko/paramiko | paramiko/transport.py | Transport.auth_gssapi_with_mic | 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
:return: list of auth types permissible for the next stage of
authentication (normally empty)
:raises: `.BadAuthenticationType` -- if gssapi-with-mic isn't
allowed by the server (and no event was passed in)
:raises:
`.AuthenticationException` -- if the authentication failed (and no
event was passed in)
:raises: `.SSHException` -- if there was a network error
"""
if (not self.active) or (not self.initial_kex_done):
# we should never try to authenticate unless we're on a secure link
raise SSHException("No existing session")
my_event = threading.Event()
self.auth_handler = AuthHandler(self)
self.auth_handler.auth_gssapi_with_mic(
username, gss_host, gss_deleg_creds, my_event
)
return self.auth_handler.wait_for_response(my_event) | python | 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
:return: list of auth types permissible for the next stage of
authentication (normally empty)
:raises: `.BadAuthenticationType` -- if gssapi-with-mic isn't
allowed by the server (and no event was passed in)
:raises:
`.AuthenticationException` -- if the authentication failed (and no
event was passed in)
:raises: `.SSHException` -- if there was a network error
"""
if (not self.active) or (not self.initial_kex_done):
# we should never try to authenticate unless we're on a secure link
raise SSHException("No existing session")
my_event = threading.Event()
self.auth_handler = AuthHandler(self)
self.auth_handler.auth_gssapi_with_mic(
username, gss_host, gss_deleg_creds, my_event
)
return self.auth_handler.wait_for_response(my_event) | [
"def",
"auth_gssapi_with_mic",
"(",
"self",
",",
"username",
",",
"gss_host",
",",
"gss_deleg_creds",
")",
":",
"if",
"(",
"not",
"self",
".",
"active",
")",
"or",
"(",
"not",
"self",
".",
"initial_kex_done",
")",
":",
"# we should never try to authenticate unless we're on a secure link",
"raise",
"SSHException",
"(",
"\"No existing session\"",
")",
"my_event",
"=",
"threading",
".",
"Event",
"(",
")",
"self",
".",
"auth_handler",
"=",
"AuthHandler",
"(",
"self",
")",
"self",
".",
"auth_handler",
".",
"auth_gssapi_with_mic",
"(",
"username",
",",
"gss_host",
",",
"gss_deleg_creds",
",",
"my_event",
")",
"return",
"self",
".",
"auth_handler",
".",
"wait_for_response",
"(",
"my_event",
")"
] | 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
:return: list of auth types permissible for the next stage of
authentication (normally empty)
:raises: `.BadAuthenticationType` -- if gssapi-with-mic isn't
allowed by the server (and no event was passed in)
:raises:
`.AuthenticationException` -- if the authentication failed (and no
event was passed in)
:raises: `.SSHException` -- if there was a network error | [
"Authenticate",
"to",
"the",
"Server",
"using",
"GSS",
"-",
"API",
"/",
"SSPI",
"."
] | cf7d49d66f3b1fbc8b0853518a54050182b3b5eb | https://github.com/paramiko/paramiko/blob/cf7d49d66f3b1fbc8b0853518a54050182b3b5eb/paramiko/transport.py#L1585-L1609 | train |
paramiko/paramiko | paramiko/transport.py | Transport.set_log_channel | 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.
:param str name: new channel name for logging
.. versionadded:: 1.1
"""
self.log_name = name
self.logger = util.get_logger(name)
self.packetizer.set_log(self.logger) | python | 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.
:param str name: new channel name for logging
.. versionadded:: 1.1
"""
self.log_name = name
self.logger = util.get_logger(name)
self.packetizer.set_log(self.logger) | [
"def",
"set_log_channel",
"(",
"self",
",",
"name",
")",
":",
"self",
".",
"log_name",
"=",
"name",
"self",
".",
"logger",
"=",
"util",
".",
"get_logger",
"(",
"name",
")",
"self",
".",
"packetizer",
".",
"set_log",
"(",
"self",
".",
"logger",
")"
] | 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.
:param str name: new channel name for logging
.. versionadded:: 1.1 | [
"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",
"."
] | cf7d49d66f3b1fbc8b0853518a54050182b3b5eb | https://github.com/paramiko/paramiko/blob/cf7d49d66f3b1fbc8b0853518a54050182b3b5eb/paramiko/transport.py#L1634-L1647 | train |
paramiko/paramiko | paramiko/transport.py | Transport._next_channel | 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._channel_counter + 1) & 0xffffff
return chanid | python | 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._channel_counter + 1) & 0xffffff
return chanid | [
"def",
"_next_channel",
"(",
"self",
")",
":",
"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",
".",
"_channel_counter",
"+",
"1",
")",
"&",
"0xffffff",
"return",
"chanid"
] | you are holding the lock | [
"you",
"are",
"holding",
"the",
"lock"
] | cf7d49d66f3b1fbc8b0853518a54050182b3b5eb | https://github.com/paramiko/paramiko/blob/cf7d49d66f3b1fbc8b0853518a54050182b3b5eb/paramiko/transport.py#L1752-L1759 | train |
paramiko/paramiko | paramiko/transport.py | Transport._compute_key | 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
# algorithm, or for e.g. transport tests that don't run kexinit.
hash_algo = getattr(self.kex_engine, "hash_algo", None)
hash_select_msg = "kex engine {} specified hash_algo {!r}".format(
self.kex_engine.__class__.__name__, hash_algo
)
if hash_algo is None:
hash_algo = sha1
hash_select_msg += ", falling back to sha1"
if not hasattr(self, "_logged_hash_selection"):
self._log(DEBUG, hash_select_msg)
setattr(self, "_logged_hash_selection", True)
out = sofar = hash_algo(m.asbytes()).digest()
while len(out) < nbytes:
m = Message()
m.add_mpint(self.K)
m.add_bytes(self.H)
m.add_bytes(sofar)
digest = hash_algo(m.asbytes()).digest()
out += digest
sofar += digest
return out[:nbytes] | python | 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
# algorithm, or for e.g. transport tests that don't run kexinit.
hash_algo = getattr(self.kex_engine, "hash_algo", None)
hash_select_msg = "kex engine {} specified hash_algo {!r}".format(
self.kex_engine.__class__.__name__, hash_algo
)
if hash_algo is None:
hash_algo = sha1
hash_select_msg += ", falling back to sha1"
if not hasattr(self, "_logged_hash_selection"):
self._log(DEBUG, hash_select_msg)
setattr(self, "_logged_hash_selection", True)
out = sofar = hash_algo(m.asbytes()).digest()
while len(out) < nbytes:
m = Message()
m.add_mpint(self.K)
m.add_bytes(self.H)
m.add_bytes(sofar)
digest = hash_algo(m.asbytes()).digest()
out += digest
sofar += digest
return out[:nbytes] | [
"def",
"_compute_key",
"(",
"self",
",",
"id",
",",
"nbytes",
")",
":",
"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",
"# algorithm, or for e.g. transport tests that don't run kexinit.",
"hash_algo",
"=",
"getattr",
"(",
"self",
".",
"kex_engine",
",",
"\"hash_algo\"",
",",
"None",
")",
"hash_select_msg",
"=",
"\"kex engine {} specified hash_algo {!r}\"",
".",
"format",
"(",
"self",
".",
"kex_engine",
".",
"__class__",
".",
"__name__",
",",
"hash_algo",
")",
"if",
"hash_algo",
"is",
"None",
":",
"hash_algo",
"=",
"sha1",
"hash_select_msg",
"+=",
"\", falling back to sha1\"",
"if",
"not",
"hasattr",
"(",
"self",
",",
"\"_logged_hash_selection\"",
")",
":",
"self",
".",
"_log",
"(",
"DEBUG",
",",
"hash_select_msg",
")",
"setattr",
"(",
"self",
",",
"\"_logged_hash_selection\"",
",",
"True",
")",
"out",
"=",
"sofar",
"=",
"hash_algo",
"(",
"m",
".",
"asbytes",
"(",
")",
")",
".",
"digest",
"(",
")",
"while",
"len",
"(",
"out",
")",
"<",
"nbytes",
":",
"m",
"=",
"Message",
"(",
")",
"m",
".",
"add_mpint",
"(",
"self",
".",
"K",
")",
"m",
".",
"add_bytes",
"(",
"self",
".",
"H",
")",
"m",
".",
"add_bytes",
"(",
"sofar",
")",
"digest",
"=",
"hash_algo",
"(",
"m",
".",
"asbytes",
"(",
")",
")",
".",
"digest",
"(",
")",
"out",
"+=",
"digest",
"sofar",
"+=",
"digest",
"return",
"out",
"[",
":",
"nbytes",
"]"
] | id is 'A' - 'F' for the various keys used by ssh | [
"id",
"is",
"A",
"-",
"F",
"for",
"the",
"various",
"keys",
"used",
"by",
"ssh"
] | cf7d49d66f3b1fbc8b0853518a54050182b3b5eb | https://github.com/paramiko/paramiko/blob/cf7d49d66f3b1fbc8b0853518a54050182b3b5eb/paramiko/transport.py#L1821-L1849 | train |
paramiko/paramiko | paramiko/transport.py | Transport._ensure_authed | 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 caller for sending.
Otherwise (client mode, authed, or pre-auth message) returns None.
"""
if (
not self.server_mode
or ptype <= HIGHEST_USERAUTH_MESSAGE_ID
or self.is_authenticated()
):
return None
# WELP. We must be dealing with someone trying to do non-auth things
# without being authed. Tell them off, based on message class.
reply = Message()
# Global requests have no details, just failure.
if ptype == MSG_GLOBAL_REQUEST:
reply.add_byte(cMSG_REQUEST_FAILURE)
# Channel opens let us reject w/ a specific type + message.
elif ptype == MSG_CHANNEL_OPEN:
kind = message.get_text() # noqa
chanid = message.get_int()
reply.add_byte(cMSG_CHANNEL_OPEN_FAILURE)
reply.add_int(chanid)
reply.add_int(OPEN_FAILED_ADMINISTRATIVELY_PROHIBITED)
reply.add_string("")
reply.add_string("en")
# NOTE: Post-open channel messages do not need checking; the above will
# reject attemps to open channels, meaning that even if a malicious
# user tries to send a MSG_CHANNEL_REQUEST, it will simply fall under
# the logic that handles unknown channel IDs (as the channel list will
# be empty.)
return reply | python | 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 caller for sending.
Otherwise (client mode, authed, or pre-auth message) returns None.
"""
if (
not self.server_mode
or ptype <= HIGHEST_USERAUTH_MESSAGE_ID
or self.is_authenticated()
):
return None
# WELP. We must be dealing with someone trying to do non-auth things
# without being authed. Tell them off, based on message class.
reply = Message()
# Global requests have no details, just failure.
if ptype == MSG_GLOBAL_REQUEST:
reply.add_byte(cMSG_REQUEST_FAILURE)
# Channel opens let us reject w/ a specific type + message.
elif ptype == MSG_CHANNEL_OPEN:
kind = message.get_text() # noqa
chanid = message.get_int()
reply.add_byte(cMSG_CHANNEL_OPEN_FAILURE)
reply.add_int(chanid)
reply.add_int(OPEN_FAILED_ADMINISTRATIVELY_PROHIBITED)
reply.add_string("")
reply.add_string("en")
# NOTE: Post-open channel messages do not need checking; the above will
# reject attemps to open channels, meaning that even if a malicious
# user tries to send a MSG_CHANNEL_REQUEST, it will simply fall under
# the logic that handles unknown channel IDs (as the channel list will
# be empty.)
return reply | [
"def",
"_ensure_authed",
"(",
"self",
",",
"ptype",
",",
"message",
")",
":",
"if",
"(",
"not",
"self",
".",
"server_mode",
"or",
"ptype",
"<=",
"HIGHEST_USERAUTH_MESSAGE_ID",
"or",
"self",
".",
"is_authenticated",
"(",
")",
")",
":",
"return",
"None",
"# WELP. We must be dealing with someone trying to do non-auth things",
"# without being authed. Tell them off, based on message class.",
"reply",
"=",
"Message",
"(",
")",
"# Global requests have no details, just failure.",
"if",
"ptype",
"==",
"MSG_GLOBAL_REQUEST",
":",
"reply",
".",
"add_byte",
"(",
"cMSG_REQUEST_FAILURE",
")",
"# Channel opens let us reject w/ a specific type + message.",
"elif",
"ptype",
"==",
"MSG_CHANNEL_OPEN",
":",
"kind",
"=",
"message",
".",
"get_text",
"(",
")",
"# noqa",
"chanid",
"=",
"message",
".",
"get_int",
"(",
")",
"reply",
".",
"add_byte",
"(",
"cMSG_CHANNEL_OPEN_FAILURE",
")",
"reply",
".",
"add_int",
"(",
"chanid",
")",
"reply",
".",
"add_int",
"(",
"OPEN_FAILED_ADMINISTRATIVELY_PROHIBITED",
")",
"reply",
".",
"add_string",
"(",
"\"\"",
")",
"reply",
".",
"add_string",
"(",
"\"en\"",
")",
"# NOTE: Post-open channel messages do not need checking; the above will",
"# reject attemps to open channels, meaning that even if a malicious",
"# user tries to send a MSG_CHANNEL_REQUEST, it will simply fall under",
"# the logic that handles unknown channel IDs (as the channel list will",
"# be empty.)",
"return",
"reply"
] | 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 caller for sending.
Otherwise (client mode, authed, or pre-auth message) returns None. | [
"Checks",
"message",
"type",
"against",
"current",
"auth",
"state",
"."
] | cf7d49d66f3b1fbc8b0853518a54050182b3b5eb | https://github.com/paramiko/paramiko/blob/cf7d49d66f3b1fbc8b0853518a54050182b3b5eb/paramiko/transport.py#L1904-L1940 | train |
paramiko/paramiko | paramiko/transport.py | Transport._activate_outbound | 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:
IV_out = self._compute_key("B", block_size)
key_out = self._compute_key(
"D", self._cipher_info[self.local_cipher]["key-size"]
)
else:
IV_out = self._compute_key("A", block_size)
key_out = self._compute_key(
"C", self._cipher_info[self.local_cipher]["key-size"]
)
engine = self._get_cipher(
self.local_cipher, key_out, IV_out, self._ENCRYPT
)
mac_size = self._mac_info[self.local_mac]["size"]
mac_engine = self._mac_info[self.local_mac]["class"]
# initial mac keys are done in the hash's natural size (not the
# potentially truncated transmission size)
if self.server_mode:
mac_key = self._compute_key("F", mac_engine().digest_size)
else:
mac_key = self._compute_key("E", mac_engine().digest_size)
sdctr = self.local_cipher.endswith("-ctr")
self.packetizer.set_outbound_cipher(
engine, block_size, mac_engine, mac_size, mac_key, sdctr
)
compress_out = self._compression_info[self.local_compression][0]
if compress_out is not None and (
self.local_compression != "zlib@openssh.com" or self.authenticated
):
self._log(DEBUG, "Switching on outbound compression ...")
self.packetizer.set_outbound_compressor(compress_out())
if not self.packetizer.need_rekey():
self.in_kex = False
# we always expect to receive NEWKEYS now
self._expect_packet(MSG_NEWKEYS) | python | 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:
IV_out = self._compute_key("B", block_size)
key_out = self._compute_key(
"D", self._cipher_info[self.local_cipher]["key-size"]
)
else:
IV_out = self._compute_key("A", block_size)
key_out = self._compute_key(
"C", self._cipher_info[self.local_cipher]["key-size"]
)
engine = self._get_cipher(
self.local_cipher, key_out, IV_out, self._ENCRYPT
)
mac_size = self._mac_info[self.local_mac]["size"]
mac_engine = self._mac_info[self.local_mac]["class"]
# initial mac keys are done in the hash's natural size (not the
# potentially truncated transmission size)
if self.server_mode:
mac_key = self._compute_key("F", mac_engine().digest_size)
else:
mac_key = self._compute_key("E", mac_engine().digest_size)
sdctr = self.local_cipher.endswith("-ctr")
self.packetizer.set_outbound_cipher(
engine, block_size, mac_engine, mac_size, mac_key, sdctr
)
compress_out = self._compression_info[self.local_compression][0]
if compress_out is not None and (
self.local_compression != "zlib@openssh.com" or self.authenticated
):
self._log(DEBUG, "Switching on outbound compression ...")
self.packetizer.set_outbound_compressor(compress_out())
if not self.packetizer.need_rekey():
self.in_kex = False
# we always expect to receive NEWKEYS now
self._expect_packet(MSG_NEWKEYS) | [
"def",
"_activate_outbound",
"(",
"self",
")",
":",
"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",
":",
"IV_out",
"=",
"self",
".",
"_compute_key",
"(",
"\"B\"",
",",
"block_size",
")",
"key_out",
"=",
"self",
".",
"_compute_key",
"(",
"\"D\"",
",",
"self",
".",
"_cipher_info",
"[",
"self",
".",
"local_cipher",
"]",
"[",
"\"key-size\"",
"]",
")",
"else",
":",
"IV_out",
"=",
"self",
".",
"_compute_key",
"(",
"\"A\"",
",",
"block_size",
")",
"key_out",
"=",
"self",
".",
"_compute_key",
"(",
"\"C\"",
",",
"self",
".",
"_cipher_info",
"[",
"self",
".",
"local_cipher",
"]",
"[",
"\"key-size\"",
"]",
")",
"engine",
"=",
"self",
".",
"_get_cipher",
"(",
"self",
".",
"local_cipher",
",",
"key_out",
",",
"IV_out",
",",
"self",
".",
"_ENCRYPT",
")",
"mac_size",
"=",
"self",
".",
"_mac_info",
"[",
"self",
".",
"local_mac",
"]",
"[",
"\"size\"",
"]",
"mac_engine",
"=",
"self",
".",
"_mac_info",
"[",
"self",
".",
"local_mac",
"]",
"[",
"\"class\"",
"]",
"# initial mac keys are done in the hash's natural size (not the",
"# potentially truncated transmission size)",
"if",
"self",
".",
"server_mode",
":",
"mac_key",
"=",
"self",
".",
"_compute_key",
"(",
"\"F\"",
",",
"mac_engine",
"(",
")",
".",
"digest_size",
")",
"else",
":",
"mac_key",
"=",
"self",
".",
"_compute_key",
"(",
"\"E\"",
",",
"mac_engine",
"(",
")",
".",
"digest_size",
")",
"sdctr",
"=",
"self",
".",
"local_cipher",
".",
"endswith",
"(",
"\"-ctr\"",
")",
"self",
".",
"packetizer",
".",
"set_outbound_cipher",
"(",
"engine",
",",
"block_size",
",",
"mac_engine",
",",
"mac_size",
",",
"mac_key",
",",
"sdctr",
")",
"compress_out",
"=",
"self",
".",
"_compression_info",
"[",
"self",
".",
"local_compression",
"]",
"[",
"0",
"]",
"if",
"compress_out",
"is",
"not",
"None",
"and",
"(",
"self",
".",
"local_compression",
"!=",
"\"zlib@openssh.com\"",
"or",
"self",
".",
"authenticated",
")",
":",
"self",
".",
"_log",
"(",
"DEBUG",
",",
"\"Switching on outbound compression ...\"",
")",
"self",
".",
"packetizer",
".",
"set_outbound_compressor",
"(",
"compress_out",
"(",
")",
")",
"if",
"not",
"self",
".",
"packetizer",
".",
"need_rekey",
"(",
")",
":",
"self",
".",
"in_kex",
"=",
"False",
"# we always expect to receive NEWKEYS now",
"self",
".",
"_expect_packet",
"(",
"MSG_NEWKEYS",
")"
] | switch on newly negotiated encryption parameters for
outbound traffic | [
"switch",
"on",
"newly",
"negotiated",
"encryption",
"parameters",
"for",
"outbound",
"traffic"
] | cf7d49d66f3b1fbc8b0853518a54050182b3b5eb | https://github.com/paramiko/paramiko/blob/cf7d49d66f3b1fbc8b0853518a54050182b3b5eb/paramiko/transport.py#L2461-L2502 | train |
paramiko/paramiko | paramiko/file.py | BufferedFile.flush | 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 | python | 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 | [
"def",
"flush",
"(",
"self",
")",
":",
"self",
".",
"_write_all",
"(",
"self",
".",
"_wbuffer",
".",
"getvalue",
"(",
")",
")",
"self",
".",
"_wbuffer",
"=",
"BytesIO",
"(",
")",
"return"
] | Write out any data in the write buffer. This may do nothing if write
buffering is not turned on. | [
"Write",
"out",
"any",
"data",
"in",
"the",
"write",
"buffer",
".",
"This",
"may",
"do",
"nothing",
"if",
"write",
"buffering",
"is",
"not",
"turned",
"on",
"."
] | cf7d49d66f3b1fbc8b0853518a54050182b3b5eb | https://github.com/paramiko/paramiko/blob/cf7d49d66f3b1fbc8b0853518a54050182b3b5eb/paramiko/file.py#L87-L94 | train |
paramiko/paramiko | paramiko/file.py | BufferedFile.readinto | 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) | python | 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) | [
"def",
"readinto",
"(",
"self",
",",
"buff",
")",
":",
"data",
"=",
"self",
".",
"read",
"(",
"len",
"(",
"buff",
")",
")",
"buff",
"[",
":",
"len",
"(",
"data",
")",
"]",
"=",
"data",
"return",
"len",
"(",
"data",
")"
] | Read up to ``len(buff)`` bytes into ``bytearray`` *buff* and return the
number of bytes read.
:returns:
The number of bytes read. | [
"Read",
"up",
"to",
"len",
"(",
"buff",
")",
"bytes",
"into",
"bytearray",
"*",
"buff",
"*",
"and",
"return",
"the",
"number",
"of",
"bytes",
"read",
"."
] | cf7d49d66f3b1fbc8b0853518a54050182b3b5eb | https://github.com/paramiko/paramiko/blob/cf7d49d66f3b1fbc8b0853518a54050182b3b5eb/paramiko/file.py#L160-L170 | train |
paramiko/paramiko | paramiko/file.py | BufferedFile.readlines | 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 internal buffer size) are read.
:param int sizehint: desired maximum number of bytes to read.
:returns: list of lines read from the file.
"""
lines = []
byte_count = 0
while True:
line = self.readline()
if len(line) == 0:
break
lines.append(line)
byte_count += len(line)
if (sizehint is not None) and (byte_count >= sizehint):
break
return lines | python | 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 internal buffer size) are read.
:param int sizehint: desired maximum number of bytes to read.
:returns: list of lines read from the file.
"""
lines = []
byte_count = 0
while True:
line = self.readline()
if len(line) == 0:
break
lines.append(line)
byte_count += len(line)
if (sizehint is not None) and (byte_count >= sizehint):
break
return lines | [
"def",
"readlines",
"(",
"self",
",",
"sizehint",
"=",
"None",
")",
":",
"lines",
"=",
"[",
"]",
"byte_count",
"=",
"0",
"while",
"True",
":",
"line",
"=",
"self",
".",
"readline",
"(",
")",
"if",
"len",
"(",
"line",
")",
"==",
"0",
":",
"break",
"lines",
".",
"append",
"(",
"line",
")",
"byte_count",
"+=",
"len",
"(",
"line",
")",
"if",
"(",
"sizehint",
"is",
"not",
"None",
")",
"and",
"(",
"byte_count",
">=",
"sizehint",
")",
":",
"break",
"return",
"lines"
] | 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.
:param int sizehint: desired maximum number of bytes to read.
:returns: list of lines read from the file. | [
"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",
"."
] | cf7d49d66f3b1fbc8b0853518a54050182b3b5eb | https://github.com/paramiko/paramiko/blob/cf7d49d66f3b1fbc8b0853518a54050182b3b5eb/paramiko/file.py#L336-L356 | train |
paramiko/paramiko | paramiko/file.py | BufferedFile.write | 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``/``bytes`` data to write
"""
if isinstance(data, text_type):
# Accept text and encode as utf-8 for compatibility only.
data = data.encode("utf-8")
if self._closed:
raise IOError("File is closed")
if not (self._flags & self.FLAG_WRITE):
raise IOError("File not open for writing")
if not (self._flags & self.FLAG_BUFFERED):
self._write_all(data)
return
self._wbuffer.write(data)
if self._flags & self.FLAG_LINE_BUFFERED:
# only scan the new data for linefeed, to avoid wasting time.
last_newline_pos = data.rfind(linefeed_byte)
if last_newline_pos >= 0:
wbuf = self._wbuffer.getvalue()
last_newline_pos += len(wbuf) - len(data)
self._write_all(wbuf[: last_newline_pos + 1])
self._wbuffer = BytesIO()
self._wbuffer.write(wbuf[last_newline_pos + 1 :])
return
# even if we're line buffering, if the buffer has grown past the
# buffer size, force a flush.
if self._wbuffer.tell() >= self._bufsize:
self.flush()
return | python | 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``/``bytes`` data to write
"""
if isinstance(data, text_type):
# Accept text and encode as utf-8 for compatibility only.
data = data.encode("utf-8")
if self._closed:
raise IOError("File is closed")
if not (self._flags & self.FLAG_WRITE):
raise IOError("File not open for writing")
if not (self._flags & self.FLAG_BUFFERED):
self._write_all(data)
return
self._wbuffer.write(data)
if self._flags & self.FLAG_LINE_BUFFERED:
# only scan the new data for linefeed, to avoid wasting time.
last_newline_pos = data.rfind(linefeed_byte)
if last_newline_pos >= 0:
wbuf = self._wbuffer.getvalue()
last_newline_pos += len(wbuf) - len(data)
self._write_all(wbuf[: last_newline_pos + 1])
self._wbuffer = BytesIO()
self._wbuffer.write(wbuf[last_newline_pos + 1 :])
return
# even if we're line buffering, if the buffer has grown past the
# buffer size, force a flush.
if self._wbuffer.tell() >= self._bufsize:
self.flush()
return | [
"def",
"write",
"(",
"self",
",",
"data",
")",
":",
"if",
"isinstance",
"(",
"data",
",",
"text_type",
")",
":",
"# Accept text and encode as utf-8 for compatibility only.",
"data",
"=",
"data",
".",
"encode",
"(",
"\"utf-8\"",
")",
"if",
"self",
".",
"_closed",
":",
"raise",
"IOError",
"(",
"\"File is closed\"",
")",
"if",
"not",
"(",
"self",
".",
"_flags",
"&",
"self",
".",
"FLAG_WRITE",
")",
":",
"raise",
"IOError",
"(",
"\"File not open for writing\"",
")",
"if",
"not",
"(",
"self",
".",
"_flags",
"&",
"self",
".",
"FLAG_BUFFERED",
")",
":",
"self",
".",
"_write_all",
"(",
"data",
")",
"return",
"self",
".",
"_wbuffer",
".",
"write",
"(",
"data",
")",
"if",
"self",
".",
"_flags",
"&",
"self",
".",
"FLAG_LINE_BUFFERED",
":",
"# only scan the new data for linefeed, to avoid wasting time.",
"last_newline_pos",
"=",
"data",
".",
"rfind",
"(",
"linefeed_byte",
")",
"if",
"last_newline_pos",
">=",
"0",
":",
"wbuf",
"=",
"self",
".",
"_wbuffer",
".",
"getvalue",
"(",
")",
"last_newline_pos",
"+=",
"len",
"(",
"wbuf",
")",
"-",
"len",
"(",
"data",
")",
"self",
".",
"_write_all",
"(",
"wbuf",
"[",
":",
"last_newline_pos",
"+",
"1",
"]",
")",
"self",
".",
"_wbuffer",
"=",
"BytesIO",
"(",
")",
"self",
".",
"_wbuffer",
".",
"write",
"(",
"wbuf",
"[",
"last_newline_pos",
"+",
"1",
":",
"]",
")",
"return",
"# even if we're line buffering, if the buffer has grown past the",
"# buffer size, force a flush.",
"if",
"self",
".",
"_wbuffer",
".",
"tell",
"(",
")",
">=",
"self",
".",
"_bufsize",
":",
"self",
".",
"flush",
"(",
")",
"return"
] | 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``/``bytes`` data to write | [
"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",
".",
")"
] | cf7d49d66f3b1fbc8b0853518a54050182b3b5eb | https://github.com/paramiko/paramiko/blob/cf7d49d66f3b1fbc8b0853518a54050182b3b5eb/paramiko/file.py#L388-L422 | train |
paramiko/paramiko | paramiko/hostkeys.py | HostKeys.add | 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 .PKey key: the key to add
"""
for e in self._entries:
if (hostname in e.hostnames) and (e.key.get_name() == keytype):
e.key = key
return
self._entries.append(HostKeyEntry([hostname], key)) | python | 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 .PKey key: the key to add
"""
for e in self._entries:
if (hostname in e.hostnames) and (e.key.get_name() == keytype):
e.key = key
return
self._entries.append(HostKeyEntry([hostname], key)) | [
"def",
"add",
"(",
"self",
",",
"hostname",
",",
"keytype",
",",
"key",
")",
":",
"for",
"e",
"in",
"self",
".",
"_entries",
":",
"if",
"(",
"hostname",
"in",
"e",
".",
"hostnames",
")",
"and",
"(",
"e",
".",
"key",
".",
"get_name",
"(",
")",
"==",
"keytype",
")",
":",
"e",
".",
"key",
"=",
"key",
"return",
"self",
".",
"_entries",
".",
"append",
"(",
"HostKeyEntry",
"(",
"[",
"hostname",
"]",
",",
"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 .PKey key: the key to add | [
"Add",
"a",
"host",
"key",
"entry",
"to",
"the",
"table",
".",
"Any",
"existing",
"entry",
"for",
"a",
"(",
"hostname",
"keytype",
")",
"pair",
"will",
"be",
"replaced",
"."
] | cf7d49d66f3b1fbc8b0853518a54050182b3b5eb | https://github.com/paramiko/paramiko/blob/cf7d49d66f3b1fbc8b0853518a54050182b3b5eb/paramiko/hostkeys.py#L61-L74 | train |
paramiko/paramiko | paramiko/hostkeys.py | HostKeys.load | 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 multiple times, the host keys are merged,
not cleared. So multiple calls to `load` will just call `add`,
replacing any existing entries and adding new ones.
:param str filename: name of the file to read host keys from
:raises: ``IOError`` -- if there was an error reading the file
"""
with open(filename, "r") as f:
for lineno, line in enumerate(f, 1):
line = line.strip()
if (len(line) == 0) or (line[0] == "#"):
continue
try:
e = HostKeyEntry.from_line(line, lineno)
except SSHException:
continue
if e is not None:
_hostnames = e.hostnames
for h in _hostnames:
if self.check(h, e.key):
e.hostnames.remove(h)
if len(e.hostnames):
self._entries.append(e) | python | 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 multiple times, the host keys are merged,
not cleared. So multiple calls to `load` will just call `add`,
replacing any existing entries and adding new ones.
:param str filename: name of the file to read host keys from
:raises: ``IOError`` -- if there was an error reading the file
"""
with open(filename, "r") as f:
for lineno, line in enumerate(f, 1):
line = line.strip()
if (len(line) == 0) or (line[0] == "#"):
continue
try:
e = HostKeyEntry.from_line(line, lineno)
except SSHException:
continue
if e is not None:
_hostnames = e.hostnames
for h in _hostnames:
if self.check(h, e.key):
e.hostnames.remove(h)
if len(e.hostnames):
self._entries.append(e) | [
"def",
"load",
"(",
"self",
",",
"filename",
")",
":",
"with",
"open",
"(",
"filename",
",",
"\"r\"",
")",
"as",
"f",
":",
"for",
"lineno",
",",
"line",
"in",
"enumerate",
"(",
"f",
",",
"1",
")",
":",
"line",
"=",
"line",
".",
"strip",
"(",
")",
"if",
"(",
"len",
"(",
"line",
")",
"==",
"0",
")",
"or",
"(",
"line",
"[",
"0",
"]",
"==",
"\"#\"",
")",
":",
"continue",
"try",
":",
"e",
"=",
"HostKeyEntry",
".",
"from_line",
"(",
"line",
",",
"lineno",
")",
"except",
"SSHException",
":",
"continue",
"if",
"e",
"is",
"not",
"None",
":",
"_hostnames",
"=",
"e",
".",
"hostnames",
"for",
"h",
"in",
"_hostnames",
":",
"if",
"self",
".",
"check",
"(",
"h",
",",
"e",
".",
"key",
")",
":",
"e",
".",
"hostnames",
".",
"remove",
"(",
"h",
")",
"if",
"len",
"(",
"e",
".",
"hostnames",
")",
":",
"self",
".",
"_entries",
".",
"append",
"(",
"e",
")"
] | 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 multiple times, the host keys are merged,
not cleared. So multiple calls to `load` will just call `add`,
replacing any existing entries and adding new ones.
:param str filename: name of the file to read host keys from
:raises: ``IOError`` -- if there was an error reading the file | [
"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",
")",
"."
] | cf7d49d66f3b1fbc8b0853518a54050182b3b5eb | https://github.com/paramiko/paramiko/blob/cf7d49d66f3b1fbc8b0853518a54050182b3b5eb/paramiko/hostkeys.py#L76-L106 | train |
paramiko/paramiko | paramiko/hostkeys.py | HostKeys.lookup | 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 IP) to lookup
:return: dict of `str` -> `.PKey` keys associated with this host
(or ``None``)
"""
class SubDict(MutableMapping):
def __init__(self, hostname, entries, hostkeys):
self._hostname = hostname
self._entries = entries
self._hostkeys = hostkeys
def __iter__(self):
for k in self.keys():
yield k
def __len__(self):
return len(self.keys())
def __delitem__(self, key):
for e in list(self._entries):
if e.key.get_name() == key:
self._entries.remove(e)
else:
raise KeyError(key)
def __getitem__(self, key):
for e in self._entries:
if e.key.get_name() == key:
return e.key
raise KeyError(key)
def __setitem__(self, key, val):
for e in self._entries:
if e.key is None:
continue
if e.key.get_name() == key:
# replace
e.key = val
break
else:
# add a new one
e = HostKeyEntry([hostname], val)
self._entries.append(e)
self._hostkeys._entries.append(e)
def keys(self):
return [
e.key.get_name()
for e in self._entries
if e.key is not None
]
entries = []
for e in self._entries:
if self._hostname_matches(hostname, e):
entries.append(e)
if len(entries) == 0:
return None
return SubDict(hostname, entries, self) | python | 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 IP) to lookup
:return: dict of `str` -> `.PKey` keys associated with this host
(or ``None``)
"""
class SubDict(MutableMapping):
def __init__(self, hostname, entries, hostkeys):
self._hostname = hostname
self._entries = entries
self._hostkeys = hostkeys
def __iter__(self):
for k in self.keys():
yield k
def __len__(self):
return len(self.keys())
def __delitem__(self, key):
for e in list(self._entries):
if e.key.get_name() == key:
self._entries.remove(e)
else:
raise KeyError(key)
def __getitem__(self, key):
for e in self._entries:
if e.key.get_name() == key:
return e.key
raise KeyError(key)
def __setitem__(self, key, val):
for e in self._entries:
if e.key is None:
continue
if e.key.get_name() == key:
# replace
e.key = val
break
else:
# add a new one
e = HostKeyEntry([hostname], val)
self._entries.append(e)
self._hostkeys._entries.append(e)
def keys(self):
return [
e.key.get_name()
for e in self._entries
if e.key is not None
]
entries = []
for e in self._entries:
if self._hostname_matches(hostname, e):
entries.append(e)
if len(entries) == 0:
return None
return SubDict(hostname, entries, self) | [
"def",
"lookup",
"(",
"self",
",",
"hostname",
")",
":",
"class",
"SubDict",
"(",
"MutableMapping",
")",
":",
"def",
"__init__",
"(",
"self",
",",
"hostname",
",",
"entries",
",",
"hostkeys",
")",
":",
"self",
".",
"_hostname",
"=",
"hostname",
"self",
".",
"_entries",
"=",
"entries",
"self",
".",
"_hostkeys",
"=",
"hostkeys",
"def",
"__iter__",
"(",
"self",
")",
":",
"for",
"k",
"in",
"self",
".",
"keys",
"(",
")",
":",
"yield",
"k",
"def",
"__len__",
"(",
"self",
")",
":",
"return",
"len",
"(",
"self",
".",
"keys",
"(",
")",
")",
"def",
"__delitem__",
"(",
"self",
",",
"key",
")",
":",
"for",
"e",
"in",
"list",
"(",
"self",
".",
"_entries",
")",
":",
"if",
"e",
".",
"key",
".",
"get_name",
"(",
")",
"==",
"key",
":",
"self",
".",
"_entries",
".",
"remove",
"(",
"e",
")",
"else",
":",
"raise",
"KeyError",
"(",
"key",
")",
"def",
"__getitem__",
"(",
"self",
",",
"key",
")",
":",
"for",
"e",
"in",
"self",
".",
"_entries",
":",
"if",
"e",
".",
"key",
".",
"get_name",
"(",
")",
"==",
"key",
":",
"return",
"e",
".",
"key",
"raise",
"KeyError",
"(",
"key",
")",
"def",
"__setitem__",
"(",
"self",
",",
"key",
",",
"val",
")",
":",
"for",
"e",
"in",
"self",
".",
"_entries",
":",
"if",
"e",
".",
"key",
"is",
"None",
":",
"continue",
"if",
"e",
".",
"key",
".",
"get_name",
"(",
")",
"==",
"key",
":",
"# replace",
"e",
".",
"key",
"=",
"val",
"break",
"else",
":",
"# add a new one",
"e",
"=",
"HostKeyEntry",
"(",
"[",
"hostname",
"]",
",",
"val",
")",
"self",
".",
"_entries",
".",
"append",
"(",
"e",
")",
"self",
".",
"_hostkeys",
".",
"_entries",
".",
"append",
"(",
"e",
")",
"def",
"keys",
"(",
"self",
")",
":",
"return",
"[",
"e",
".",
"key",
".",
"get_name",
"(",
")",
"for",
"e",
"in",
"self",
".",
"_entries",
"if",
"e",
".",
"key",
"is",
"not",
"None",
"]",
"entries",
"=",
"[",
"]",
"for",
"e",
"in",
"self",
".",
"_entries",
":",
"if",
"self",
".",
"_hostname_matches",
"(",
"hostname",
",",
"e",
")",
":",
"entries",
".",
"append",
"(",
"e",
")",
"if",
"len",
"(",
"entries",
")",
"==",
"0",
":",
"return",
"None",
"return",
"SubDict",
"(",
"hostname",
",",
"entries",
",",
"self",
")"
] | 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 IP) to lookup
:return: dict of `str` -> `.PKey` keys associated with this host
(or ``None``) | [
"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",
"."
] | cf7d49d66f3b1fbc8b0853518a54050182b3b5eb | https://github.com/paramiko/paramiko/blob/cf7d49d66f3b1fbc8b0853518a54050182b3b5eb/paramiko/hostkeys.py#L127-L191 | train |
paramiko/paramiko | paramiko/hostkeys.py | HostKeys._hostname_matches | 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 hostname.startswith("|1|")
and constant_time_bytes_eq(self.hash_host(hostname, h), h)
):
return True
return False | python | 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 hostname.startswith("|1|")
and constant_time_bytes_eq(self.hash_host(hostname, h), h)
):
return True
return False | [
"def",
"_hostname_matches",
"(",
"self",
",",
"hostname",
",",
"entry",
")",
":",
"for",
"h",
"in",
"entry",
".",
"hostnames",
":",
"if",
"(",
"h",
"==",
"hostname",
"or",
"h",
".",
"startswith",
"(",
"\"|1|\"",
")",
"and",
"not",
"hostname",
".",
"startswith",
"(",
"\"|1|\"",
")",
"and",
"constant_time_bytes_eq",
"(",
"self",
".",
"hash_host",
"(",
"hostname",
",",
"h",
")",
",",
"h",
")",
")",
":",
"return",
"True",
"return",
"False"
] | Tests whether ``hostname`` string matches given SubDict ``entry``.
:returns bool: | [
"Tests",
"whether",
"hostname",
"string",
"matches",
"given",
"SubDict",
"entry",
"."
] | cf7d49d66f3b1fbc8b0853518a54050182b3b5eb | https://github.com/paramiko/paramiko/blob/cf7d49d66f3b1fbc8b0853518a54050182b3b5eb/paramiko/hostkeys.py#L193-L207 | train |
paramiko/paramiko | paramiko/hostkeys.py | HostKeyEntry.from_line | 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 whitespace.
We don't bother to check for comments or empty lines. All of
that should be taken care of before sending the line to us.
:param str line: a line from an OpenSSH known_hosts file
"""
log = get_logger("paramiko.hostkeys")
fields = line.split(" ")
if len(fields) < 3:
# Bad number of fields
msg = "Not enough fields found in known_hosts in line {} ({!r})"
log.info(msg.format(lineno, line))
return None
fields = fields[:3]
names, keytype, key = fields
names = names.split(",")
# Decide what kind of key we're looking at and create an object
# to hold it accordingly.
try:
key = b(key)
if keytype == "ssh-rsa":
key = RSAKey(data=decodebytes(key))
elif keytype == "ssh-dss":
key = DSSKey(data=decodebytes(key))
elif keytype in ECDSAKey.supported_key_format_identifiers():
key = ECDSAKey(data=decodebytes(key), validate_point=False)
elif keytype == "ssh-ed25519":
key = Ed25519Key(data=decodebytes(key))
else:
log.info("Unable to handle key of type {}".format(keytype))
return None
except binascii.Error as e:
raise InvalidHostKey(line, e)
return cls(names, key) | python | 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 whitespace.
We don't bother to check for comments or empty lines. All of
that should be taken care of before sending the line to us.
:param str line: a line from an OpenSSH known_hosts file
"""
log = get_logger("paramiko.hostkeys")
fields = line.split(" ")
if len(fields) < 3:
# Bad number of fields
msg = "Not enough fields found in known_hosts in line {} ({!r})"
log.info(msg.format(lineno, line))
return None
fields = fields[:3]
names, keytype, key = fields
names = names.split(",")
# Decide what kind of key we're looking at and create an object
# to hold it accordingly.
try:
key = b(key)
if keytype == "ssh-rsa":
key = RSAKey(data=decodebytes(key))
elif keytype == "ssh-dss":
key = DSSKey(data=decodebytes(key))
elif keytype in ECDSAKey.supported_key_format_identifiers():
key = ECDSAKey(data=decodebytes(key), validate_point=False)
elif keytype == "ssh-ed25519":
key = Ed25519Key(data=decodebytes(key))
else:
log.info("Unable to handle key of type {}".format(keytype))
return None
except binascii.Error as e:
raise InvalidHostKey(line, e)
return cls(names, key) | [
"def",
"from_line",
"(",
"cls",
",",
"line",
",",
"lineno",
"=",
"None",
")",
":",
"log",
"=",
"get_logger",
"(",
"\"paramiko.hostkeys\"",
")",
"fields",
"=",
"line",
".",
"split",
"(",
"\" \"",
")",
"if",
"len",
"(",
"fields",
")",
"<",
"3",
":",
"# Bad number of fields",
"msg",
"=",
"\"Not enough fields found in known_hosts in line {} ({!r})\"",
"log",
".",
"info",
"(",
"msg",
".",
"format",
"(",
"lineno",
",",
"line",
")",
")",
"return",
"None",
"fields",
"=",
"fields",
"[",
":",
"3",
"]",
"names",
",",
"keytype",
",",
"key",
"=",
"fields",
"names",
"=",
"names",
".",
"split",
"(",
"\",\"",
")",
"# Decide what kind of key we're looking at and create an object",
"# to hold it accordingly.",
"try",
":",
"key",
"=",
"b",
"(",
"key",
")",
"if",
"keytype",
"==",
"\"ssh-rsa\"",
":",
"key",
"=",
"RSAKey",
"(",
"data",
"=",
"decodebytes",
"(",
"key",
")",
")",
"elif",
"keytype",
"==",
"\"ssh-dss\"",
":",
"key",
"=",
"DSSKey",
"(",
"data",
"=",
"decodebytes",
"(",
"key",
")",
")",
"elif",
"keytype",
"in",
"ECDSAKey",
".",
"supported_key_format_identifiers",
"(",
")",
":",
"key",
"=",
"ECDSAKey",
"(",
"data",
"=",
"decodebytes",
"(",
"key",
")",
",",
"validate_point",
"=",
"False",
")",
"elif",
"keytype",
"==",
"\"ssh-ed25519\"",
":",
"key",
"=",
"Ed25519Key",
"(",
"data",
"=",
"decodebytes",
"(",
"key",
")",
")",
"else",
":",
"log",
".",
"info",
"(",
"\"Unable to handle key of type {}\"",
".",
"format",
"(",
"keytype",
")",
")",
"return",
"None",
"except",
"binascii",
".",
"Error",
"as",
"e",
":",
"raise",
"InvalidHostKey",
"(",
"line",
",",
"e",
")",
"return",
"cls",
"(",
"names",
",",
"key",
")"
] | 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 whitespace.
We don't bother to check for comments or empty lines. All of
that should be taken care of before sending the line to us.
:param str line: a line from an OpenSSH known_hosts file | [
"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",
"."
] | cf7d49d66f3b1fbc8b0853518a54050182b3b5eb | https://github.com/paramiko/paramiko/blob/cf7d49d66f3b1fbc8b0853518a54050182b3b5eb/paramiko/hostkeys.py#L327-L370 | train |
paramiko/paramiko | paramiko/win_pageant.py | _query_pageant | 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 mmap
map_name = "PageantRequest%08x" % thread.get_ident()
pymap = _winapi.MemoryMap(
map_name, _AGENT_MAX_MSGLEN, _winapi.get_security_attributes_for_user()
)
with pymap:
pymap.write(msg)
# Create an array buffer containing the mapped filename
char_buffer = array.array("b", b(map_name) + zero_byte) # noqa
char_buffer_address, char_buffer_size = char_buffer.buffer_info()
# Create a string to use for the SendMessage function call
cds = COPYDATASTRUCT(
_AGENT_COPYDATA_ID, char_buffer_size, char_buffer_address
)
response = ctypes.windll.user32.SendMessageA(
hwnd, win32con_WM_COPYDATA, ctypes.sizeof(cds), ctypes.byref(cds)
)
if response > 0:
pymap.seek(0)
datalen = pymap.read(4)
retlen = struct.unpack(">I", datalen)[0]
return datalen + pymap.read(retlen)
return None | python | 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 mmap
map_name = "PageantRequest%08x" % thread.get_ident()
pymap = _winapi.MemoryMap(
map_name, _AGENT_MAX_MSGLEN, _winapi.get_security_attributes_for_user()
)
with pymap:
pymap.write(msg)
# Create an array buffer containing the mapped filename
char_buffer = array.array("b", b(map_name) + zero_byte) # noqa
char_buffer_address, char_buffer_size = char_buffer.buffer_info()
# Create a string to use for the SendMessage function call
cds = COPYDATASTRUCT(
_AGENT_COPYDATA_ID, char_buffer_size, char_buffer_address
)
response = ctypes.windll.user32.SendMessageA(
hwnd, win32con_WM_COPYDATA, ctypes.sizeof(cds), ctypes.byref(cds)
)
if response > 0:
pymap.seek(0)
datalen = pymap.read(4)
retlen = struct.unpack(">I", datalen)[0]
return datalen + pymap.read(retlen)
return None | [
"def",
"_query_pageant",
"(",
"msg",
")",
":",
"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 mmap",
"map_name",
"=",
"\"PageantRequest%08x\"",
"%",
"thread",
".",
"get_ident",
"(",
")",
"pymap",
"=",
"_winapi",
".",
"MemoryMap",
"(",
"map_name",
",",
"_AGENT_MAX_MSGLEN",
",",
"_winapi",
".",
"get_security_attributes_for_user",
"(",
")",
")",
"with",
"pymap",
":",
"pymap",
".",
"write",
"(",
"msg",
")",
"# Create an array buffer containing the mapped filename",
"char_buffer",
"=",
"array",
".",
"array",
"(",
"\"b\"",
",",
"b",
"(",
"map_name",
")",
"+",
"zero_byte",
")",
"# noqa",
"char_buffer_address",
",",
"char_buffer_size",
"=",
"char_buffer",
".",
"buffer_info",
"(",
")",
"# Create a string to use for the SendMessage function call",
"cds",
"=",
"COPYDATASTRUCT",
"(",
"_AGENT_COPYDATA_ID",
",",
"char_buffer_size",
",",
"char_buffer_address",
")",
"response",
"=",
"ctypes",
".",
"windll",
".",
"user32",
".",
"SendMessageA",
"(",
"hwnd",
",",
"win32con_WM_COPYDATA",
",",
"ctypes",
".",
"sizeof",
"(",
"cds",
")",
",",
"ctypes",
".",
"byref",
"(",
"cds",
")",
")",
"if",
"response",
">",
"0",
":",
"pymap",
".",
"seek",
"(",
"0",
")",
"datalen",
"=",
"pymap",
".",
"read",
"(",
"4",
")",
"retlen",
"=",
"struct",
".",
"unpack",
"(",
"\">I\"",
",",
"datalen",
")",
"[",
"0",
"]",
"return",
"datalen",
"+",
"pymap",
".",
"read",
"(",
"retlen",
")",
"return",
"None"
] | Communication with the Pageant process is done through a shared
memory-mapped file. | [
"Communication",
"with",
"the",
"Pageant",
"process",
"is",
"done",
"through",
"a",
"shared",
"memory",
"-",
"mapped",
"file",
"."
] | cf7d49d66f3b1fbc8b0853518a54050182b3b5eb | https://github.com/paramiko/paramiko/blob/cf7d49d66f3b1fbc8b0853518a54050182b3b5eb/paramiko/win_pageant.py#L79-L114 | train |
paramiko/paramiko | paramiko/message.py | Message.get_remainder | 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 | python | 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 | [
"def",
"get_remainder",
"(",
"self",
")",
":",
"position",
"=",
"self",
".",
"packet",
".",
"tell",
"(",
")",
"remainder",
"=",
"self",
".",
"packet",
".",
"read",
"(",
")",
"self",
".",
"packet",
".",
"seek",
"(",
"position",
")",
"return",
"remainder"
] | Return the bytes (as a `str`) of this message that haven't already been
parsed and returned. | [
"Return",
"the",
"bytes",
"(",
"as",
"a",
"str",
")",
"of",
"this",
"message",
"that",
"haven",
"t",
"already",
"been",
"parsed",
"and",
"returned",
"."
] | cf7d49d66f3b1fbc8b0853518a54050182b3b5eb | https://github.com/paramiko/paramiko/blob/cf7d49d66f3b1fbc8b0853518a54050182b3b5eb/paramiko/message.py#L81-L89 | train |
paramiko/paramiko | paramiko/message.py | Message.get_so_far | 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.rewind()
return self.packet.read(position) | python | 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.rewind()
return self.packet.read(position) | [
"def",
"get_so_far",
"(",
"self",
")",
":",
"position",
"=",
"self",
".",
"packet",
".",
"tell",
"(",
")",
"self",
".",
"rewind",
"(",
")",
"return",
"self",
".",
"packet",
".",
"read",
"(",
"position",
")"
] | 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`. | [
"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",
"."
] | cf7d49d66f3b1fbc8b0853518a54050182b3b5eb | https://github.com/paramiko/paramiko/blob/cf7d49d66f3b1fbc8b0853518a54050182b3b5eb/paramiko/message.py#L91-L99 | train |
paramiko/paramiko | paramiko/message.py | Message.get_bytes | 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.
"""
b = self.packet.read(n)
max_pad_size = 1 << 20 # Limit padding to 1 MB
if len(b) < n < max_pad_size:
return b + zero_byte * (n - len(b))
return b | python | 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.
"""
b = self.packet.read(n)
max_pad_size = 1 << 20 # Limit padding to 1 MB
if len(b) < n < max_pad_size:
return b + zero_byte * (n - len(b))
return b | [
"def",
"get_bytes",
"(",
"self",
",",
"n",
")",
":",
"b",
"=",
"self",
".",
"packet",
".",
"read",
"(",
"n",
")",
"max_pad_size",
"=",
"1",
"<<",
"20",
"# Limit padding to 1 MB",
"if",
"len",
"(",
"b",
")",
"<",
"n",
"<",
"max_pad_size",
":",
"return",
"b",
"+",
"zero_byte",
"*",
"(",
"n",
"-",
"len",
"(",
"b",
")",
")",
"return",
"b"
] | 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. | [
"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",
"."
] | cf7d49d66f3b1fbc8b0853518a54050182b3b5eb | https://github.com/paramiko/paramiko/blob/cf7d49d66f3b1fbc8b0853518a54050182b3b5eb/paramiko/message.py#L101-L112 | train |
paramiko/paramiko | paramiko/message.py | Message.add_boolean | 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 | python | 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 | [
"def",
"add_boolean",
"(",
"self",
",",
"b",
")",
":",
"if",
"b",
":",
"self",
".",
"packet",
".",
"write",
"(",
"one_byte",
")",
"else",
":",
"self",
".",
"packet",
".",
"write",
"(",
"zero_byte",
")",
"return",
"self"
] | Add a boolean value to the stream.
:param bool b: boolean value to add | [
"Add",
"a",
"boolean",
"value",
"to",
"the",
"stream",
"."
] | cf7d49d66f3b1fbc8b0853518a54050182b3b5eb | https://github.com/paramiko/paramiko/blob/cf7d49d66f3b1fbc8b0853518a54050182b3b5eb/paramiko/message.py#L214-L224 | train |
paramiko/paramiko | paramiko/message.py | Message.add_adaptive_int | 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))
return self | python | 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))
return self | [
"def",
"add_adaptive_int",
"(",
"self",
",",
"n",
")",
":",
"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",
")",
")",
"return",
"self"
] | Add an integer to the stream.
:param int n: integer to add | [
"Add",
"an",
"integer",
"to",
"the",
"stream",
"."
] | cf7d49d66f3b1fbc8b0853518a54050182b3b5eb | https://github.com/paramiko/paramiko/blob/cf7d49d66f3b1fbc8b0853518a54050182b3b5eb/paramiko/message.py#L235-L246 | train |
paramiko/paramiko | paramiko/message.py | Message.add_int64 | 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 | python | 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 | [
"def",
"add_int64",
"(",
"self",
",",
"n",
")",
":",
"self",
".",
"packet",
".",
"write",
"(",
"struct",
".",
"pack",
"(",
"\">Q\"",
",",
"n",
")",
")",
"return",
"self"
] | Add a 64-bit int to the stream.
:param long n: long int to add | [
"Add",
"a",
"64",
"-",
"bit",
"int",
"to",
"the",
"stream",
"."
] | cf7d49d66f3b1fbc8b0853518a54050182b3b5eb | https://github.com/paramiko/paramiko/blob/cf7d49d66f3b1fbc8b0853518a54050182b3b5eb/paramiko/message.py#L248-L255 | train |
paramiko/paramiko | paramiko/primes.py | _roll_random | 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 worst case (N-1 is a
# power of 2), we have slightly better than 50% odds of getting one that
# fits, so i can't guarantee that this loop will ever finish, but the odds
# of it looping forever should be infinitesimal.
while True:
x = os.urandom(byte_count)
if hbyte_mask > 0:
x = byte_mask(x[0], hbyte_mask) + x[1:]
num = util.inflate_long(x, 1)
if num < n:
break
return num | python | 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 worst case (N-1 is a
# power of 2), we have slightly better than 50% odds of getting one that
# fits, so i can't guarantee that this loop will ever finish, but the odds
# of it looping forever should be infinitesimal.
while True:
x = os.urandom(byte_count)
if hbyte_mask > 0:
x = byte_mask(x[0], hbyte_mask) + x[1:]
num = util.inflate_long(x, 1)
if num < n:
break
return num | [
"def",
"_roll_random",
"(",
"n",
")",
":",
"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 worst case (N-1 is a",
"# power of 2), we have slightly better than 50% odds of getting one that",
"# fits, so i can't guarantee that this loop will ever finish, but the odds",
"# of it looping forever should be infinitesimal.",
"while",
"True",
":",
"x",
"=",
"os",
".",
"urandom",
"(",
"byte_count",
")",
"if",
"hbyte_mask",
">",
"0",
":",
"x",
"=",
"byte_mask",
"(",
"x",
"[",
"0",
"]",
",",
"hbyte_mask",
")",
"+",
"x",
"[",
"1",
":",
"]",
"num",
"=",
"util",
".",
"inflate_long",
"(",
"x",
",",
"1",
")",
"if",
"num",
"<",
"n",
":",
"break",
"return",
"num"
] | returns a random # from 0 to N-1 | [
"returns",
"a",
"random",
"#",
"from",
"0",
"to",
"N",
"-",
"1"
] | cf7d49d66f3b1fbc8b0853518a54050182b3b5eb | https://github.com/paramiko/paramiko/blob/cf7d49d66f3b1fbc8b0853518a54050182b3b5eb/paramiko/primes.py#L30-L49 | train |
paramiko/paramiko | paramiko/primes.py | ModulusPack.read_file | 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] == "#"):
continue
try:
self._parse_modulus(line)
except:
continue | python | 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] == "#"):
continue
try:
self._parse_modulus(line)
except:
continue | [
"def",
"read_file",
"(",
"self",
",",
"filename",
")",
":",
"self",
".",
"pack",
"=",
"{",
"}",
"with",
"open",
"(",
"filename",
",",
"\"r\"",
")",
"as",
"f",
":",
"for",
"line",
"in",
"f",
":",
"line",
"=",
"line",
".",
"strip",
"(",
")",
"if",
"(",
"len",
"(",
"line",
")",
"==",
"0",
")",
"or",
"(",
"line",
"[",
"0",
"]",
"==",
"\"#\"",
")",
":",
"continue",
"try",
":",
"self",
".",
"_parse_modulus",
"(",
"line",
")",
"except",
":",
"continue"
] | :raises IOError: passed from any file operations that fail. | [
":",
"raises",
"IOError",
":",
"passed",
"from",
"any",
"file",
"operations",
"that",
"fail",
"."
] | cf7d49d66f3b1fbc8b0853518a54050182b3b5eb | https://github.com/paramiko/paramiko/blob/cf7d49d66f3b1fbc8b0853518a54050182b3b5eb/paramiko/primes.py#L109-L122 | train |
paramiko/paramiko | paramiko/ecdsakey.py | ECDSAKey.generate | 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 (`.ECDSAKey`) object
"""
if bits is not None:
curve = cls._ECDSA_CURVES.get_by_key_length(bits)
if curve is None:
raise ValueError("Unsupported key length: {:d}".format(bits))
curve = curve.curve_class()
private_key = ec.generate_private_key(curve, backend=default_backend())
return ECDSAKey(vals=(private_key, private_key.public_key())) | python | 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 (`.ECDSAKey`) object
"""
if bits is not None:
curve = cls._ECDSA_CURVES.get_by_key_length(bits)
if curve is None:
raise ValueError("Unsupported key length: {:d}".format(bits))
curve = curve.curve_class()
private_key = ec.generate_private_key(curve, backend=default_backend())
return ECDSAKey(vals=(private_key, private_key.public_key())) | [
"def",
"generate",
"(",
"cls",
",",
"curve",
"=",
"ec",
".",
"SECP256R1",
"(",
")",
",",
"progress_func",
"=",
"None",
",",
"bits",
"=",
"None",
")",
":",
"if",
"bits",
"is",
"not",
"None",
":",
"curve",
"=",
"cls",
".",
"_ECDSA_CURVES",
".",
"get_by_key_length",
"(",
"bits",
")",
"if",
"curve",
"is",
"None",
":",
"raise",
"ValueError",
"(",
"\"Unsupported key length: {:d}\"",
".",
"format",
"(",
"bits",
")",
")",
"curve",
"=",
"curve",
".",
"curve_class",
"(",
")",
"private_key",
"=",
"ec",
".",
"generate_private_key",
"(",
"curve",
",",
"backend",
"=",
"default_backend",
"(",
")",
")",
"return",
"ECDSAKey",
"(",
"vals",
"=",
"(",
"private_key",
",",
"private_key",
".",
"public_key",
"(",
")",
")",
")"
] | 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 (`.ECDSAKey`) object | [
"Generate",
"a",
"new",
"private",
"ECDSA",
"key",
".",
"This",
"factory",
"function",
"can",
"be",
"used",
"to",
"generate",
"a",
"new",
"host",
"key",
"or",
"authentication",
"key",
"."
] | cf7d49d66f3b1fbc8b0853518a54050182b3b5eb | https://github.com/paramiko/paramiko/blob/cf7d49d66f3b1fbc8b0853518a54050182b3b5eb/paramiko/ecdsakey.py#L258-L273 | train |
paramiko/paramiko | paramiko/pkey.py | PKey.from_private_key_file | 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). Through the magic of Python, this factory method will
exist in all subclasses of PKey (such as `.RSAKey` or `.DSSKey`), but
is useless on the abstract PKey class.
:param str filename: name of the file to read
:param str password:
an optional password to use to decrypt the key file, if it's
encrypted
:return: a new `.PKey` based on the given private key
:raises: ``IOError`` -- if there was an error reading the file
:raises: `.PasswordRequiredException` -- if the private key file is
encrypted, and ``password`` is ``None``
:raises: `.SSHException` -- if the key file is invalid
"""
key = cls(filename=filename, password=password)
return key | python | 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). Through the magic of Python, this factory method will
exist in all subclasses of PKey (such as `.RSAKey` or `.DSSKey`), but
is useless on the abstract PKey class.
:param str filename: name of the file to read
:param str password:
an optional password to use to decrypt the key file, if it's
encrypted
:return: a new `.PKey` based on the given private key
:raises: ``IOError`` -- if there was an error reading the file
:raises: `.PasswordRequiredException` -- if the private key file is
encrypted, and ``password`` is ``None``
:raises: `.SSHException` -- if the key file is invalid
"""
key = cls(filename=filename, password=password)
return key | [
"def",
"from_private_key_file",
"(",
"cls",
",",
"filename",
",",
"password",
"=",
"None",
")",
":",
"key",
"=",
"cls",
"(",
"filename",
"=",
"filename",
",",
"password",
"=",
"password",
")",
"return",
"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 `.DSSKey`), but
is useless on the abstract PKey class.
:param str filename: name of the file to read
:param str password:
an optional password to use to decrypt the key file, if it's
encrypted
:return: a new `.PKey` based on the given private key
:raises: ``IOError`` -- if there was an error reading the file
:raises: `.PasswordRequiredException` -- if the private key file is
encrypted, and ``password`` is ``None``
:raises: `.SSHException` -- if the key file is invalid | [
"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",
".",
"DSSKey",
")",
"but",
"is",
"useless",
"on",
"the",
"abstract",
"PKey",
"class",
"."
] | cf7d49d66f3b1fbc8b0853518a54050182b3b5eb | https://github.com/paramiko/paramiko/blob/cf7d49d66f3b1fbc8b0853518a54050182b3b5eb/paramiko/pkey.py#L186-L207 | train |
paramiko/paramiko | paramiko/pkey.py | PKey.from_private_key | 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
`.PasswordRequiredException` is thrown).
:param file_obj: the file-like object to read from
:param str password:
an optional password to use to decrypt the key, if it's encrypted
:return: a new `.PKey` based on the given private key
:raises: ``IOError`` -- if there was an error reading the key
:raises: `.PasswordRequiredException` --
if the private key file is encrypted, and ``password`` is ``None``
:raises: `.SSHException` -- if the key file is invalid
"""
key = cls(file_obj=file_obj, password=password)
return key | python | 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
`.PasswordRequiredException` is thrown).
:param file_obj: the file-like object to read from
:param str password:
an optional password to use to decrypt the key, if it's encrypted
:return: a new `.PKey` based on the given private key
:raises: ``IOError`` -- if there was an error reading the key
:raises: `.PasswordRequiredException` --
if the private key file is encrypted, and ``password`` is ``None``
:raises: `.SSHException` -- if the key file is invalid
"""
key = cls(file_obj=file_obj, password=password)
return key | [
"def",
"from_private_key",
"(",
"cls",
",",
"file_obj",
",",
"password",
"=",
"None",
")",
":",
"key",
"=",
"cls",
"(",
"file_obj",
"=",
"file_obj",
",",
"password",
"=",
"password",
")",
"return",
"key"
] | 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).
:param file_obj: the file-like object to read from
:param str password:
an optional password to use to decrypt the key, if it's encrypted
:return: a new `.PKey` based on the given private key
:raises: ``IOError`` -- if there was an error reading the key
:raises: `.PasswordRequiredException` --
if the private key file is encrypted, and ``password`` is ``None``
:raises: `.SSHException` -- if the key file is invalid | [
"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",
")",
"."
] | cf7d49d66f3b1fbc8b0853518a54050182b3b5eb | https://github.com/paramiko/paramiko/blob/cf7d49d66f3b1fbc8b0853518a54050182b3b5eb/paramiko/pkey.py#L210-L228 | train |
paramiko/paramiko | paramiko/pkey.py | PKey._write_private_key_file | 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
a password is given, DES-EDE3-CBC is used.
:param str tag:
``"RSA"`` or ``"DSA"``, the tag used to mark the data block.
:param filename: name of the file to write.
:param str data: data blob that makes up the private key.
:param str password: an optional password to use to encrypt the file.
:raises: ``IOError`` -- if there was an error writing the file.
"""
with open(filename, "w") as f:
os.chmod(filename, o600)
self._write_private_key(f, key, format, password=password) | python | 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
a password is given, DES-EDE3-CBC is used.
:param str tag:
``"RSA"`` or ``"DSA"``, the tag used to mark the data block.
:param filename: name of the file to write.
:param str data: data blob that makes up the private key.
:param str password: an optional password to use to encrypt the file.
:raises: ``IOError`` -- if there was an error writing the file.
"""
with open(filename, "w") as f:
os.chmod(filename, o600)
self._write_private_key(f, key, format, password=password) | [
"def",
"_write_private_key_file",
"(",
"self",
",",
"filename",
",",
"key",
",",
"format",
",",
"password",
"=",
"None",
")",
":",
"with",
"open",
"(",
"filename",
",",
"\"w\"",
")",
"as",
"f",
":",
"os",
".",
"chmod",
"(",
"filename",
",",
"o600",
")",
"self",
".",
"_write_private_key",
"(",
"f",
",",
"key",
",",
"format",
",",
"password",
"=",
"password",
")"
] | 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.
:param str tag:
``"RSA"`` or ``"DSA"``, the tag used to mark the data block.
:param filename: name of the file to write.
:param str data: data blob that makes up the private key.
:param str password: an optional password to use to encrypt the file.
:raises: ``IOError`` -- if there was an error writing the file. | [
"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",
"."
] | cf7d49d66f3b1fbc8b0853518a54050182b3b5eb | https://github.com/paramiko/paramiko/blob/cf7d49d66f3b1fbc8b0853518a54050182b3b5eb/paramiko/pkey.py#L340-L357 | train |
paramiko/paramiko | paramiko/pkey.py | PKey._check_type_and_load_cert | 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 treat the message as key material afterwards either way.
The obtained key type is returned for classes which need to know what
it was (e.g. ECDSA.)
"""
# Normalization; most classes have a single key type and give a string,
# but eg ECDSA is a 1:N mapping.
key_types = key_type
cert_types = cert_type
if isinstance(key_type, string_types):
key_types = [key_types]
if isinstance(cert_types, string_types):
cert_types = [cert_types]
# Can't do much with no message, that should've been handled elsewhere
if msg is None:
raise SSHException("Key object may not be empty")
# First field is always key type, in either kind of object. (make sure
# we rewind before grabbing it - sometimes caller had to do their own
# introspection first!)
msg.rewind()
type_ = msg.get_text()
# Regular public key - nothing special to do besides the implicit
# type check.
if type_ in key_types:
pass
# OpenSSH-compatible certificate - store full copy as .public_blob
# (so signing works correctly) and then fast-forward past the
# nonce.
elif type_ in cert_types:
# This seems the cleanest way to 'clone' an already-being-read
# message; they're *IO objects at heart and their .getvalue()
# always returns the full value regardless of pointer position.
self.load_certificate(Message(msg.asbytes()))
# Read out nonce as it comes before the public numbers.
# TODO: usefully interpret it & other non-public-number fields
# (requires going back into per-type subclasses.)
msg.get_string()
else:
err = "Invalid key (class: {}, data type: {}"
raise SSHException(err.format(self.__class__.__name__, type_)) | python | 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 treat the message as key material afterwards either way.
The obtained key type is returned for classes which need to know what
it was (e.g. ECDSA.)
"""
# Normalization; most classes have a single key type and give a string,
# but eg ECDSA is a 1:N mapping.
key_types = key_type
cert_types = cert_type
if isinstance(key_type, string_types):
key_types = [key_types]
if isinstance(cert_types, string_types):
cert_types = [cert_types]
# Can't do much with no message, that should've been handled elsewhere
if msg is None:
raise SSHException("Key object may not be empty")
# First field is always key type, in either kind of object. (make sure
# we rewind before grabbing it - sometimes caller had to do their own
# introspection first!)
msg.rewind()
type_ = msg.get_text()
# Regular public key - nothing special to do besides the implicit
# type check.
if type_ in key_types:
pass
# OpenSSH-compatible certificate - store full copy as .public_blob
# (so signing works correctly) and then fast-forward past the
# nonce.
elif type_ in cert_types:
# This seems the cleanest way to 'clone' an already-being-read
# message; they're *IO objects at heart and their .getvalue()
# always returns the full value regardless of pointer position.
self.load_certificate(Message(msg.asbytes()))
# Read out nonce as it comes before the public numbers.
# TODO: usefully interpret it & other non-public-number fields
# (requires going back into per-type subclasses.)
msg.get_string()
else:
err = "Invalid key (class: {}, data type: {}"
raise SSHException(err.format(self.__class__.__name__, type_)) | [
"def",
"_check_type_and_load_cert",
"(",
"self",
",",
"msg",
",",
"key_type",
",",
"cert_type",
")",
":",
"# Normalization; most classes have a single key type and give a string,",
"# but eg ECDSA is a 1:N mapping.",
"key_types",
"=",
"key_type",
"cert_types",
"=",
"cert_type",
"if",
"isinstance",
"(",
"key_type",
",",
"string_types",
")",
":",
"key_types",
"=",
"[",
"key_types",
"]",
"if",
"isinstance",
"(",
"cert_types",
",",
"string_types",
")",
":",
"cert_types",
"=",
"[",
"cert_types",
"]",
"# Can't do much with no message, that should've been handled elsewhere",
"if",
"msg",
"is",
"None",
":",
"raise",
"SSHException",
"(",
"\"Key object may not be empty\"",
")",
"# First field is always key type, in either kind of object. (make sure",
"# we rewind before grabbing it - sometimes caller had to do their own",
"# introspection first!)",
"msg",
".",
"rewind",
"(",
")",
"type_",
"=",
"msg",
".",
"get_text",
"(",
")",
"# Regular public key - nothing special to do besides the implicit",
"# type check.",
"if",
"type_",
"in",
"key_types",
":",
"pass",
"# OpenSSH-compatible certificate - store full copy as .public_blob",
"# (so signing works correctly) and then fast-forward past the",
"# nonce.",
"elif",
"type_",
"in",
"cert_types",
":",
"# This seems the cleanest way to 'clone' an already-being-read",
"# message; they're *IO objects at heart and their .getvalue()",
"# always returns the full value regardless of pointer position.",
"self",
".",
"load_certificate",
"(",
"Message",
"(",
"msg",
".",
"asbytes",
"(",
")",
")",
")",
"# Read out nonce as it comes before the public numbers.",
"# TODO: usefully interpret it & other non-public-number fields",
"# (requires going back into per-type subclasses.)",
"msg",
".",
"get_string",
"(",
")",
"else",
":",
"err",
"=",
"\"Invalid key (class: {}, data type: {}\"",
"raise",
"SSHException",
"(",
"err",
".",
"format",
"(",
"self",
".",
"__class__",
".",
"__name__",
",",
"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 treat the message as key material afterwards either way.
The obtained key type is returned for classes which need to know what
it was (e.g. ECDSA.) | [
"Perform",
"message",
"type",
"-",
"checking",
"&",
"optional",
"certificate",
"loading",
"."
] | cf7d49d66f3b1fbc8b0853518a54050182b3b5eb | https://github.com/paramiko/paramiko/blob/cf7d49d66f3b1fbc8b0853518a54050182b3b5eb/paramiko/pkey.py#L371-L416 | train |
paramiko/paramiko | paramiko/pkey.py | PKey.load_certificate | 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 key
file includes sufficient information to derive the public
key info. For certificates, however, this can be used on
the client side to offer authentication requests to the server
based on certificate instead of raw public key.
See:
https://github.com/openssh/openssh-portable/blob/master/PROTOCOL.certkeys
Note: very little effort is made to validate the certificate contents,
that is for the server to decide if it is good enough to authenticate
successfully.
"""
if isinstance(value, Message):
constructor = "from_message"
elif os.path.isfile(value):
constructor = "from_file"
else:
constructor = "from_string"
blob = getattr(PublicBlob, constructor)(value)
if not blob.key_type.startswith(self.get_name()):
err = "PublicBlob type {} incompatible with key type {}"
raise ValueError(err.format(blob.key_type, self.get_name()))
self.public_blob = blob | python | 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 key
file includes sufficient information to derive the public
key info. For certificates, however, this can be used on
the client side to offer authentication requests to the server
based on certificate instead of raw public key.
See:
https://github.com/openssh/openssh-portable/blob/master/PROTOCOL.certkeys
Note: very little effort is made to validate the certificate contents,
that is for the server to decide if it is good enough to authenticate
successfully.
"""
if isinstance(value, Message):
constructor = "from_message"
elif os.path.isfile(value):
constructor = "from_file"
else:
constructor = "from_string"
blob = getattr(PublicBlob, constructor)(value)
if not blob.key_type.startswith(self.get_name()):
err = "PublicBlob type {} incompatible with key type {}"
raise ValueError(err.format(blob.key_type, self.get_name()))
self.public_blob = blob | [
"def",
"load_certificate",
"(",
"self",
",",
"value",
")",
":",
"if",
"isinstance",
"(",
"value",
",",
"Message",
")",
":",
"constructor",
"=",
"\"from_message\"",
"elif",
"os",
".",
"path",
".",
"isfile",
"(",
"value",
")",
":",
"constructor",
"=",
"\"from_file\"",
"else",
":",
"constructor",
"=",
"\"from_string\"",
"blob",
"=",
"getattr",
"(",
"PublicBlob",
",",
"constructor",
")",
"(",
"value",
")",
"if",
"not",
"blob",
".",
"key_type",
".",
"startswith",
"(",
"self",
".",
"get_name",
"(",
")",
")",
":",
"err",
"=",
"\"PublicBlob type {} incompatible with key type {}\"",
"raise",
"ValueError",
"(",
"err",
".",
"format",
"(",
"blob",
".",
"key_type",
",",
"self",
".",
"get_name",
"(",
")",
")",
")",
"self",
".",
"public_blob",
"=",
"blob"
] | 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 key
file includes sufficient information to derive the public
key info. For certificates, however, this can be used on
the client side to offer authentication requests to the server
based on certificate instead of raw public key.
See:
https://github.com/openssh/openssh-portable/blob/master/PROTOCOL.certkeys
Note: very little effort is made to validate the certificate contents,
that is for the server to decide if it is good enough to authenticate
successfully. | [
"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",
"."
] | cf7d49d66f3b1fbc8b0853518a54050182b3b5eb | https://github.com/paramiko/paramiko/blob/cf7d49d66f3b1fbc8b0853518a54050182b3b5eb/paramiko/pkey.py#L418-L447 | train |
paramiko/paramiko | paramiko/pkey.py | PublicBlob.from_file | 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) | python | 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) | [
"def",
"from_file",
"(",
"cls",
",",
"filename",
")",
":",
"with",
"open",
"(",
"filename",
")",
"as",
"f",
":",
"string",
"=",
"f",
".",
"read",
"(",
")",
"return",
"cls",
".",
"from_string",
"(",
"string",
")"
] | Create a public blob from a ``-cert.pub``-style file on disk. | [
"Create",
"a",
"public",
"blob",
"from",
"a",
"-",
"cert",
".",
"pub",
"-",
"style",
"file",
"on",
"disk",
"."
] | cf7d49d66f3b1fbc8b0853518a54050182b3b5eb | https://github.com/paramiko/paramiko/blob/cf7d49d66f3b1fbc8b0853518a54050182b3b5eb/paramiko/pkey.py#L482-L488 | train |
paramiko/paramiko | paramiko/pkey.py | PublicBlob.from_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]
key_blob = decodebytes(b(fields[1]))
try:
comment = fields[2].strip()
except IndexError:
comment = None
# Verify that the blob message first (string) field matches the
# key_type
m = Message(key_blob)
blob_type = m.get_text()
if blob_type != key_type:
deets = "key type={!r}, but blob type={!r}".format(
key_type, blob_type
)
raise ValueError("Invalid PublicBlob contents: {}".format(deets))
# All good? All good.
return cls(type_=key_type, blob=key_blob, comment=comment) | python | 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]
key_blob = decodebytes(b(fields[1]))
try:
comment = fields[2].strip()
except IndexError:
comment = None
# Verify that the blob message first (string) field matches the
# key_type
m = Message(key_blob)
blob_type = m.get_text()
if blob_type != key_type:
deets = "key type={!r}, but blob type={!r}".format(
key_type, blob_type
)
raise ValueError("Invalid PublicBlob contents: {}".format(deets))
# All good? All good.
return cls(type_=key_type, blob=key_blob, comment=comment) | [
"def",
"from_string",
"(",
"cls",
",",
"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",
"]",
"key_blob",
"=",
"decodebytes",
"(",
"b",
"(",
"fields",
"[",
"1",
"]",
")",
")",
"try",
":",
"comment",
"=",
"fields",
"[",
"2",
"]",
".",
"strip",
"(",
")",
"except",
"IndexError",
":",
"comment",
"=",
"None",
"# Verify that the blob message first (string) field matches the",
"# key_type",
"m",
"=",
"Message",
"(",
"key_blob",
")",
"blob_type",
"=",
"m",
".",
"get_text",
"(",
")",
"if",
"blob_type",
"!=",
"key_type",
":",
"deets",
"=",
"\"key type={!r}, but blob type={!r}\"",
".",
"format",
"(",
"key_type",
",",
"blob_type",
")",
"raise",
"ValueError",
"(",
"\"Invalid PublicBlob contents: {}\"",
".",
"format",
"(",
"deets",
")",
")",
"# All good? All good.",
"return",
"cls",
"(",
"type_",
"=",
"key_type",
",",
"blob",
"=",
"key_blob",
",",
"comment",
"=",
"comment",
")"
] | Create a public blob from a ``-cert.pub``-style string. | [
"Create",
"a",
"public",
"blob",
"from",
"a",
"-",
"cert",
".",
"pub",
"-",
"style",
"string",
"."
] | cf7d49d66f3b1fbc8b0853518a54050182b3b5eb | https://github.com/paramiko/paramiko/blob/cf7d49d66f3b1fbc8b0853518a54050182b3b5eb/paramiko/pkey.py#L491-L515 | train |
paramiko/paramiko | paramiko/pkey.py | PublicBlob.from_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 cls(type_=type_, blob=message.asbytes()) | python | 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 cls(type_=type_, blob=message.asbytes()) | [
"def",
"from_message",
"(",
"cls",
",",
"message",
")",
":",
"type_",
"=",
"message",
".",
"get_text",
"(",
")",
"return",
"cls",
"(",
"type_",
"=",
"type_",
",",
"blob",
"=",
"message",
".",
"asbytes",
"(",
")",
")"
] | 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." | [
"Create",
"a",
"public",
"blob",
"from",
"a",
"network",
".",
"Message",
"."
] | cf7d49d66f3b1fbc8b0853518a54050182b3b5eb | https://github.com/paramiko/paramiko/blob/cf7d49d66f3b1fbc8b0853518a54050182b3b5eb/paramiko/pkey.py#L518-L526 | train |
paramiko/paramiko | paramiko/pipe.py | make_or_pipe | 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
p2._partner = p1
return p1, p2 | python | 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
p2._partner = p1
return p1, p2 | [
"def",
"make_or_pipe",
"(",
"pipe",
")",
":",
"p1",
"=",
"OrPipe",
"(",
"pipe",
")",
"p2",
"=",
"OrPipe",
"(",
"pipe",
")",
"p1",
".",
"_partner",
"=",
"p2",
"p2",
".",
"_partner",
"=",
"p1",
"return",
"p1",
",",
"p2"
] | 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. | [
"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",
"."
] | cf7d49d66f3b1fbc8b0853518a54050182b3b5eb | https://github.com/paramiko/paramiko/blob/cf7d49d66f3b1fbc8b0853518a54050182b3b5eb/paramiko/pipe.py#L138-L148 | train |
paramiko/paramiko | paramiko/agent.py | AgentLocalProxy.get_connection | 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()
return r, addr
except:
raise | python | 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()
return r, addr
except:
raise | [
"def",
"get_connection",
"(",
"self",
")",
":",
"conn",
"=",
"socket",
".",
"socket",
"(",
"socket",
".",
"AF_UNIX",
",",
"socket",
".",
"SOCK_STREAM",
")",
"try",
":",
"conn",
".",
"bind",
"(",
"self",
".",
"_agent",
".",
"_get_filename",
"(",
")",
")",
"conn",
".",
"listen",
"(",
"1",
")",
"(",
"r",
",",
"addr",
")",
"=",
"conn",
".",
"accept",
"(",
")",
"return",
"r",
",",
"addr",
"except",
":",
"raise"
] | Return a pair of socket object and string address.
May block! | [
"Return",
"a",
"pair",
"of",
"socket",
"object",
"and",
"string",
"address",
"."
] | cf7d49d66f3b1fbc8b0853518a54050182b3b5eb | https://github.com/paramiko/paramiko/blob/cf7d49d66f3b1fbc8b0853518a54050182b3b5eb/paramiko/agent.py#L167-L180 | train |
paramiko/paramiko | paramiko/agent.py | AgentClientProxy.close | 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() | python | 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() | [
"def",
"close",
"(",
"self",
")",
":",
"if",
"hasattr",
"(",
"self",
",",
"\"thread\"",
")",
":",
"self",
".",
"thread",
".",
"_exit",
"=",
"True",
"self",
".",
"thread",
".",
"join",
"(",
"1000",
")",
"if",
"self",
".",
"_conn",
"is",
"not",
"None",
":",
"self",
".",
"_conn",
".",
"close",
"(",
")"
] | Close the current connection and terminate the agent
Should be called manually | [
"Close",
"the",
"current",
"connection",
"and",
"terminate",
"the",
"agent",
"Should",
"be",
"called",
"manually"
] | cf7d49d66f3b1fbc8b0853518a54050182b3b5eb | https://github.com/paramiko/paramiko/blob/cf7d49d66f3b1fbc8b0853518a54050182b3b5eb/paramiko/agent.py#L243-L252 | train |
paramiko/paramiko | paramiko/agent.py | AgentServerProxy.close | 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() | python | 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() | [
"def",
"close",
"(",
"self",
")",
":",
"os",
".",
"remove",
"(",
"self",
".",
"_file",
")",
"os",
".",
"rmdir",
"(",
"self",
".",
"_dir",
")",
"self",
".",
"thread",
".",
"_exit",
"=",
"True",
"self",
".",
"thread",
".",
"join",
"(",
"1000",
")",
"self",
".",
"_close",
"(",
")"
] | Terminate the agent, clean the files, close connections
Should be called manually | [
"Terminate",
"the",
"agent",
"clean",
"the",
"files",
"close",
"connections",
"Should",
"be",
"called",
"manually"
] | cf7d49d66f3b1fbc8b0853518a54050182b3b5eb | https://github.com/paramiko/paramiko/blob/cf7d49d66f3b1fbc8b0853518a54050182b3b5eb/paramiko/agent.py#L281-L290 | train |
paramiko/paramiko | paramiko/packet.py | Packetizer.set_outbound_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.__block_size_out = block_size
self.__mac_engine_out = mac_engine
self.__mac_size_out = mac_size
self.__mac_key_out = mac_key
self.__sent_bytes = 0
self.__sent_packets = 0
# wait until the reset happens in both directions before clearing
# rekey flag
self.__init_count |= 1
if self.__init_count == 3:
self.__init_count = 0
self.__need_rekey = False | python | 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.__block_size_out = block_size
self.__mac_engine_out = mac_engine
self.__mac_size_out = mac_size
self.__mac_key_out = mac_key
self.__sent_bytes = 0
self.__sent_packets = 0
# wait until the reset happens in both directions before clearing
# rekey flag
self.__init_count |= 1
if self.__init_count == 3:
self.__init_count = 0
self.__need_rekey = False | [
"def",
"set_outbound_cipher",
"(",
"self",
",",
"block_engine",
",",
"block_size",
",",
"mac_engine",
",",
"mac_size",
",",
"mac_key",
",",
"sdctr",
"=",
"False",
",",
")",
":",
"self",
".",
"__block_engine_out",
"=",
"block_engine",
"self",
".",
"__sdctr_out",
"=",
"sdctr",
"self",
".",
"__block_size_out",
"=",
"block_size",
"self",
".",
"__mac_engine_out",
"=",
"mac_engine",
"self",
".",
"__mac_size_out",
"=",
"mac_size",
"self",
".",
"__mac_key_out",
"=",
"mac_key",
"self",
".",
"__sent_bytes",
"=",
"0",
"self",
".",
"__sent_packets",
"=",
"0",
"# wait until the reset happens in both directions before clearing",
"# rekey flag",
"self",
".",
"__init_count",
"|=",
"1",
"if",
"self",
".",
"__init_count",
"==",
"3",
":",
"self",
".",
"__init_count",
"=",
"0",
"self",
".",
"__need_rekey",
"=",
"False"
] | Switch outbound data cipher. | [
"Switch",
"outbound",
"data",
"cipher",
"."
] | cf7d49d66f3b1fbc8b0853518a54050182b3b5eb | https://github.com/paramiko/paramiko/blob/cf7d49d66f3b1fbc8b0853518a54050182b3b5eb/paramiko/packet.py#L137-L162 | train |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.