id int32 0 252k | repo stringlengths 7 55 | path stringlengths 4 127 | func_name stringlengths 1 88 | original_string stringlengths 75 19.8k | language stringclasses 1 value | code stringlengths 75 19.8k | code_tokens list | docstring stringlengths 3 17.3k | docstring_tokens list | sha stringlengths 40 40 | url stringlengths 87 242 |
|---|---|---|---|---|---|---|---|---|---|---|---|
32,300 | elastic/elasticsearch-dsl-py | examples/parent_child.py | Question.get_answers | def get_answers(self):
"""
Get answers either from inner_hits already present or by searching
elasticsearch.
"""
if 'inner_hits' in self.meta and 'answer' in self.meta.inner_hits:
return self.meta.inner_hits.answer.hits
return list(self.search_answers()) | python | def get_answers(self):
"""
Get answers either from inner_hits already present or by searching
elasticsearch.
"""
if 'inner_hits' in self.meta and 'answer' in self.meta.inner_hits:
return self.meta.inner_hits.answer.hits
return list(self.search_answers()) | [
"def",
"get_answers",
"(",
"self",
")",
":",
"if",
"'inner_hits'",
"in",
"self",
".",
"meta",
"and",
"'answer'",
"in",
"self",
".",
"meta",
".",
"inner_hits",
":",
"return",
"self",
".",
"meta",
".",
"inner_hits",
".",
"answer",
".",
"hits",
"return",
... | Get answers either from inner_hits already present or by searching
elasticsearch. | [
"Get",
"answers",
"either",
"from",
"inner_hits",
"already",
"present",
"or",
"by",
"searching",
"elasticsearch",
"."
] | 874b52472fc47b601de0e5fa0e4300e21aff0085 | https://github.com/elastic/elasticsearch-dsl-py/blob/874b52472fc47b601de0e5fa0e4300e21aff0085/examples/parent_child.py#L130-L137 |
32,301 | elastic/elasticsearch-dsl-py | elasticsearch_dsl/faceted_search.py | Facet.get_aggregation | def get_aggregation(self):
"""
Return the aggregation object.
"""
agg = A(self.agg_type, **self._params)
if self._metric:
agg.metric('metric', self._metric)
return agg | python | def get_aggregation(self):
"""
Return the aggregation object.
"""
agg = A(self.agg_type, **self._params)
if self._metric:
agg.metric('metric', self._metric)
return agg | [
"def",
"get_aggregation",
"(",
"self",
")",
":",
"agg",
"=",
"A",
"(",
"self",
".",
"agg_type",
",",
"*",
"*",
"self",
".",
"_params",
")",
"if",
"self",
".",
"_metric",
":",
"agg",
".",
"metric",
"(",
"'metric'",
",",
"self",
".",
"_metric",
")",
... | Return the aggregation object. | [
"Return",
"the",
"aggregation",
"object",
"."
] | 874b52472fc47b601de0e5fa0e4300e21aff0085 | https://github.com/elastic/elasticsearch-dsl-py/blob/874b52472fc47b601de0e5fa0e4300e21aff0085/elasticsearch_dsl/faceted_search.py#L30-L37 |
32,302 | elastic/elasticsearch-dsl-py | elasticsearch_dsl/faceted_search.py | Facet.add_filter | def add_filter(self, filter_values):
"""
Construct a filter.
"""
if not filter_values:
return
f = self.get_value_filter(filter_values[0])
for v in filter_values[1:]:
f |= self.get_value_filter(v)
return f | python | def add_filter(self, filter_values):
"""
Construct a filter.
"""
if not filter_values:
return
f = self.get_value_filter(filter_values[0])
for v in filter_values[1:]:
f |= self.get_value_filter(v)
return f | [
"def",
"add_filter",
"(",
"self",
",",
"filter_values",
")",
":",
"if",
"not",
"filter_values",
":",
"return",
"f",
"=",
"self",
".",
"get_value_filter",
"(",
"filter_values",
"[",
"0",
"]",
")",
"for",
"v",
"in",
"filter_values",
"[",
"1",
":",
"]",
"... | Construct a filter. | [
"Construct",
"a",
"filter",
"."
] | 874b52472fc47b601de0e5fa0e4300e21aff0085 | https://github.com/elastic/elasticsearch-dsl-py/blob/874b52472fc47b601de0e5fa0e4300e21aff0085/elasticsearch_dsl/faceted_search.py#L39-L49 |
32,303 | elastic/elasticsearch-dsl-py | elasticsearch_dsl/faceted_search.py | Facet.get_values | def get_values(self, data, filter_values):
"""
Turn the raw bucket data into a list of tuples containing the key,
number of documents and a flag indicating whether this value has been
selected or not.
"""
out = []
for bucket in data.buckets:
key = self.get_value(bucket)
out.append((
key,
self.get_metric(bucket),
self.is_filtered(key, filter_values)
))
return out | python | def get_values(self, data, filter_values):
"""
Turn the raw bucket data into a list of tuples containing the key,
number of documents and a flag indicating whether this value has been
selected or not.
"""
out = []
for bucket in data.buckets:
key = self.get_value(bucket)
out.append((
key,
self.get_metric(bucket),
self.is_filtered(key, filter_values)
))
return out | [
"def",
"get_values",
"(",
"self",
",",
"data",
",",
"filter_values",
")",
":",
"out",
"=",
"[",
"]",
"for",
"bucket",
"in",
"data",
".",
"buckets",
":",
"key",
"=",
"self",
".",
"get_value",
"(",
"bucket",
")",
"out",
".",
"append",
"(",
"(",
"key"... | Turn the raw bucket data into a list of tuples containing the key,
number of documents and a flag indicating whether this value has been
selected or not. | [
"Turn",
"the",
"raw",
"bucket",
"data",
"into",
"a",
"list",
"of",
"tuples",
"containing",
"the",
"key",
"number",
"of",
"documents",
"and",
"a",
"flag",
"indicating",
"whether",
"this",
"value",
"has",
"been",
"selected",
"or",
"not",
"."
] | 874b52472fc47b601de0e5fa0e4300e21aff0085 | https://github.com/elastic/elasticsearch-dsl-py/blob/874b52472fc47b601de0e5fa0e4300e21aff0085/elasticsearch_dsl/faceted_search.py#L77-L91 |
32,304 | elastic/elasticsearch-dsl-py | elasticsearch_dsl/faceted_search.py | FacetedSearch.add_filter | def add_filter(self, name, filter_values):
"""
Add a filter for a facet.
"""
# normalize the value into a list
if not isinstance(filter_values, (tuple, list)):
if filter_values is None:
return
filter_values = [filter_values, ]
# remember the filter values for use in FacetedResponse
self.filter_values[name] = filter_values
# get the filter from the facet
f = self.facets[name].add_filter(filter_values)
if f is None:
return
self._filters[name] = f | python | def add_filter(self, name, filter_values):
"""
Add a filter for a facet.
"""
# normalize the value into a list
if not isinstance(filter_values, (tuple, list)):
if filter_values is None:
return
filter_values = [filter_values, ]
# remember the filter values for use in FacetedResponse
self.filter_values[name] = filter_values
# get the filter from the facet
f = self.facets[name].add_filter(filter_values)
if f is None:
return
self._filters[name] = f | [
"def",
"add_filter",
"(",
"self",
",",
"name",
",",
"filter_values",
")",
":",
"# normalize the value into a list",
"if",
"not",
"isinstance",
"(",
"filter_values",
",",
"(",
"tuple",
",",
"list",
")",
")",
":",
"if",
"filter_values",
"is",
"None",
":",
"ret... | Add a filter for a facet. | [
"Add",
"a",
"filter",
"for",
"a",
"facet",
"."
] | 874b52472fc47b601de0e5fa0e4300e21aff0085 | https://github.com/elastic/elasticsearch-dsl-py/blob/874b52472fc47b601de0e5fa0e4300e21aff0085/elasticsearch_dsl/faceted_search.py#L283-L301 |
32,305 | elastic/elasticsearch-dsl-py | elasticsearch_dsl/faceted_search.py | FacetedSearch.search | def search(self):
"""
Returns the base Search object to which the facets are added.
You can customize the query by overriding this method and returning a
modified search object.
"""
s = Search(doc_type=self.doc_types, index=self.index, using=self.using)
return s.response_class(FacetedResponse) | python | def search(self):
"""
Returns the base Search object to which the facets are added.
You can customize the query by overriding this method and returning a
modified search object.
"""
s = Search(doc_type=self.doc_types, index=self.index, using=self.using)
return s.response_class(FacetedResponse) | [
"def",
"search",
"(",
"self",
")",
":",
"s",
"=",
"Search",
"(",
"doc_type",
"=",
"self",
".",
"doc_types",
",",
"index",
"=",
"self",
".",
"index",
",",
"using",
"=",
"self",
".",
"using",
")",
"return",
"s",
".",
"response_class",
"(",
"FacetedResp... | Returns the base Search object to which the facets are added.
You can customize the query by overriding this method and returning a
modified search object. | [
"Returns",
"the",
"base",
"Search",
"object",
"to",
"which",
"the",
"facets",
"are",
"added",
"."
] | 874b52472fc47b601de0e5fa0e4300e21aff0085 | https://github.com/elastic/elasticsearch-dsl-py/blob/874b52472fc47b601de0e5fa0e4300e21aff0085/elasticsearch_dsl/faceted_search.py#L303-L311 |
32,306 | elastic/elasticsearch-dsl-py | elasticsearch_dsl/faceted_search.py | FacetedSearch.query | def query(self, search, query):
"""
Add query part to ``search``.
Override this if you wish to customize the query used.
"""
if query:
if self.fields:
return search.query('multi_match', fields=self.fields, query=query)
else:
return search.query('multi_match', query=query)
return search | python | def query(self, search, query):
"""
Add query part to ``search``.
Override this if you wish to customize the query used.
"""
if query:
if self.fields:
return search.query('multi_match', fields=self.fields, query=query)
else:
return search.query('multi_match', query=query)
return search | [
"def",
"query",
"(",
"self",
",",
"search",
",",
"query",
")",
":",
"if",
"query",
":",
"if",
"self",
".",
"fields",
":",
"return",
"search",
".",
"query",
"(",
"'multi_match'",
",",
"fields",
"=",
"self",
".",
"fields",
",",
"query",
"=",
"query",
... | Add query part to ``search``.
Override this if you wish to customize the query used. | [
"Add",
"query",
"part",
"to",
"search",
"."
] | 874b52472fc47b601de0e5fa0e4300e21aff0085 | https://github.com/elastic/elasticsearch-dsl-py/blob/874b52472fc47b601de0e5fa0e4300e21aff0085/elasticsearch_dsl/faceted_search.py#L313-L324 |
32,307 | elastic/elasticsearch-dsl-py | elasticsearch_dsl/faceted_search.py | FacetedSearch.aggregate | def aggregate(self, search):
"""
Add aggregations representing the facets selected, including potential
filters.
"""
for f, facet in iteritems(self.facets):
agg = facet.get_aggregation()
agg_filter = MatchAll()
for field, filter in iteritems(self._filters):
if f == field:
continue
agg_filter &= filter
search.aggs.bucket(
'_filter_' + f,
'filter',
filter=agg_filter
).bucket(f, agg) | python | def aggregate(self, search):
"""
Add aggregations representing the facets selected, including potential
filters.
"""
for f, facet in iteritems(self.facets):
agg = facet.get_aggregation()
agg_filter = MatchAll()
for field, filter in iteritems(self._filters):
if f == field:
continue
agg_filter &= filter
search.aggs.bucket(
'_filter_' + f,
'filter',
filter=agg_filter
).bucket(f, agg) | [
"def",
"aggregate",
"(",
"self",
",",
"search",
")",
":",
"for",
"f",
",",
"facet",
"in",
"iteritems",
"(",
"self",
".",
"facets",
")",
":",
"agg",
"=",
"facet",
".",
"get_aggregation",
"(",
")",
"agg_filter",
"=",
"MatchAll",
"(",
")",
"for",
"field... | Add aggregations representing the facets selected, including potential
filters. | [
"Add",
"aggregations",
"representing",
"the",
"facets",
"selected",
"including",
"potential",
"filters",
"."
] | 874b52472fc47b601de0e5fa0e4300e21aff0085 | https://github.com/elastic/elasticsearch-dsl-py/blob/874b52472fc47b601de0e5fa0e4300e21aff0085/elasticsearch_dsl/faceted_search.py#L326-L342 |
32,308 | elastic/elasticsearch-dsl-py | elasticsearch_dsl/faceted_search.py | FacetedSearch.filter | def filter(self, search):
"""
Add a ``post_filter`` to the search request narrowing the results based
on the facet filters.
"""
if not self._filters:
return search
post_filter = MatchAll()
for f in itervalues(self._filters):
post_filter &= f
return search.post_filter(post_filter) | python | def filter(self, search):
"""
Add a ``post_filter`` to the search request narrowing the results based
on the facet filters.
"""
if not self._filters:
return search
post_filter = MatchAll()
for f in itervalues(self._filters):
post_filter &= f
return search.post_filter(post_filter) | [
"def",
"filter",
"(",
"self",
",",
"search",
")",
":",
"if",
"not",
"self",
".",
"_filters",
":",
"return",
"search",
"post_filter",
"=",
"MatchAll",
"(",
")",
"for",
"f",
"in",
"itervalues",
"(",
"self",
".",
"_filters",
")",
":",
"post_filter",
"&=",... | Add a ``post_filter`` to the search request narrowing the results based
on the facet filters. | [
"Add",
"a",
"post_filter",
"to",
"the",
"search",
"request",
"narrowing",
"the",
"results",
"based",
"on",
"the",
"facet",
"filters",
"."
] | 874b52472fc47b601de0e5fa0e4300e21aff0085 | https://github.com/elastic/elasticsearch-dsl-py/blob/874b52472fc47b601de0e5fa0e4300e21aff0085/elasticsearch_dsl/faceted_search.py#L344-L355 |
32,309 | elastic/elasticsearch-dsl-py | elasticsearch_dsl/faceted_search.py | FacetedSearch.highlight | def highlight(self, search):
"""
Add highlighting for all the fields
"""
return search.highlight(*(f if '^' not in f else f.split('^', 1)[0]
for f in self.fields)) | python | def highlight(self, search):
"""
Add highlighting for all the fields
"""
return search.highlight(*(f if '^' not in f else f.split('^', 1)[0]
for f in self.fields)) | [
"def",
"highlight",
"(",
"self",
",",
"search",
")",
":",
"return",
"search",
".",
"highlight",
"(",
"*",
"(",
"f",
"if",
"'^'",
"not",
"in",
"f",
"else",
"f",
".",
"split",
"(",
"'^'",
",",
"1",
")",
"[",
"0",
"]",
"for",
"f",
"in",
"self",
... | Add highlighting for all the fields | [
"Add",
"highlighting",
"for",
"all",
"the",
"fields"
] | 874b52472fc47b601de0e5fa0e4300e21aff0085 | https://github.com/elastic/elasticsearch-dsl-py/blob/874b52472fc47b601de0e5fa0e4300e21aff0085/elasticsearch_dsl/faceted_search.py#L357-L362 |
32,310 | elastic/elasticsearch-dsl-py | elasticsearch_dsl/faceted_search.py | FacetedSearch.sort | def sort(self, search):
"""
Add sorting information to the request.
"""
if self._sort:
search = search.sort(*self._sort)
return search | python | def sort(self, search):
"""
Add sorting information to the request.
"""
if self._sort:
search = search.sort(*self._sort)
return search | [
"def",
"sort",
"(",
"self",
",",
"search",
")",
":",
"if",
"self",
".",
"_sort",
":",
"search",
"=",
"search",
".",
"sort",
"(",
"*",
"self",
".",
"_sort",
")",
"return",
"search"
] | Add sorting information to the request. | [
"Add",
"sorting",
"information",
"to",
"the",
"request",
"."
] | 874b52472fc47b601de0e5fa0e4300e21aff0085 | https://github.com/elastic/elasticsearch-dsl-py/blob/874b52472fc47b601de0e5fa0e4300e21aff0085/elasticsearch_dsl/faceted_search.py#L364-L370 |
32,311 | elastic/elasticsearch-dsl-py | elasticsearch_dsl/faceted_search.py | FacetedSearch.execute | def execute(self):
"""
Execute the search and return the response.
"""
r = self._s.execute()
r._faceted_search = self
return r | python | def execute(self):
"""
Execute the search and return the response.
"""
r = self._s.execute()
r._faceted_search = self
return r | [
"def",
"execute",
"(",
"self",
")",
":",
"r",
"=",
"self",
".",
"_s",
".",
"execute",
"(",
")",
"r",
".",
"_faceted_search",
"=",
"self",
"return",
"r"
] | Execute the search and return the response. | [
"Execute",
"the",
"search",
"and",
"return",
"the",
"response",
"."
] | 874b52472fc47b601de0e5fa0e4300e21aff0085 | https://github.com/elastic/elasticsearch-dsl-py/blob/874b52472fc47b601de0e5fa0e4300e21aff0085/elasticsearch_dsl/faceted_search.py#L385-L391 |
32,312 | elastic/elasticsearch-dsl-py | elasticsearch_dsl/search.py | Request.index | def index(self, *index):
"""
Set the index for the search. If called empty it will remove all information.
Example:
s = Search()
s = s.index('twitter-2015.01.01', 'twitter-2015.01.02')
s = s.index(['twitter-2015.01.01', 'twitter-2015.01.02'])
"""
# .index() resets
s = self._clone()
if not index:
s._index = None
else:
indexes = []
for i in index:
if isinstance(i, string_types):
indexes.append(i)
elif isinstance(i, list):
indexes += i
elif isinstance(i, tuple):
indexes += list(i)
s._index = (self._index or []) + indexes
return s | python | def index(self, *index):
"""
Set the index for the search. If called empty it will remove all information.
Example:
s = Search()
s = s.index('twitter-2015.01.01', 'twitter-2015.01.02')
s = s.index(['twitter-2015.01.01', 'twitter-2015.01.02'])
"""
# .index() resets
s = self._clone()
if not index:
s._index = None
else:
indexes = []
for i in index:
if isinstance(i, string_types):
indexes.append(i)
elif isinstance(i, list):
indexes += i
elif isinstance(i, tuple):
indexes += list(i)
s._index = (self._index or []) + indexes
return s | [
"def",
"index",
"(",
"self",
",",
"*",
"index",
")",
":",
"# .index() resets",
"s",
"=",
"self",
".",
"_clone",
"(",
")",
"if",
"not",
"index",
":",
"s",
".",
"_index",
"=",
"None",
"else",
":",
"indexes",
"=",
"[",
"]",
"for",
"i",
"in",
"index"... | Set the index for the search. If called empty it will remove all information.
Example:
s = Search()
s = s.index('twitter-2015.01.01', 'twitter-2015.01.02')
s = s.index(['twitter-2015.01.01', 'twitter-2015.01.02']) | [
"Set",
"the",
"index",
"for",
"the",
"search",
".",
"If",
"called",
"empty",
"it",
"will",
"remove",
"all",
"information",
"."
] | 874b52472fc47b601de0e5fa0e4300e21aff0085 | https://github.com/elastic/elasticsearch-dsl-py/blob/874b52472fc47b601de0e5fa0e4300e21aff0085/elasticsearch_dsl/search.py#L147-L173 |
32,313 | elastic/elasticsearch-dsl-py | elasticsearch_dsl/search.py | Request.doc_type | def doc_type(self, *doc_type, **kwargs):
"""
Set the type to search through. You can supply a single value or
multiple. Values can be strings or subclasses of ``Document``.
You can also pass in any keyword arguments, mapping a doc_type to a
callback that should be used instead of the Hit class.
If no doc_type is supplied any information stored on the instance will
be erased.
Example:
s = Search().doc_type('product', 'store', User, custom=my_callback)
"""
# .doc_type() resets
s = self._clone()
if not doc_type and not kwargs:
s._doc_type = []
s._doc_type_map = {}
else:
s._doc_type.extend(doc_type)
s._doc_type.extend(kwargs.keys())
s._doc_type_map.update(kwargs)
return s | python | def doc_type(self, *doc_type, **kwargs):
"""
Set the type to search through. You can supply a single value or
multiple. Values can be strings or subclasses of ``Document``.
You can also pass in any keyword arguments, mapping a doc_type to a
callback that should be used instead of the Hit class.
If no doc_type is supplied any information stored on the instance will
be erased.
Example:
s = Search().doc_type('product', 'store', User, custom=my_callback)
"""
# .doc_type() resets
s = self._clone()
if not doc_type and not kwargs:
s._doc_type = []
s._doc_type_map = {}
else:
s._doc_type.extend(doc_type)
s._doc_type.extend(kwargs.keys())
s._doc_type_map.update(kwargs)
return s | [
"def",
"doc_type",
"(",
"self",
",",
"*",
"doc_type",
",",
"*",
"*",
"kwargs",
")",
":",
"# .doc_type() resets",
"s",
"=",
"self",
".",
"_clone",
"(",
")",
"if",
"not",
"doc_type",
"and",
"not",
"kwargs",
":",
"s",
".",
"_doc_type",
"=",
"[",
"]",
... | Set the type to search through. You can supply a single value or
multiple. Values can be strings or subclasses of ``Document``.
You can also pass in any keyword arguments, mapping a doc_type to a
callback that should be used instead of the Hit class.
If no doc_type is supplied any information stored on the instance will
be erased.
Example:
s = Search().doc_type('product', 'store', User, custom=my_callback) | [
"Set",
"the",
"type",
"to",
"search",
"through",
".",
"You",
"can",
"supply",
"a",
"single",
"value",
"or",
"multiple",
".",
"Values",
"can",
"be",
"strings",
"or",
"subclasses",
"of",
"Document",
"."
] | 874b52472fc47b601de0e5fa0e4300e21aff0085 | https://github.com/elastic/elasticsearch-dsl-py/blob/874b52472fc47b601de0e5fa0e4300e21aff0085/elasticsearch_dsl/search.py#L225-L249 |
32,314 | elastic/elasticsearch-dsl-py | elasticsearch_dsl/search.py | Request.using | def using(self, client):
"""
Associate the search request with an elasticsearch client. A fresh copy
will be returned with current instance remaining unchanged.
:arg client: an instance of ``elasticsearch.Elasticsearch`` to use or
an alias to look up in ``elasticsearch_dsl.connections``
"""
s = self._clone()
s._using = client
return s | python | def using(self, client):
"""
Associate the search request with an elasticsearch client. A fresh copy
will be returned with current instance remaining unchanged.
:arg client: an instance of ``elasticsearch.Elasticsearch`` to use or
an alias to look up in ``elasticsearch_dsl.connections``
"""
s = self._clone()
s._using = client
return s | [
"def",
"using",
"(",
"self",
",",
"client",
")",
":",
"s",
"=",
"self",
".",
"_clone",
"(",
")",
"s",
".",
"_using",
"=",
"client",
"return",
"s"
] | Associate the search request with an elasticsearch client. A fresh copy
will be returned with current instance remaining unchanged.
:arg client: an instance of ``elasticsearch.Elasticsearch`` to use or
an alias to look up in ``elasticsearch_dsl.connections`` | [
"Associate",
"the",
"search",
"request",
"with",
"an",
"elasticsearch",
"client",
".",
"A",
"fresh",
"copy",
"will",
"be",
"returned",
"with",
"current",
"instance",
"remaining",
"unchanged",
"."
] | 874b52472fc47b601de0e5fa0e4300e21aff0085 | https://github.com/elastic/elasticsearch-dsl-py/blob/874b52472fc47b601de0e5fa0e4300e21aff0085/elasticsearch_dsl/search.py#L251-L262 |
32,315 | elastic/elasticsearch-dsl-py | elasticsearch_dsl/search.py | Request.extra | def extra(self, **kwargs):
"""
Add extra keys to the request body. Mostly here for backwards
compatibility.
"""
s = self._clone()
if 'from_' in kwargs:
kwargs['from'] = kwargs.pop('from_')
s._extra.update(kwargs)
return s | python | def extra(self, **kwargs):
"""
Add extra keys to the request body. Mostly here for backwards
compatibility.
"""
s = self._clone()
if 'from_' in kwargs:
kwargs['from'] = kwargs.pop('from_')
s._extra.update(kwargs)
return s | [
"def",
"extra",
"(",
"self",
",",
"*",
"*",
"kwargs",
")",
":",
"s",
"=",
"self",
".",
"_clone",
"(",
")",
"if",
"'from_'",
"in",
"kwargs",
":",
"kwargs",
"[",
"'from'",
"]",
"=",
"kwargs",
".",
"pop",
"(",
"'from_'",
")",
"s",
".",
"_extra",
"... | Add extra keys to the request body. Mostly here for backwards
compatibility. | [
"Add",
"extra",
"keys",
"to",
"the",
"request",
"body",
".",
"Mostly",
"here",
"for",
"backwards",
"compatibility",
"."
] | 874b52472fc47b601de0e5fa0e4300e21aff0085 | https://github.com/elastic/elasticsearch-dsl-py/blob/874b52472fc47b601de0e5fa0e4300e21aff0085/elasticsearch_dsl/search.py#L264-L273 |
32,316 | elastic/elasticsearch-dsl-py | elasticsearch_dsl/search.py | Search.source | def source(self, fields=None, **kwargs):
"""
Selectively control how the _source field is returned.
:arg fields: wildcard string, array of wildcards, or dictionary of includes and excludes
If ``fields`` is None, the entire document will be returned for
each hit. If fields is a dictionary with keys of 'include' and/or
'exclude' the fields will be either included or excluded appropriately.
Calling this multiple times with the same named parameter will override the
previous values with the new ones.
Example::
s = Search()
s = s.source(include=['obj1.*'], exclude=["*.description"])
s = Search()
s = s.source(include=['obj1.*']).source(exclude=["*.description"])
"""
s = self._clone()
if fields and kwargs:
raise ValueError("You cannot specify fields and kwargs at the same time.")
if fields is not None:
s._source = fields
return s
if kwargs and not isinstance(s._source, dict):
s._source = {}
for key, value in kwargs.items():
if value is None:
try:
del s._source[key]
except KeyError:
pass
else:
s._source[key] = value
return s | python | def source(self, fields=None, **kwargs):
"""
Selectively control how the _source field is returned.
:arg fields: wildcard string, array of wildcards, or dictionary of includes and excludes
If ``fields`` is None, the entire document will be returned for
each hit. If fields is a dictionary with keys of 'include' and/or
'exclude' the fields will be either included or excluded appropriately.
Calling this multiple times with the same named parameter will override the
previous values with the new ones.
Example::
s = Search()
s = s.source(include=['obj1.*'], exclude=["*.description"])
s = Search()
s = s.source(include=['obj1.*']).source(exclude=["*.description"])
"""
s = self._clone()
if fields and kwargs:
raise ValueError("You cannot specify fields and kwargs at the same time.")
if fields is not None:
s._source = fields
return s
if kwargs and not isinstance(s._source, dict):
s._source = {}
for key, value in kwargs.items():
if value is None:
try:
del s._source[key]
except KeyError:
pass
else:
s._source[key] = value
return s | [
"def",
"source",
"(",
"self",
",",
"fields",
"=",
"None",
",",
"*",
"*",
"kwargs",
")",
":",
"s",
"=",
"self",
".",
"_clone",
"(",
")",
"if",
"fields",
"and",
"kwargs",
":",
"raise",
"ValueError",
"(",
"\"You cannot specify fields and kwargs at the same time... | Selectively control how the _source field is returned.
:arg fields: wildcard string, array of wildcards, or dictionary of includes and excludes
If ``fields`` is None, the entire document will be returned for
each hit. If fields is a dictionary with keys of 'include' and/or
'exclude' the fields will be either included or excluded appropriately.
Calling this multiple times with the same named parameter will override the
previous values with the new ones.
Example::
s = Search()
s = s.source(include=['obj1.*'], exclude=["*.description"])
s = Search()
s = s.source(include=['obj1.*']).source(exclude=["*.description"]) | [
"Selectively",
"control",
"how",
"the",
"_source",
"field",
"is",
"returned",
"."
] | 874b52472fc47b601de0e5fa0e4300e21aff0085 | https://github.com/elastic/elasticsearch-dsl-py/blob/874b52472fc47b601de0e5fa0e4300e21aff0085/elasticsearch_dsl/search.py#L474-L517 |
32,317 | elastic/elasticsearch-dsl-py | elasticsearch_dsl/search.py | Search.suggest | def suggest(self, name, text, **kwargs):
"""
Add a suggestions request to the search.
:arg name: name of the suggestion
:arg text: text to suggest on
All keyword arguments will be added to the suggestions body. For example::
s = Search()
s = s.suggest('suggestion-1', 'Elasticsearch', term={'field': 'body'})
"""
s = self._clone()
s._suggest[name] = {'text': text}
s._suggest[name].update(kwargs)
return s | python | def suggest(self, name, text, **kwargs):
"""
Add a suggestions request to the search.
:arg name: name of the suggestion
:arg text: text to suggest on
All keyword arguments will be added to the suggestions body. For example::
s = Search()
s = s.suggest('suggestion-1', 'Elasticsearch', term={'field': 'body'})
"""
s = self._clone()
s._suggest[name] = {'text': text}
s._suggest[name].update(kwargs)
return s | [
"def",
"suggest",
"(",
"self",
",",
"name",
",",
"text",
",",
"*",
"*",
"kwargs",
")",
":",
"s",
"=",
"self",
".",
"_clone",
"(",
")",
"s",
".",
"_suggest",
"[",
"name",
"]",
"=",
"{",
"'text'",
":",
"text",
"}",
"s",
".",
"_suggest",
"[",
"n... | Add a suggestions request to the search.
:arg name: name of the suggestion
:arg text: text to suggest on
All keyword arguments will be added to the suggestions body. For example::
s = Search()
s = s.suggest('suggestion-1', 'Elasticsearch', term={'field': 'body'}) | [
"Add",
"a",
"suggestions",
"request",
"to",
"the",
"search",
"."
] | 874b52472fc47b601de0e5fa0e4300e21aff0085 | https://github.com/elastic/elasticsearch-dsl-py/blob/874b52472fc47b601de0e5fa0e4300e21aff0085/elasticsearch_dsl/search.py#L603-L618 |
32,318 | elastic/elasticsearch-dsl-py | elasticsearch_dsl/search.py | Search.to_dict | def to_dict(self, count=False, **kwargs):
"""
Serialize the search into the dictionary that will be sent over as the
request's body.
:arg count: a flag to specify if we are interested in a body for count -
no aggregations, no pagination bounds etc.
All additional keyword arguments will be included into the dictionary.
"""
d = {}
if self.query:
d["query"] = self.query.to_dict()
# count request doesn't care for sorting and other things
if not count:
if self.post_filter:
d['post_filter'] = self.post_filter.to_dict()
if self.aggs.aggs:
d.update(self.aggs.to_dict())
if self._sort:
d['sort'] = self._sort
d.update(self._extra)
if self._source not in (None, {}):
d['_source'] = self._source
if self._highlight:
d['highlight'] = {'fields': self._highlight}
d['highlight'].update(self._highlight_opts)
if self._suggest:
d['suggest'] = self._suggest
if self._script_fields:
d['script_fields'] = self._script_fields
d.update(kwargs)
return d | python | def to_dict(self, count=False, **kwargs):
"""
Serialize the search into the dictionary that will be sent over as the
request's body.
:arg count: a flag to specify if we are interested in a body for count -
no aggregations, no pagination bounds etc.
All additional keyword arguments will be included into the dictionary.
"""
d = {}
if self.query:
d["query"] = self.query.to_dict()
# count request doesn't care for sorting and other things
if not count:
if self.post_filter:
d['post_filter'] = self.post_filter.to_dict()
if self.aggs.aggs:
d.update(self.aggs.to_dict())
if self._sort:
d['sort'] = self._sort
d.update(self._extra)
if self._source not in (None, {}):
d['_source'] = self._source
if self._highlight:
d['highlight'] = {'fields': self._highlight}
d['highlight'].update(self._highlight_opts)
if self._suggest:
d['suggest'] = self._suggest
if self._script_fields:
d['script_fields'] = self._script_fields
d.update(kwargs)
return d | [
"def",
"to_dict",
"(",
"self",
",",
"count",
"=",
"False",
",",
"*",
"*",
"kwargs",
")",
":",
"d",
"=",
"{",
"}",
"if",
"self",
".",
"query",
":",
"d",
"[",
"\"query\"",
"]",
"=",
"self",
".",
"query",
".",
"to_dict",
"(",
")",
"# count request d... | Serialize the search into the dictionary that will be sent over as the
request's body.
:arg count: a flag to specify if we are interested in a body for count -
no aggregations, no pagination bounds etc.
All additional keyword arguments will be included into the dictionary. | [
"Serialize",
"the",
"search",
"into",
"the",
"dictionary",
"that",
"will",
"be",
"sent",
"over",
"as",
"the",
"request",
"s",
"body",
"."
] | 874b52472fc47b601de0e5fa0e4300e21aff0085 | https://github.com/elastic/elasticsearch-dsl-py/blob/874b52472fc47b601de0e5fa0e4300e21aff0085/elasticsearch_dsl/search.py#L620-L662 |
32,319 | elastic/elasticsearch-dsl-py | elasticsearch_dsl/search.py | Search.count | def count(self):
"""
Return the number of hits matching the query and filters. Note that
only the actual number is returned.
"""
if hasattr(self, '_response'):
return self._response.hits.total
es = connections.get_connection(self._using)
d = self.to_dict(count=True)
# TODO: failed shards detection
return es.count(
index=self._index,
body=d,
**self._params
)['count'] | python | def count(self):
"""
Return the number of hits matching the query and filters. Note that
only the actual number is returned.
"""
if hasattr(self, '_response'):
return self._response.hits.total
es = connections.get_connection(self._using)
d = self.to_dict(count=True)
# TODO: failed shards detection
return es.count(
index=self._index,
body=d,
**self._params
)['count'] | [
"def",
"count",
"(",
"self",
")",
":",
"if",
"hasattr",
"(",
"self",
",",
"'_response'",
")",
":",
"return",
"self",
".",
"_response",
".",
"hits",
".",
"total",
"es",
"=",
"connections",
".",
"get_connection",
"(",
"self",
".",
"_using",
")",
"d",
"... | Return the number of hits matching the query and filters. Note that
only the actual number is returned. | [
"Return",
"the",
"number",
"of",
"hits",
"matching",
"the",
"query",
"and",
"filters",
".",
"Note",
"that",
"only",
"the",
"actual",
"number",
"is",
"returned",
"."
] | 874b52472fc47b601de0e5fa0e4300e21aff0085 | https://github.com/elastic/elasticsearch-dsl-py/blob/874b52472fc47b601de0e5fa0e4300e21aff0085/elasticsearch_dsl/search.py#L664-L680 |
32,320 | elastic/elasticsearch-dsl-py | elasticsearch_dsl/search.py | Search.scan | def scan(self):
"""
Turn the search into a scan search and return a generator that will
iterate over all the documents matching the query.
Use ``params`` method to specify any additional arguments you with to
pass to the underlying ``scan`` helper from ``elasticsearch-py`` -
https://elasticsearch-py.readthedocs.io/en/master/helpers.html#elasticsearch.helpers.scan
"""
es = connections.get_connection(self._using)
for hit in scan(
es,
query=self.to_dict(),
index=self._index,
**self._params
):
yield self._get_result(hit) | python | def scan(self):
"""
Turn the search into a scan search and return a generator that will
iterate over all the documents matching the query.
Use ``params`` method to specify any additional arguments you with to
pass to the underlying ``scan`` helper from ``elasticsearch-py`` -
https://elasticsearch-py.readthedocs.io/en/master/helpers.html#elasticsearch.helpers.scan
"""
es = connections.get_connection(self._using)
for hit in scan(
es,
query=self.to_dict(),
index=self._index,
**self._params
):
yield self._get_result(hit) | [
"def",
"scan",
"(",
"self",
")",
":",
"es",
"=",
"connections",
".",
"get_connection",
"(",
"self",
".",
"_using",
")",
"for",
"hit",
"in",
"scan",
"(",
"es",
",",
"query",
"=",
"self",
".",
"to_dict",
"(",
")",
",",
"index",
"=",
"self",
".",
"_... | Turn the search into a scan search and return a generator that will
iterate over all the documents matching the query.
Use ``params`` method to specify any additional arguments you with to
pass to the underlying ``scan`` helper from ``elasticsearch-py`` -
https://elasticsearch-py.readthedocs.io/en/master/helpers.html#elasticsearch.helpers.scan | [
"Turn",
"the",
"search",
"into",
"a",
"scan",
"search",
"and",
"return",
"a",
"generator",
"that",
"will",
"iterate",
"over",
"all",
"the",
"documents",
"matching",
"the",
"query",
"."
] | 874b52472fc47b601de0e5fa0e4300e21aff0085 | https://github.com/elastic/elasticsearch-dsl-py/blob/874b52472fc47b601de0e5fa0e4300e21aff0085/elasticsearch_dsl/search.py#L703-L721 |
32,321 | elastic/elasticsearch-dsl-py | elasticsearch_dsl/search.py | MultiSearch.execute | def execute(self, ignore_cache=False, raise_on_error=True):
"""
Execute the multi search request and return a list of search results.
"""
if ignore_cache or not hasattr(self, '_response'):
es = connections.get_connection(self._using)
responses = es.msearch(
index=self._index,
body=self.to_dict(),
**self._params
)
out = []
for s, r in zip(self._searches, responses['responses']):
if r.get('error', False):
if raise_on_error:
raise TransportError('N/A', r['error']['type'], r['error'])
r = None
else:
r = Response(s, r)
out.append(r)
self._response = out
return self._response | python | def execute(self, ignore_cache=False, raise_on_error=True):
"""
Execute the multi search request and return a list of search results.
"""
if ignore_cache or not hasattr(self, '_response'):
es = connections.get_connection(self._using)
responses = es.msearch(
index=self._index,
body=self.to_dict(),
**self._params
)
out = []
for s, r in zip(self._searches, responses['responses']):
if r.get('error', False):
if raise_on_error:
raise TransportError('N/A', r['error']['type'], r['error'])
r = None
else:
r = Response(s, r)
out.append(r)
self._response = out
return self._response | [
"def",
"execute",
"(",
"self",
",",
"ignore_cache",
"=",
"False",
",",
"raise_on_error",
"=",
"True",
")",
":",
"if",
"ignore_cache",
"or",
"not",
"hasattr",
"(",
"self",
",",
"'_response'",
")",
":",
"es",
"=",
"connections",
".",
"get_connection",
"(",
... | Execute the multi search request and return a list of search results. | [
"Execute",
"the",
"multi",
"search",
"request",
"and",
"return",
"a",
"list",
"of",
"search",
"results",
"."
] | 874b52472fc47b601de0e5fa0e4300e21aff0085 | https://github.com/elastic/elasticsearch-dsl-py/blob/874b52472fc47b601de0e5fa0e4300e21aff0085/elasticsearch_dsl/search.py#L784-L809 |
32,322 | paramiko/paramiko | paramiko/kex_gss.py | KexGSSGroup1._parse_kexgss_continue | def _parse_kexgss_continue(self, m):
"""
Parse the SSH2_MSG_KEXGSS_CONTINUE message.
:param `.Message` m: The content of the SSH2_MSG_KEXGSS_CONTINUE
message
"""
if not self.transport.server_mode:
srv_token = m.get_string()
m = Message()
m.add_byte(c_MSG_KEXGSS_CONTINUE)
m.add_string(
self.kexgss.ssh_init_sec_context(
target=self.gss_host, recv_token=srv_token
)
)
self.transport.send_message(m)
self.transport._expect_packet(
MSG_KEXGSS_CONTINUE, MSG_KEXGSS_COMPLETE, MSG_KEXGSS_ERROR
)
else:
pass | python | def _parse_kexgss_continue(self, m):
"""
Parse the SSH2_MSG_KEXGSS_CONTINUE message.
:param `.Message` m: The content of the SSH2_MSG_KEXGSS_CONTINUE
message
"""
if not self.transport.server_mode:
srv_token = m.get_string()
m = Message()
m.add_byte(c_MSG_KEXGSS_CONTINUE)
m.add_string(
self.kexgss.ssh_init_sec_context(
target=self.gss_host, recv_token=srv_token
)
)
self.transport.send_message(m)
self.transport._expect_packet(
MSG_KEXGSS_CONTINUE, MSG_KEXGSS_COMPLETE, MSG_KEXGSS_ERROR
)
else:
pass | [
"def",
"_parse_kexgss_continue",
"(",
"self",
",",
"m",
")",
":",
"if",
"not",
"self",
".",
"transport",
".",
"server_mode",
":",
"srv_token",
"=",
"m",
".",
"get_string",
"(",
")",
"m",
"=",
"Message",
"(",
")",
"m",
".",
"add_byte",
"(",
"c_MSG_KEXGS... | Parse the SSH2_MSG_KEXGSS_CONTINUE message.
:param `.Message` m: The content of the SSH2_MSG_KEXGSS_CONTINUE
message | [
"Parse",
"the",
"SSH2_MSG_KEXGSS_CONTINUE",
"message",
"."
] | cf7d49d66f3b1fbc8b0853518a54050182b3b5eb | https://github.com/paramiko/paramiko/blob/cf7d49d66f3b1fbc8b0853518a54050182b3b5eb/paramiko/kex_gss.py#L168-L189 |
32,323 | paramiko/paramiko | paramiko/sftp_file.py | SFTPFile._data_in_prefetch_buffers | def _data_in_prefetch_buffers(self, offset):
"""
if a block of data is present in the prefetch buffers, at the given
offset, return the offset of the relevant prefetch buffer. otherwise,
return None. this guarantees nothing about the number of bytes
collected in the prefetch buffer so far.
"""
k = [i for i in self._prefetch_data.keys() if i <= offset]
if len(k) == 0:
return None
index = max(k)
buf_offset = offset - index
if buf_offset >= len(self._prefetch_data[index]):
# it's not here
return None
return index | python | def _data_in_prefetch_buffers(self, offset):
"""
if a block of data is present in the prefetch buffers, at the given
offset, return the offset of the relevant prefetch buffer. otherwise,
return None. this guarantees nothing about the number of bytes
collected in the prefetch buffer so far.
"""
k = [i for i in self._prefetch_data.keys() if i <= offset]
if len(k) == 0:
return None
index = max(k)
buf_offset = offset - index
if buf_offset >= len(self._prefetch_data[index]):
# it's not here
return None
return index | [
"def",
"_data_in_prefetch_buffers",
"(",
"self",
",",
"offset",
")",
":",
"k",
"=",
"[",
"i",
"for",
"i",
"in",
"self",
".",
"_prefetch_data",
".",
"keys",
"(",
")",
"if",
"i",
"<=",
"offset",
"]",
"if",
"len",
"(",
"k",
")",
"==",
"0",
":",
"ret... | if a block of data is present in the prefetch buffers, at the given
offset, return the offset of the relevant prefetch buffer. otherwise,
return None. this guarantees nothing about the number of bytes
collected in the prefetch buffer so far. | [
"if",
"a",
"block",
"of",
"data",
"is",
"present",
"in",
"the",
"prefetch",
"buffers",
"at",
"the",
"given",
"offset",
"return",
"the",
"offset",
"of",
"the",
"relevant",
"prefetch",
"buffer",
".",
"otherwise",
"return",
"None",
".",
"this",
"guarantees",
... | cf7d49d66f3b1fbc8b0853518a54050182b3b5eb | https://github.com/paramiko/paramiko/blob/cf7d49d66f3b1fbc8b0853518a54050182b3b5eb/paramiko/sftp_file.py#L132-L147 |
32,324 | paramiko/paramiko | paramiko/sftp_file.py | SFTPFile.seek | def seek(self, offset, whence=0):
"""
Set the file's current position.
See `file.seek` for details.
"""
self.flush()
if whence == self.SEEK_SET:
self._realpos = self._pos = offset
elif whence == self.SEEK_CUR:
self._pos += offset
self._realpos = self._pos
else:
self._realpos = self._pos = self._get_size() + offset
self._rbuffer = bytes() | python | def seek(self, offset, whence=0):
"""
Set the file's current position.
See `file.seek` for details.
"""
self.flush()
if whence == self.SEEK_SET:
self._realpos = self._pos = offset
elif whence == self.SEEK_CUR:
self._pos += offset
self._realpos = self._pos
else:
self._realpos = self._pos = self._get_size() + offset
self._rbuffer = bytes() | [
"def",
"seek",
"(",
"self",
",",
"offset",
",",
"whence",
"=",
"0",
")",
":",
"self",
".",
"flush",
"(",
")",
"if",
"whence",
"==",
"self",
".",
"SEEK_SET",
":",
"self",
".",
"_realpos",
"=",
"self",
".",
"_pos",
"=",
"offset",
"elif",
"whence",
... | Set the file's current position.
See `file.seek` for details. | [
"Set",
"the",
"file",
"s",
"current",
"position",
"."
] | cf7d49d66f3b1fbc8b0853518a54050182b3b5eb | https://github.com/paramiko/paramiko/blob/cf7d49d66f3b1fbc8b0853518a54050182b3b5eb/paramiko/sftp_file.py#L258-L272 |
32,325 | paramiko/paramiko | paramiko/sftp_file.py | SFTPFile.stat | def stat(self):
"""
Retrieve information about this file from the remote system. This is
exactly like `.SFTPClient.stat`, except that it operates on an
already-open file.
:returns:
an `.SFTPAttributes` object containing attributes about this file.
"""
t, msg = self.sftp._request(CMD_FSTAT, self.handle)
if t != CMD_ATTRS:
raise SFTPError("Expected attributes")
return SFTPAttributes._from_msg(msg) | python | def stat(self):
"""
Retrieve information about this file from the remote system. This is
exactly like `.SFTPClient.stat`, except that it operates on an
already-open file.
:returns:
an `.SFTPAttributes` object containing attributes about this file.
"""
t, msg = self.sftp._request(CMD_FSTAT, self.handle)
if t != CMD_ATTRS:
raise SFTPError("Expected attributes")
return SFTPAttributes._from_msg(msg) | [
"def",
"stat",
"(",
"self",
")",
":",
"t",
",",
"msg",
"=",
"self",
".",
"sftp",
".",
"_request",
"(",
"CMD_FSTAT",
",",
"self",
".",
"handle",
")",
"if",
"t",
"!=",
"CMD_ATTRS",
":",
"raise",
"SFTPError",
"(",
"\"Expected attributes\"",
")",
"return",... | Retrieve information about this file from the remote system. This is
exactly like `.SFTPClient.stat`, except that it operates on an
already-open file.
:returns:
an `.SFTPAttributes` object containing attributes about this file. | [
"Retrieve",
"information",
"about",
"this",
"file",
"from",
"the",
"remote",
"system",
".",
"This",
"is",
"exactly",
"like",
".",
"SFTPClient",
".",
"stat",
"except",
"that",
"it",
"operates",
"on",
"an",
"already",
"-",
"open",
"file",
"."
] | cf7d49d66f3b1fbc8b0853518a54050182b3b5eb | https://github.com/paramiko/paramiko/blob/cf7d49d66f3b1fbc8b0853518a54050182b3b5eb/paramiko/sftp_file.py#L274-L286 |
32,326 | paramiko/paramiko | paramiko/sftp_file.py | SFTPFile.check | def check(self, hash_algorithm, offset=0, length=0, block_size=0):
"""
Ask the server for a hash of a section of this file. This can be used
to verify a successful upload or download, or for various rsync-like
operations.
The file is hashed from ``offset``, for ``length`` bytes.
If ``length`` is 0, the remainder of the file is hashed. Thus, if both
``offset`` and ``length`` are zero, the entire file is hashed.
Normally, ``block_size`` will be 0 (the default), and this method will
return a byte string representing the requested hash (for example, a
string of length 16 for MD5, or 20 for SHA-1). If a non-zero
``block_size`` is given, each chunk of the file (from ``offset`` to
``offset + length``) of ``block_size`` bytes is computed as a separate
hash. The hash results are all concatenated and returned as a single
string.
For example, ``check('sha1', 0, 1024, 512)`` will return a string of
length 40. The first 20 bytes will be the SHA-1 of the first 512 bytes
of the file, and the last 20 bytes will be the SHA-1 of the next 512
bytes.
:param str hash_algorithm:
the name of the hash algorithm to use (normally ``"sha1"`` or
``"md5"``)
:param offset:
offset into the file to begin hashing (0 means to start from the
beginning)
:param length:
number of bytes to hash (0 means continue to the end of the file)
:param int block_size:
number of bytes to hash per result (must not be less than 256; 0
means to compute only one hash of the entire segment)
:return:
`str` of bytes representing the hash of each block, concatenated
together
:raises:
``IOError`` -- if the server doesn't support the "check-file"
extension, or possibly doesn't support the hash algorithm requested
.. note:: Many (most?) servers don't support this extension yet.
.. versionadded:: 1.4
"""
t, msg = self.sftp._request(
CMD_EXTENDED,
"check-file",
self.handle,
hash_algorithm,
long(offset),
long(length),
block_size,
)
msg.get_text() # ext
msg.get_text() # alg
data = msg.get_remainder()
return data | python | def check(self, hash_algorithm, offset=0, length=0, block_size=0):
"""
Ask the server for a hash of a section of this file. This can be used
to verify a successful upload or download, or for various rsync-like
operations.
The file is hashed from ``offset``, for ``length`` bytes.
If ``length`` is 0, the remainder of the file is hashed. Thus, if both
``offset`` and ``length`` are zero, the entire file is hashed.
Normally, ``block_size`` will be 0 (the default), and this method will
return a byte string representing the requested hash (for example, a
string of length 16 for MD5, or 20 for SHA-1). If a non-zero
``block_size`` is given, each chunk of the file (from ``offset`` to
``offset + length``) of ``block_size`` bytes is computed as a separate
hash. The hash results are all concatenated and returned as a single
string.
For example, ``check('sha1', 0, 1024, 512)`` will return a string of
length 40. The first 20 bytes will be the SHA-1 of the first 512 bytes
of the file, and the last 20 bytes will be the SHA-1 of the next 512
bytes.
:param str hash_algorithm:
the name of the hash algorithm to use (normally ``"sha1"`` or
``"md5"``)
:param offset:
offset into the file to begin hashing (0 means to start from the
beginning)
:param length:
number of bytes to hash (0 means continue to the end of the file)
:param int block_size:
number of bytes to hash per result (must not be less than 256; 0
means to compute only one hash of the entire segment)
:return:
`str` of bytes representing the hash of each block, concatenated
together
:raises:
``IOError`` -- if the server doesn't support the "check-file"
extension, or possibly doesn't support the hash algorithm requested
.. note:: Many (most?) servers don't support this extension yet.
.. versionadded:: 1.4
"""
t, msg = self.sftp._request(
CMD_EXTENDED,
"check-file",
self.handle,
hash_algorithm,
long(offset),
long(length),
block_size,
)
msg.get_text() # ext
msg.get_text() # alg
data = msg.get_remainder()
return data | [
"def",
"check",
"(",
"self",
",",
"hash_algorithm",
",",
"offset",
"=",
"0",
",",
"length",
"=",
"0",
",",
"block_size",
"=",
"0",
")",
":",
"t",
",",
"msg",
"=",
"self",
".",
"sftp",
".",
"_request",
"(",
"CMD_EXTENDED",
",",
"\"check-file\"",
",",
... | Ask the server for a hash of a section of this file. This can be used
to verify a successful upload or download, or for various rsync-like
operations.
The file is hashed from ``offset``, for ``length`` bytes.
If ``length`` is 0, the remainder of the file is hashed. Thus, if both
``offset`` and ``length`` are zero, the entire file is hashed.
Normally, ``block_size`` will be 0 (the default), and this method will
return a byte string representing the requested hash (for example, a
string of length 16 for MD5, or 20 for SHA-1). If a non-zero
``block_size`` is given, each chunk of the file (from ``offset`` to
``offset + length``) of ``block_size`` bytes is computed as a separate
hash. The hash results are all concatenated and returned as a single
string.
For example, ``check('sha1', 0, 1024, 512)`` will return a string of
length 40. The first 20 bytes will be the SHA-1 of the first 512 bytes
of the file, and the last 20 bytes will be the SHA-1 of the next 512
bytes.
:param str hash_algorithm:
the name of the hash algorithm to use (normally ``"sha1"`` or
``"md5"``)
:param offset:
offset into the file to begin hashing (0 means to start from the
beginning)
:param length:
number of bytes to hash (0 means continue to the end of the file)
:param int block_size:
number of bytes to hash per result (must not be less than 256; 0
means to compute only one hash of the entire segment)
:return:
`str` of bytes representing the hash of each block, concatenated
together
:raises:
``IOError`` -- if the server doesn't support the "check-file"
extension, or possibly doesn't support the hash algorithm requested
.. note:: Many (most?) servers don't support this extension yet.
.. versionadded:: 1.4 | [
"Ask",
"the",
"server",
"for",
"a",
"hash",
"of",
"a",
"section",
"of",
"this",
"file",
".",
"This",
"can",
"be",
"used",
"to",
"verify",
"a",
"successful",
"upload",
"or",
"download",
"or",
"for",
"various",
"rsync",
"-",
"like",
"operations",
"."
] | cf7d49d66f3b1fbc8b0853518a54050182b3b5eb | https://github.com/paramiko/paramiko/blob/cf7d49d66f3b1fbc8b0853518a54050182b3b5eb/paramiko/sftp_file.py#L358-L416 |
32,327 | paramiko/paramiko | paramiko/sftp_file.py | SFTPFile.prefetch | def prefetch(self, file_size=None):
"""
Pre-fetch the remaining contents of this file in anticipation of future
`.read` calls. If reading the entire file, pre-fetching can
dramatically improve the download speed by avoiding roundtrip latency.
The file's contents are incrementally buffered in a background thread.
The prefetched data is stored in a buffer until read via the `.read`
method. Once data has been read, it's removed from the buffer. The
data may be read in a random order (using `.seek`); chunks of the
buffer that haven't been read will continue to be buffered.
:param int file_size:
When this is ``None`` (the default), this method calls `stat` to
determine the remote file size. In some situations, doing so can
cause exceptions or hangs (see `#562
<https://github.com/paramiko/paramiko/pull/562>`_); as a
workaround, one may call `stat` explicitly and pass its value in
via this parameter.
.. versionadded:: 1.5.1
.. versionchanged:: 1.16.0
The ``file_size`` parameter was added (with no default value).
.. versionchanged:: 1.16.1
The ``file_size`` parameter was made optional for backwards
compatibility.
"""
if file_size is None:
file_size = self.stat().st_size
# queue up async reads for the rest of the file
chunks = []
n = self._realpos
while n < file_size:
chunk = min(self.MAX_REQUEST_SIZE, file_size - n)
chunks.append((n, chunk))
n += chunk
if len(chunks) > 0:
self._start_prefetch(chunks) | python | def prefetch(self, file_size=None):
"""
Pre-fetch the remaining contents of this file in anticipation of future
`.read` calls. If reading the entire file, pre-fetching can
dramatically improve the download speed by avoiding roundtrip latency.
The file's contents are incrementally buffered in a background thread.
The prefetched data is stored in a buffer until read via the `.read`
method. Once data has been read, it's removed from the buffer. The
data may be read in a random order (using `.seek`); chunks of the
buffer that haven't been read will continue to be buffered.
:param int file_size:
When this is ``None`` (the default), this method calls `stat` to
determine the remote file size. In some situations, doing so can
cause exceptions or hangs (see `#562
<https://github.com/paramiko/paramiko/pull/562>`_); as a
workaround, one may call `stat` explicitly and pass its value in
via this parameter.
.. versionadded:: 1.5.1
.. versionchanged:: 1.16.0
The ``file_size`` parameter was added (with no default value).
.. versionchanged:: 1.16.1
The ``file_size`` parameter was made optional for backwards
compatibility.
"""
if file_size is None:
file_size = self.stat().st_size
# queue up async reads for the rest of the file
chunks = []
n = self._realpos
while n < file_size:
chunk = min(self.MAX_REQUEST_SIZE, file_size - n)
chunks.append((n, chunk))
n += chunk
if len(chunks) > 0:
self._start_prefetch(chunks) | [
"def",
"prefetch",
"(",
"self",
",",
"file_size",
"=",
"None",
")",
":",
"if",
"file_size",
"is",
"None",
":",
"file_size",
"=",
"self",
".",
"stat",
"(",
")",
".",
"st_size",
"# queue up async reads for the rest of the file",
"chunks",
"=",
"[",
"]",
"n",
... | Pre-fetch the remaining contents of this file in anticipation of future
`.read` calls. If reading the entire file, pre-fetching can
dramatically improve the download speed by avoiding roundtrip latency.
The file's contents are incrementally buffered in a background thread.
The prefetched data is stored in a buffer until read via the `.read`
method. Once data has been read, it's removed from the buffer. The
data may be read in a random order (using `.seek`); chunks of the
buffer that haven't been read will continue to be buffered.
:param int file_size:
When this is ``None`` (the default), this method calls `stat` to
determine the remote file size. In some situations, doing so can
cause exceptions or hangs (see `#562
<https://github.com/paramiko/paramiko/pull/562>`_); as a
workaround, one may call `stat` explicitly and pass its value in
via this parameter.
.. versionadded:: 1.5.1
.. versionchanged:: 1.16.0
The ``file_size`` parameter was added (with no default value).
.. versionchanged:: 1.16.1
The ``file_size`` parameter was made optional for backwards
compatibility. | [
"Pre",
"-",
"fetch",
"the",
"remaining",
"contents",
"of",
"this",
"file",
"in",
"anticipation",
"of",
"future",
".",
"read",
"calls",
".",
"If",
"reading",
"the",
"entire",
"file",
"pre",
"-",
"fetching",
"can",
"dramatically",
"improve",
"the",
"download",... | cf7d49d66f3b1fbc8b0853518a54050182b3b5eb | https://github.com/paramiko/paramiko/blob/cf7d49d66f3b1fbc8b0853518a54050182b3b5eb/paramiko/sftp_file.py#L438-L476 |
32,328 | paramiko/paramiko | paramiko/sftp_file.py | SFTPFile._check_exception | def _check_exception(self):
"""if there's a saved exception, raise & clear it"""
if self._saved_exception is not None:
x = self._saved_exception
self._saved_exception = None
raise x | python | def _check_exception(self):
"""if there's a saved exception, raise & clear it"""
if self._saved_exception is not None:
x = self._saved_exception
self._saved_exception = None
raise x | [
"def",
"_check_exception",
"(",
"self",
")",
":",
"if",
"self",
".",
"_saved_exception",
"is",
"not",
"None",
":",
"x",
"=",
"self",
".",
"_saved_exception",
"self",
".",
"_saved_exception",
"=",
"None",
"raise",
"x"
] | if there's a saved exception, raise & clear it | [
"if",
"there",
"s",
"a",
"saved",
"exception",
"raise",
"&",
"clear",
"it"
] | cf7d49d66f3b1fbc8b0853518a54050182b3b5eb | https://github.com/paramiko/paramiko/blob/cf7d49d66f3b1fbc8b0853518a54050182b3b5eb/paramiko/sftp_file.py#L565-L570 |
32,329 | paramiko/paramiko | paramiko/channel.py | open_only | def open_only(func):
"""
Decorator for `.Channel` methods which performs an openness check.
:raises:
`.SSHException` -- If the wrapped method is called on an unopened
`.Channel`.
"""
@wraps(func)
def _check(self, *args, **kwds):
if (
self.closed
or self.eof_received
or self.eof_sent
or not self.active
):
raise SSHException("Channel is not open")
return func(self, *args, **kwds)
return _check | python | def open_only(func):
"""
Decorator for `.Channel` methods which performs an openness check.
:raises:
`.SSHException` -- If the wrapped method is called on an unopened
`.Channel`.
"""
@wraps(func)
def _check(self, *args, **kwds):
if (
self.closed
or self.eof_received
or self.eof_sent
or not self.active
):
raise SSHException("Channel is not open")
return func(self, *args, **kwds)
return _check | [
"def",
"open_only",
"(",
"func",
")",
":",
"@",
"wraps",
"(",
"func",
")",
"def",
"_check",
"(",
"self",
",",
"*",
"args",
",",
"*",
"*",
"kwds",
")",
":",
"if",
"(",
"self",
".",
"closed",
"or",
"self",
".",
"eof_received",
"or",
"self",
".",
... | Decorator for `.Channel` methods which performs an openness check.
:raises:
`.SSHException` -- If the wrapped method is called on an unopened
`.Channel`. | [
"Decorator",
"for",
".",
"Channel",
"methods",
"which",
"performs",
"an",
"openness",
"check",
"."
] | cf7d49d66f3b1fbc8b0853518a54050182b3b5eb | https://github.com/paramiko/paramiko/blob/cf7d49d66f3b1fbc8b0853518a54050182b3b5eb/paramiko/channel.py#L54-L74 |
32,330 | paramiko/paramiko | paramiko/channel.py | Channel.exec_command | def exec_command(self, command):
"""
Execute a command on the server. If the server allows it, the channel
will then be directly connected to the stdin, stdout, and stderr of
the command being executed.
When the command finishes executing, the channel will be closed and
can't be reused. You must open a new channel if you wish to execute
another command.
:param str command: a shell command to execute.
:raises:
`.SSHException` -- if the request was rejected or the channel was
closed
"""
m = Message()
m.add_byte(cMSG_CHANNEL_REQUEST)
m.add_int(self.remote_chanid)
m.add_string("exec")
m.add_boolean(True)
m.add_string(command)
self._event_pending()
self.transport._send_user_message(m)
self._wait_for_event() | python | def exec_command(self, command):
"""
Execute a command on the server. If the server allows it, the channel
will then be directly connected to the stdin, stdout, and stderr of
the command being executed.
When the command finishes executing, the channel will be closed and
can't be reused. You must open a new channel if you wish to execute
another command.
:param str command: a shell command to execute.
:raises:
`.SSHException` -- if the request was rejected or the channel was
closed
"""
m = Message()
m.add_byte(cMSG_CHANNEL_REQUEST)
m.add_int(self.remote_chanid)
m.add_string("exec")
m.add_boolean(True)
m.add_string(command)
self._event_pending()
self.transport._send_user_message(m)
self._wait_for_event() | [
"def",
"exec_command",
"(",
"self",
",",
"command",
")",
":",
"m",
"=",
"Message",
"(",
")",
"m",
".",
"add_byte",
"(",
"cMSG_CHANNEL_REQUEST",
")",
"m",
".",
"add_int",
"(",
"self",
".",
"remote_chanid",
")",
"m",
".",
"add_string",
"(",
"\"exec\"",
"... | Execute a command on the server. If the server allows it, the channel
will then be directly connected to the stdin, stdout, and stderr of
the command being executed.
When the command finishes executing, the channel will be closed and
can't be reused. You must open a new channel if you wish to execute
another command.
:param str command: a shell command to execute.
:raises:
`.SSHException` -- if the request was rejected or the channel was
closed | [
"Execute",
"a",
"command",
"on",
"the",
"server",
".",
"If",
"the",
"server",
"allows",
"it",
"the",
"channel",
"will",
"then",
"be",
"directly",
"connected",
"to",
"the",
"stdin",
"stdout",
"and",
"stderr",
"of",
"the",
"command",
"being",
"executed",
"."... | cf7d49d66f3b1fbc8b0853518a54050182b3b5eb | https://github.com/paramiko/paramiko/blob/cf7d49d66f3b1fbc8b0853518a54050182b3b5eb/paramiko/channel.py#L233-L257 |
32,331 | paramiko/paramiko | paramiko/channel.py | Channel.update_environment | def update_environment(self, environment):
"""
Updates this channel's remote shell environment.
.. note::
This operation is additive - i.e. the current environment is not
reset before the given environment variables are set.
.. warning::
Servers may silently reject some environment variables; see the
warning in `set_environment_variable` for details.
:param dict environment:
a dictionary containing the name and respective values to set
:raises:
`.SSHException` -- if any of the environment variables was rejected
by the server or the channel was closed
"""
for name, value in environment.items():
try:
self.set_environment_variable(name, value)
except SSHException as e:
err = 'Failed to set environment variable "{}".'
raise SSHException(err.format(name), e) | python | def update_environment(self, environment):
"""
Updates this channel's remote shell environment.
.. note::
This operation is additive - i.e. the current environment is not
reset before the given environment variables are set.
.. warning::
Servers may silently reject some environment variables; see the
warning in `set_environment_variable` for details.
:param dict environment:
a dictionary containing the name and respective values to set
:raises:
`.SSHException` -- if any of the environment variables was rejected
by the server or the channel was closed
"""
for name, value in environment.items():
try:
self.set_environment_variable(name, value)
except SSHException as e:
err = 'Failed to set environment variable "{}".'
raise SSHException(err.format(name), e) | [
"def",
"update_environment",
"(",
"self",
",",
"environment",
")",
":",
"for",
"name",
",",
"value",
"in",
"environment",
".",
"items",
"(",
")",
":",
"try",
":",
"self",
".",
"set_environment_variable",
"(",
"name",
",",
"value",
")",
"except",
"SSHExcept... | Updates this channel's remote shell environment.
.. note::
This operation is additive - i.e. the current environment is not
reset before the given environment variables are set.
.. warning::
Servers may silently reject some environment variables; see the
warning in `set_environment_variable` for details.
:param dict environment:
a dictionary containing the name and respective values to set
:raises:
`.SSHException` -- if any of the environment variables was rejected
by the server or the channel was closed | [
"Updates",
"this",
"channel",
"s",
"remote",
"shell",
"environment",
"."
] | cf7d49d66f3b1fbc8b0853518a54050182b3b5eb | https://github.com/paramiko/paramiko/blob/cf7d49d66f3b1fbc8b0853518a54050182b3b5eb/paramiko/channel.py#L312-L335 |
32,332 | paramiko/paramiko | paramiko/channel.py | Channel.set_environment_variable | def set_environment_variable(self, name, value):
"""
Set the value of an environment variable.
.. warning::
The server may reject this request depending on its ``AcceptEnv``
setting; such rejections will fail silently (which is common client
practice for this particular request type). Make sure you
understand your server's configuration before using!
:param str name: name of the environment variable
:param str value: value of the environment variable
:raises:
`.SSHException` -- if the request was rejected or the channel was
closed
"""
m = Message()
m.add_byte(cMSG_CHANNEL_REQUEST)
m.add_int(self.remote_chanid)
m.add_string("env")
m.add_boolean(False)
m.add_string(name)
m.add_string(value)
self.transport._send_user_message(m) | python | def set_environment_variable(self, name, value):
"""
Set the value of an environment variable.
.. warning::
The server may reject this request depending on its ``AcceptEnv``
setting; such rejections will fail silently (which is common client
practice for this particular request type). Make sure you
understand your server's configuration before using!
:param str name: name of the environment variable
:param str value: value of the environment variable
:raises:
`.SSHException` -- if the request was rejected or the channel was
closed
"""
m = Message()
m.add_byte(cMSG_CHANNEL_REQUEST)
m.add_int(self.remote_chanid)
m.add_string("env")
m.add_boolean(False)
m.add_string(name)
m.add_string(value)
self.transport._send_user_message(m) | [
"def",
"set_environment_variable",
"(",
"self",
",",
"name",
",",
"value",
")",
":",
"m",
"=",
"Message",
"(",
")",
"m",
".",
"add_byte",
"(",
"cMSG_CHANNEL_REQUEST",
")",
"m",
".",
"add_int",
"(",
"self",
".",
"remote_chanid",
")",
"m",
".",
"add_string... | Set the value of an environment variable.
.. warning::
The server may reject this request depending on its ``AcceptEnv``
setting; such rejections will fail silently (which is common client
practice for this particular request type). Make sure you
understand your server's configuration before using!
:param str name: name of the environment variable
:param str value: value of the environment variable
:raises:
`.SSHException` -- if the request was rejected or the channel was
closed | [
"Set",
"the",
"value",
"of",
"an",
"environment",
"variable",
"."
] | cf7d49d66f3b1fbc8b0853518a54050182b3b5eb | https://github.com/paramiko/paramiko/blob/cf7d49d66f3b1fbc8b0853518a54050182b3b5eb/paramiko/channel.py#L338-L362 |
32,333 | paramiko/paramiko | paramiko/channel.py | Channel.recv_exit_status | def recv_exit_status(self):
"""
Return the exit status from the process on the server. This is
mostly useful for retrieving the results of an `exec_command`.
If the command hasn't finished yet, this method will wait until
it does, or until the channel is closed. If no exit status is
provided by the server, -1 is returned.
.. warning::
In some situations, receiving remote output larger than the current
`.Transport` or session's ``window_size`` (e.g. that set by the
``default_window_size`` kwarg for `.Transport.__init__`) will cause
`.recv_exit_status` to hang indefinitely if it is called prior to a
sufficiently large `.Channel.recv` (or if there are no threads
calling `.Channel.recv` in the background).
In these cases, ensuring that `.recv_exit_status` is called *after*
`.Channel.recv` (or, again, using threads) can avoid the hang.
:return: the exit code (as an `int`) of the process on the server.
.. versionadded:: 1.2
"""
self.status_event.wait()
assert self.status_event.is_set()
return self.exit_status | python | def recv_exit_status(self):
"""
Return the exit status from the process on the server. This is
mostly useful for retrieving the results of an `exec_command`.
If the command hasn't finished yet, this method will wait until
it does, or until the channel is closed. If no exit status is
provided by the server, -1 is returned.
.. warning::
In some situations, receiving remote output larger than the current
`.Transport` or session's ``window_size`` (e.g. that set by the
``default_window_size`` kwarg for `.Transport.__init__`) will cause
`.recv_exit_status` to hang indefinitely if it is called prior to a
sufficiently large `.Channel.recv` (or if there are no threads
calling `.Channel.recv` in the background).
In these cases, ensuring that `.recv_exit_status` is called *after*
`.Channel.recv` (or, again, using threads) can avoid the hang.
:return: the exit code (as an `int`) of the process on the server.
.. versionadded:: 1.2
"""
self.status_event.wait()
assert self.status_event.is_set()
return self.exit_status | [
"def",
"recv_exit_status",
"(",
"self",
")",
":",
"self",
".",
"status_event",
".",
"wait",
"(",
")",
"assert",
"self",
".",
"status_event",
".",
"is_set",
"(",
")",
"return",
"self",
".",
"exit_status"
] | Return the exit status from the process on the server. This is
mostly useful for retrieving the results of an `exec_command`.
If the command hasn't finished yet, this method will wait until
it does, or until the channel is closed. If no exit status is
provided by the server, -1 is returned.
.. warning::
In some situations, receiving remote output larger than the current
`.Transport` or session's ``window_size`` (e.g. that set by the
``default_window_size`` kwarg for `.Transport.__init__`) will cause
`.recv_exit_status` to hang indefinitely if it is called prior to a
sufficiently large `.Channel.recv` (or if there are no threads
calling `.Channel.recv` in the background).
In these cases, ensuring that `.recv_exit_status` is called *after*
`.Channel.recv` (or, again, using threads) can avoid the hang.
:return: the exit code (as an `int`) of the process on the server.
.. versionadded:: 1.2 | [
"Return",
"the",
"exit",
"status",
"from",
"the",
"process",
"on",
"the",
"server",
".",
"This",
"is",
"mostly",
"useful",
"for",
"retrieving",
"the",
"results",
"of",
"an",
"exec_command",
".",
"If",
"the",
"command",
"hasn",
"t",
"finished",
"yet",
"this... | cf7d49d66f3b1fbc8b0853518a54050182b3b5eb | https://github.com/paramiko/paramiko/blob/cf7d49d66f3b1fbc8b0853518a54050182b3b5eb/paramiko/channel.py#L379-L404 |
32,334 | paramiko/paramiko | paramiko/channel.py | Channel.request_x11 | def request_x11(
self,
screen_number=0,
auth_protocol=None,
auth_cookie=None,
single_connection=False,
handler=None,
):
"""
Request an x11 session on this channel. If the server allows it,
further x11 requests can be made from the server to the client,
when an x11 application is run in a shell session.
From :rfc:`4254`::
It is RECOMMENDED that the 'x11 authentication cookie' that is
sent be a fake, random cookie, and that the cookie be checked and
replaced by the real cookie when a connection request is received.
If you omit the auth_cookie, a new secure random 128-bit value will be
generated, used, and returned. You will need to use this value to
verify incoming x11 requests and replace them with the actual local
x11 cookie (which requires some knowledge of the x11 protocol).
If a handler is passed in, the handler is called from another thread
whenever a new x11 connection arrives. The default handler queues up
incoming x11 connections, which may be retrieved using
`.Transport.accept`. The handler's calling signature is::
handler(channel: Channel, (address: str, port: int))
:param int screen_number: the x11 screen number (0, 10, etc.)
:param str auth_protocol:
the name of the X11 authentication method used; if none is given,
``"MIT-MAGIC-COOKIE-1"`` is used
:param str auth_cookie:
hexadecimal string containing the x11 auth cookie; if none is
given, a secure random 128-bit value is generated
:param bool single_connection:
if True, only a single x11 connection will be forwarded (by
default, any number of x11 connections can arrive over this
session)
:param handler:
an optional callable handler to use for incoming X11 connections
:return: the auth_cookie used
"""
if auth_protocol is None:
auth_protocol = "MIT-MAGIC-COOKIE-1"
if auth_cookie is None:
auth_cookie = binascii.hexlify(os.urandom(16))
m = Message()
m.add_byte(cMSG_CHANNEL_REQUEST)
m.add_int(self.remote_chanid)
m.add_string("x11-req")
m.add_boolean(True)
m.add_boolean(single_connection)
m.add_string(auth_protocol)
m.add_string(auth_cookie)
m.add_int(screen_number)
self._event_pending()
self.transport._send_user_message(m)
self._wait_for_event()
self.transport._set_x11_handler(handler)
return auth_cookie | python | def request_x11(
self,
screen_number=0,
auth_protocol=None,
auth_cookie=None,
single_connection=False,
handler=None,
):
"""
Request an x11 session on this channel. If the server allows it,
further x11 requests can be made from the server to the client,
when an x11 application is run in a shell session.
From :rfc:`4254`::
It is RECOMMENDED that the 'x11 authentication cookie' that is
sent be a fake, random cookie, and that the cookie be checked and
replaced by the real cookie when a connection request is received.
If you omit the auth_cookie, a new secure random 128-bit value will be
generated, used, and returned. You will need to use this value to
verify incoming x11 requests and replace them with the actual local
x11 cookie (which requires some knowledge of the x11 protocol).
If a handler is passed in, the handler is called from another thread
whenever a new x11 connection arrives. The default handler queues up
incoming x11 connections, which may be retrieved using
`.Transport.accept`. The handler's calling signature is::
handler(channel: Channel, (address: str, port: int))
:param int screen_number: the x11 screen number (0, 10, etc.)
:param str auth_protocol:
the name of the X11 authentication method used; if none is given,
``"MIT-MAGIC-COOKIE-1"`` is used
:param str auth_cookie:
hexadecimal string containing the x11 auth cookie; if none is
given, a secure random 128-bit value is generated
:param bool single_connection:
if True, only a single x11 connection will be forwarded (by
default, any number of x11 connections can arrive over this
session)
:param handler:
an optional callable handler to use for incoming X11 connections
:return: the auth_cookie used
"""
if auth_protocol is None:
auth_protocol = "MIT-MAGIC-COOKIE-1"
if auth_cookie is None:
auth_cookie = binascii.hexlify(os.urandom(16))
m = Message()
m.add_byte(cMSG_CHANNEL_REQUEST)
m.add_int(self.remote_chanid)
m.add_string("x11-req")
m.add_boolean(True)
m.add_boolean(single_connection)
m.add_string(auth_protocol)
m.add_string(auth_cookie)
m.add_int(screen_number)
self._event_pending()
self.transport._send_user_message(m)
self._wait_for_event()
self.transport._set_x11_handler(handler)
return auth_cookie | [
"def",
"request_x11",
"(",
"self",
",",
"screen_number",
"=",
"0",
",",
"auth_protocol",
"=",
"None",
",",
"auth_cookie",
"=",
"None",
",",
"single_connection",
"=",
"False",
",",
"handler",
"=",
"None",
",",
")",
":",
"if",
"auth_protocol",
"is",
"None",
... | Request an x11 session on this channel. If the server allows it,
further x11 requests can be made from the server to the client,
when an x11 application is run in a shell session.
From :rfc:`4254`::
It is RECOMMENDED that the 'x11 authentication cookie' that is
sent be a fake, random cookie, and that the cookie be checked and
replaced by the real cookie when a connection request is received.
If you omit the auth_cookie, a new secure random 128-bit value will be
generated, used, and returned. You will need to use this value to
verify incoming x11 requests and replace them with the actual local
x11 cookie (which requires some knowledge of the x11 protocol).
If a handler is passed in, the handler is called from another thread
whenever a new x11 connection arrives. The default handler queues up
incoming x11 connections, which may be retrieved using
`.Transport.accept`. The handler's calling signature is::
handler(channel: Channel, (address: str, port: int))
:param int screen_number: the x11 screen number (0, 10, etc.)
:param str auth_protocol:
the name of the X11 authentication method used; if none is given,
``"MIT-MAGIC-COOKIE-1"`` is used
:param str auth_cookie:
hexadecimal string containing the x11 auth cookie; if none is
given, a secure random 128-bit value is generated
:param bool single_connection:
if True, only a single x11 connection will be forwarded (by
default, any number of x11 connections can arrive over this
session)
:param handler:
an optional callable handler to use for incoming X11 connections
:return: the auth_cookie used | [
"Request",
"an",
"x11",
"session",
"on",
"this",
"channel",
".",
"If",
"the",
"server",
"allows",
"it",
"further",
"x11",
"requests",
"can",
"be",
"made",
"from",
"the",
"server",
"to",
"the",
"client",
"when",
"an",
"x11",
"application",
"is",
"run",
"i... | cf7d49d66f3b1fbc8b0853518a54050182b3b5eb | https://github.com/paramiko/paramiko/blob/cf7d49d66f3b1fbc8b0853518a54050182b3b5eb/paramiko/channel.py#L428-L492 |
32,335 | paramiko/paramiko | paramiko/channel.py | Channel.set_combine_stderr | def set_combine_stderr(self, combine):
"""
Set whether stderr should be combined into stdout on this channel.
The default is ``False``, but in some cases it may be convenient to
have both streams combined.
If this is ``False``, and `exec_command` is called (or ``invoke_shell``
with no pty), output to stderr will not show up through the `recv`
and `recv_ready` calls. You will have to use `recv_stderr` and
`recv_stderr_ready` to get stderr output.
If this is ``True``, data will never show up via `recv_stderr` or
`recv_stderr_ready`.
:param bool combine:
``True`` if stderr output should be combined into stdout on this
channel.
:return: the previous setting (a `bool`).
.. versionadded:: 1.1
"""
data = bytes()
self.lock.acquire()
try:
old = self.combine_stderr
self.combine_stderr = combine
if combine and not old:
# copy old stderr buffer into primary buffer
data = self.in_stderr_buffer.empty()
finally:
self.lock.release()
if len(data) > 0:
self._feed(data)
return old | python | def set_combine_stderr(self, combine):
"""
Set whether stderr should be combined into stdout on this channel.
The default is ``False``, but in some cases it may be convenient to
have both streams combined.
If this is ``False``, and `exec_command` is called (or ``invoke_shell``
with no pty), output to stderr will not show up through the `recv`
and `recv_ready` calls. You will have to use `recv_stderr` and
`recv_stderr_ready` to get stderr output.
If this is ``True``, data will never show up via `recv_stderr` or
`recv_stderr_ready`.
:param bool combine:
``True`` if stderr output should be combined into stdout on this
channel.
:return: the previous setting (a `bool`).
.. versionadded:: 1.1
"""
data = bytes()
self.lock.acquire()
try:
old = self.combine_stderr
self.combine_stderr = combine
if combine and not old:
# copy old stderr buffer into primary buffer
data = self.in_stderr_buffer.empty()
finally:
self.lock.release()
if len(data) > 0:
self._feed(data)
return old | [
"def",
"set_combine_stderr",
"(",
"self",
",",
"combine",
")",
":",
"data",
"=",
"bytes",
"(",
")",
"self",
".",
"lock",
".",
"acquire",
"(",
")",
"try",
":",
"old",
"=",
"self",
".",
"combine_stderr",
"self",
".",
"combine_stderr",
"=",
"combine",
"if... | Set whether stderr should be combined into stdout on this channel.
The default is ``False``, but in some cases it may be convenient to
have both streams combined.
If this is ``False``, and `exec_command` is called (or ``invoke_shell``
with no pty), output to stderr will not show up through the `recv`
and `recv_ready` calls. You will have to use `recv_stderr` and
`recv_stderr_ready` to get stderr output.
If this is ``True``, data will never show up via `recv_stderr` or
`recv_stderr_ready`.
:param bool combine:
``True`` if stderr output should be combined into stdout on this
channel.
:return: the previous setting (a `bool`).
.. versionadded:: 1.1 | [
"Set",
"whether",
"stderr",
"should",
"be",
"combined",
"into",
"stdout",
"on",
"this",
"channel",
".",
"The",
"default",
"is",
"False",
"but",
"in",
"some",
"cases",
"it",
"may",
"be",
"convenient",
"to",
"have",
"both",
"streams",
"combined",
"."
] | cf7d49d66f3b1fbc8b0853518a54050182b3b5eb | https://github.com/paramiko/paramiko/blob/cf7d49d66f3b1fbc8b0853518a54050182b3b5eb/paramiko/channel.py#L551-L584 |
32,336 | paramiko/paramiko | paramiko/channel.py | Channel.sendall | def sendall(self, s):
"""
Send data to the channel, without allowing partial results. Unlike
`send`, this method continues to send data from the given string until
either all data has been sent or an error occurs. Nothing is returned.
:param str s: data to send.
:raises socket.timeout:
if sending stalled for longer than the timeout set by `settimeout`.
:raises socket.error:
if an error occurred before the entire string was sent.
.. note::
If the channel is closed while only part of the data has been
sent, there is no way to determine how much data (if any) was sent.
This is irritating, but identically follows Python's API.
"""
while s:
sent = self.send(s)
s = s[sent:]
return None | python | def sendall(self, s):
"""
Send data to the channel, without allowing partial results. Unlike
`send`, this method continues to send data from the given string until
either all data has been sent or an error occurs. Nothing is returned.
:param str s: data to send.
:raises socket.timeout:
if sending stalled for longer than the timeout set by `settimeout`.
:raises socket.error:
if an error occurred before the entire string was sent.
.. note::
If the channel is closed while only part of the data has been
sent, there is no way to determine how much data (if any) was sent.
This is irritating, but identically follows Python's API.
"""
while s:
sent = self.send(s)
s = s[sent:]
return None | [
"def",
"sendall",
"(",
"self",
",",
"s",
")",
":",
"while",
"s",
":",
"sent",
"=",
"self",
".",
"send",
"(",
"s",
")",
"s",
"=",
"s",
"[",
"sent",
":",
"]",
"return",
"None"
] | Send data to the channel, without allowing partial results. Unlike
`send`, this method continues to send data from the given string until
either all data has been sent or an error occurs. Nothing is returned.
:param str s: data to send.
:raises socket.timeout:
if sending stalled for longer than the timeout set by `settimeout`.
:raises socket.error:
if an error occurred before the entire string was sent.
.. note::
If the channel is closed while only part of the data has been
sent, there is no way to determine how much data (if any) was sent.
This is irritating, but identically follows Python's API. | [
"Send",
"data",
"to",
"the",
"channel",
"without",
"allowing",
"partial",
"results",
".",
"Unlike",
"send",
"this",
"method",
"continues",
"to",
"send",
"data",
"from",
"the",
"given",
"string",
"until",
"either",
"all",
"data",
"has",
"been",
"sent",
"or",
... | cf7d49d66f3b1fbc8b0853518a54050182b3b5eb | https://github.com/paramiko/paramiko/blob/cf7d49d66f3b1fbc8b0853518a54050182b3b5eb/paramiko/channel.py#L827-L848 |
32,337 | paramiko/paramiko | paramiko/channel.py | Channel.sendall_stderr | def sendall_stderr(self, s):
"""
Send data to the channel's "stderr" stream, without allowing partial
results. Unlike `send_stderr`, this method continues to send data
from the given string until all data has been sent or an error occurs.
Nothing is returned.
:param str s: data to send to the client as "stderr" output.
:raises socket.timeout:
if sending stalled for longer than the timeout set by `settimeout`.
:raises socket.error:
if an error occurred before the entire string was sent.
.. versionadded:: 1.1
"""
while s:
sent = self.send_stderr(s)
s = s[sent:]
return None | python | def sendall_stderr(self, s):
"""
Send data to the channel's "stderr" stream, without allowing partial
results. Unlike `send_stderr`, this method continues to send data
from the given string until all data has been sent or an error occurs.
Nothing is returned.
:param str s: data to send to the client as "stderr" output.
:raises socket.timeout:
if sending stalled for longer than the timeout set by `settimeout`.
:raises socket.error:
if an error occurred before the entire string was sent.
.. versionadded:: 1.1
"""
while s:
sent = self.send_stderr(s)
s = s[sent:]
return None | [
"def",
"sendall_stderr",
"(",
"self",
",",
"s",
")",
":",
"while",
"s",
":",
"sent",
"=",
"self",
".",
"send_stderr",
"(",
"s",
")",
"s",
"=",
"s",
"[",
"sent",
":",
"]",
"return",
"None"
] | Send data to the channel's "stderr" stream, without allowing partial
results. Unlike `send_stderr`, this method continues to send data
from the given string until all data has been sent or an error occurs.
Nothing is returned.
:param str s: data to send to the client as "stderr" output.
:raises socket.timeout:
if sending stalled for longer than the timeout set by `settimeout`.
:raises socket.error:
if an error occurred before the entire string was sent.
.. versionadded:: 1.1 | [
"Send",
"data",
"to",
"the",
"channel",
"s",
"stderr",
"stream",
"without",
"allowing",
"partial",
"results",
".",
"Unlike",
"send_stderr",
"this",
"method",
"continues",
"to",
"send",
"data",
"from",
"the",
"given",
"string",
"until",
"all",
"data",
"has",
... | cf7d49d66f3b1fbc8b0853518a54050182b3b5eb | https://github.com/paramiko/paramiko/blob/cf7d49d66f3b1fbc8b0853518a54050182b3b5eb/paramiko/channel.py#L850-L869 |
32,338 | paramiko/paramiko | paramiko/channel.py | Channel.fileno | def fileno(self):
"""
Returns an OS-level file descriptor which can be used for polling, but
but not for reading or writing. This is primarily to allow Python's
``select`` module to work.
The first time ``fileno`` is called on a channel, a pipe is created to
simulate real OS-level file descriptor (FD) behavior. Because of this,
two OS-level FDs are created, which will use up FDs faster than normal.
(You won't notice this effect unless you have hundreds of channels
open at the same time.)
:return: an OS-level file descriptor (`int`)
.. warning::
This method causes channel reads to be slightly less efficient.
"""
self.lock.acquire()
try:
if self._pipe is not None:
return self._pipe.fileno()
# create the pipe and feed in any existing data
self._pipe = pipe.make_pipe()
p1, p2 = pipe.make_or_pipe(self._pipe)
self.in_buffer.set_event(p1)
self.in_stderr_buffer.set_event(p2)
return self._pipe.fileno()
finally:
self.lock.release() | python | def fileno(self):
"""
Returns an OS-level file descriptor which can be used for polling, but
but not for reading or writing. This is primarily to allow Python's
``select`` module to work.
The first time ``fileno`` is called on a channel, a pipe is created to
simulate real OS-level file descriptor (FD) behavior. Because of this,
two OS-level FDs are created, which will use up FDs faster than normal.
(You won't notice this effect unless you have hundreds of channels
open at the same time.)
:return: an OS-level file descriptor (`int`)
.. warning::
This method causes channel reads to be slightly less efficient.
"""
self.lock.acquire()
try:
if self._pipe is not None:
return self._pipe.fileno()
# create the pipe and feed in any existing data
self._pipe = pipe.make_pipe()
p1, p2 = pipe.make_or_pipe(self._pipe)
self.in_buffer.set_event(p1)
self.in_stderr_buffer.set_event(p2)
return self._pipe.fileno()
finally:
self.lock.release() | [
"def",
"fileno",
"(",
"self",
")",
":",
"self",
".",
"lock",
".",
"acquire",
"(",
")",
"try",
":",
"if",
"self",
".",
"_pipe",
"is",
"not",
"None",
":",
"return",
"self",
".",
"_pipe",
".",
"fileno",
"(",
")",
"# create the pipe and feed in any existing ... | Returns an OS-level file descriptor which can be used for polling, but
but not for reading or writing. This is primarily to allow Python's
``select`` module to work.
The first time ``fileno`` is called on a channel, a pipe is created to
simulate real OS-level file descriptor (FD) behavior. Because of this,
two OS-level FDs are created, which will use up FDs faster than normal.
(You won't notice this effect unless you have hundreds of channels
open at the same time.)
:return: an OS-level file descriptor (`int`)
.. warning::
This method causes channel reads to be slightly less efficient. | [
"Returns",
"an",
"OS",
"-",
"level",
"file",
"descriptor",
"which",
"can",
"be",
"used",
"for",
"polling",
"but",
"but",
"not",
"for",
"reading",
"or",
"writing",
".",
"This",
"is",
"primarily",
"to",
"allow",
"Python",
"s",
"select",
"module",
"to",
"wo... | cf7d49d66f3b1fbc8b0853518a54050182b3b5eb | https://github.com/paramiko/paramiko/blob/cf7d49d66f3b1fbc8b0853518a54050182b3b5eb/paramiko/channel.py#L898-L926 |
32,339 | paramiko/paramiko | paramiko/channel.py | Channel.shutdown | def shutdown(self, how):
"""
Shut down one or both halves of the connection. If ``how`` is 0,
further receives are disallowed. If ``how`` is 1, further sends
are disallowed. If ``how`` is 2, further sends and receives are
disallowed. This closes the stream in one or both directions.
:param int how:
0 (stop receiving), 1 (stop sending), or 2 (stop receiving and
sending).
"""
if (how == 0) or (how == 2):
# feign "read" shutdown
self.eof_received = 1
if (how == 1) or (how == 2):
self.lock.acquire()
try:
m = self._send_eof()
finally:
self.lock.release()
if m is not None:
self.transport._send_user_message(m) | python | def shutdown(self, how):
"""
Shut down one or both halves of the connection. If ``how`` is 0,
further receives are disallowed. If ``how`` is 1, further sends
are disallowed. If ``how`` is 2, further sends and receives are
disallowed. This closes the stream in one or both directions.
:param int how:
0 (stop receiving), 1 (stop sending), or 2 (stop receiving and
sending).
"""
if (how == 0) or (how == 2):
# feign "read" shutdown
self.eof_received = 1
if (how == 1) or (how == 2):
self.lock.acquire()
try:
m = self._send_eof()
finally:
self.lock.release()
if m is not None:
self.transport._send_user_message(m) | [
"def",
"shutdown",
"(",
"self",
",",
"how",
")",
":",
"if",
"(",
"how",
"==",
"0",
")",
"or",
"(",
"how",
"==",
"2",
")",
":",
"# feign \"read\" shutdown",
"self",
".",
"eof_received",
"=",
"1",
"if",
"(",
"how",
"==",
"1",
")",
"or",
"(",
"how",... | Shut down one or both halves of the connection. If ``how`` is 0,
further receives are disallowed. If ``how`` is 1, further sends
are disallowed. If ``how`` is 2, further sends and receives are
disallowed. This closes the stream in one or both directions.
:param int how:
0 (stop receiving), 1 (stop sending), or 2 (stop receiving and
sending). | [
"Shut",
"down",
"one",
"or",
"both",
"halves",
"of",
"the",
"connection",
".",
"If",
"how",
"is",
"0",
"further",
"receives",
"are",
"disallowed",
".",
"If",
"how",
"is",
"1",
"further",
"sends",
"are",
"disallowed",
".",
"If",
"how",
"is",
"2",
"furth... | cf7d49d66f3b1fbc8b0853518a54050182b3b5eb | https://github.com/paramiko/paramiko/blob/cf7d49d66f3b1fbc8b0853518a54050182b3b5eb/paramiko/channel.py#L928-L949 |
32,340 | 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",
".",
... | 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... | cf7d49d66f3b1fbc8b0853518a54050182b3b5eb | https://github.com/paramiko/paramiko/blob/cf7d49d66f3b1fbc8b0853518a54050182b3b5eb/paramiko/buffered_pipe.py#L108-L124 |
32,341 | 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",
... | 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",
... | cf7d49d66f3b1fbc8b0853518a54050182b3b5eb | https://github.com/paramiko/paramiko/blob/cf7d49d66f3b1fbc8b0853518a54050182b3b5eb/paramiko/buffered_pipe.py#L126-L178 |
32,342 | 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",
... | 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 |
32,343 | 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",... | 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 |
32,344 | 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 |
32,345 | 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 |
32,346 | 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 |
32,347 | 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... | cf7d49d66f3b1fbc8b0853518a54050182b3b5eb | https://github.com/paramiko/paramiko/blob/cf7d49d66f3b1fbc8b0853518a54050182b3b5eb/paramiko/server.py#L269-L299 |
32,348 | 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... | 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 |
32,349 | 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",
".... | 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 |
32,350 | 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",
... | 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 |
32,351 | 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",
... | 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 |
32,352 | 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",
",",... | 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 |
32,353 | 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",
":",
"# serve... | 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 |
32,354 | 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",
")",... | 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 |
32,355 | 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",
... | 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 |
32,356 | 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(... | 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 |
32,357 | 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",
",",
"\"p... | 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 |
32,358 | 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",
")",
")",
"s... | 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 |
32,359 | 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",
")",
")",
"att... | 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 |
32,360 | 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",
... | 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 |
32,361 | 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 |
32,362 | 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",
".",
"r... | 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 |
32,363 | 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",
".",
"... | 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 |
32,364 | 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_pack... | 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 |
32,365 | 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"... | 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 |
32,366 | 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",
".",
... | 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 |
32,367 | 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_del... | 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",... | cf7d49d66f3b1fbc8b0853518a54050182b3b5eb | https://github.com/paramiko/paramiko/blob/cf7d49d66f3b1fbc8b0853518a54050182b3b5eb/paramiko/transport.py#L1149-L1265 |
32,368 | 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... | 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 |
32,369 | 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 w... | 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 |
32,370 | 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 authentica... | 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 |
32,371 | 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_... | you are holding the lock | [
"you",
"are",
"holding",
"the",
"lock"
] | cf7d49d66f3b1fbc8b0853518a54050182b3b5eb | https://github.com/paramiko/paramiko/blob/cf7d49d66f3b1fbc8b0853518a54050182b3b5eb/paramiko/transport.py#L1752-L1759 |
32,372 | 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",
"# ... | 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 |
32,373 | 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_ciphe... | 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 |
32,374 | 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",
... | 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",
... | cf7d49d66f3b1fbc8b0853518a54050182b3b5eb | https://github.com/paramiko/paramiko/blob/cf7d49d66f3b1fbc8b0853518a54050182b3b5eb/paramiko/hostkeys.py#L127-L191 |
32,375 | 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",
".",
"s... | 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 |
32,376 | 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",
"=",
"\"Page... | 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 |
32,377 | 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",
... | cf7d49d66f3b1fbc8b0853518a54050182b3b5eb | https://github.com/paramiko/paramiko/blob/cf7d49d66f3b1fbc8b0853518a54050182b3b5eb/paramiko/message.py#L91-L99 |
32,378 | 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 |
32,379 | 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 |
32,380 | 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_... | 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 |
32,381 | 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",... | 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 |
32,382 | 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 |
32,383 | 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",
... | 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 |
32,384 | 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 |
32,385 | 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",... | cf7d49d66f3b1fbc8b0853518a54050182b3b5eb | https://github.com/paramiko/paramiko/blob/cf7d49d66f3b1fbc8b0853518a54050182b3b5eb/paramiko/pipe.py#L138-L148 |
32,386 | 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",
"(",
")",
... | 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 |
32,387 | 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",
"No... | 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 |
32,388 | 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",
")... | 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 |
32,389 | 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"... | Switch outbound data cipher. | [
"Switch",
"outbound",
"data",
"cipher",
"."
] | cf7d49d66f3b1fbc8b0853518a54050182b3b5eb | https://github.com/paramiko/paramiko/blob/cf7d49d66f3b1fbc8b0853518a54050182b3b5eb/paramiko/packet.py#L137-L162 |
32,390 | paramiko/paramiko | paramiko/packet.py | Packetizer.set_inbound_cipher | def set_inbound_cipher(
self, block_engine, block_size, mac_engine, mac_size, mac_key
):
"""
Switch inbound data cipher.
"""
self.__block_engine_in = block_engine
self.__block_size_in = block_size
self.__mac_engine_in = mac_engine
self.__mac_size_in = mac_size
self.__mac_key_in = mac_key
self.__received_bytes = 0
self.__received_packets = 0
self.__received_bytes_overflow = 0
self.__received_packets_overflow = 0
# wait until the reset happens in both directions before clearing
# rekey flag
self.__init_count |= 2
if self.__init_count == 3:
self.__init_count = 0
self.__need_rekey = False | python | def set_inbound_cipher(
self, block_engine, block_size, mac_engine, mac_size, mac_key
):
"""
Switch inbound data cipher.
"""
self.__block_engine_in = block_engine
self.__block_size_in = block_size
self.__mac_engine_in = mac_engine
self.__mac_size_in = mac_size
self.__mac_key_in = mac_key
self.__received_bytes = 0
self.__received_packets = 0
self.__received_bytes_overflow = 0
self.__received_packets_overflow = 0
# wait until the reset happens in both directions before clearing
# rekey flag
self.__init_count |= 2
if self.__init_count == 3:
self.__init_count = 0
self.__need_rekey = False | [
"def",
"set_inbound_cipher",
"(",
"self",
",",
"block_engine",
",",
"block_size",
",",
"mac_engine",
",",
"mac_size",
",",
"mac_key",
")",
":",
"self",
".",
"__block_engine_in",
"=",
"block_engine",
"self",
".",
"__block_size_in",
"=",
"block_size",
"self",
".",... | Switch inbound data cipher. | [
"Switch",
"inbound",
"data",
"cipher",
"."
] | cf7d49d66f3b1fbc8b0853518a54050182b3b5eb | https://github.com/paramiko/paramiko/blob/cf7d49d66f3b1fbc8b0853518a54050182b3b5eb/paramiko/packet.py#L164-L184 |
32,391 | paramiko/paramiko | paramiko/packet.py | Packetizer.start_handshake | def start_handshake(self, timeout):
"""
Tells `Packetizer` that the handshake process started.
Starts a book keeping timer that can signal a timeout in the
handshake process.
:param float timeout: amount of seconds to wait before timing out
"""
if not self.__timer:
self.__timer = threading.Timer(float(timeout), self.read_timer)
self.__timer.start() | python | def start_handshake(self, timeout):
"""
Tells `Packetizer` that the handshake process started.
Starts a book keeping timer that can signal a timeout in the
handshake process.
:param float timeout: amount of seconds to wait before timing out
"""
if not self.__timer:
self.__timer = threading.Timer(float(timeout), self.read_timer)
self.__timer.start() | [
"def",
"start_handshake",
"(",
"self",
",",
"timeout",
")",
":",
"if",
"not",
"self",
".",
"__timer",
":",
"self",
".",
"__timer",
"=",
"threading",
".",
"Timer",
"(",
"float",
"(",
"timeout",
")",
",",
"self",
".",
"read_timer",
")",
"self",
".",
"_... | Tells `Packetizer` that the handshake process started.
Starts a book keeping timer that can signal a timeout in the
handshake process.
:param float timeout: amount of seconds to wait before timing out | [
"Tells",
"Packetizer",
"that",
"the",
"handshake",
"process",
"started",
".",
"Starts",
"a",
"book",
"keeping",
"timer",
"that",
"can",
"signal",
"a",
"timeout",
"in",
"the",
"handshake",
"process",
"."
] | cf7d49d66f3b1fbc8b0853518a54050182b3b5eb | https://github.com/paramiko/paramiko/blob/cf7d49d66f3b1fbc8b0853518a54050182b3b5eb/paramiko/packet.py#L229-L239 |
32,392 | paramiko/paramiko | paramiko/packet.py | Packetizer.handshake_timed_out | def handshake_timed_out(self):
"""
Checks if the handshake has timed out.
If `start_handshake` wasn't called before the call to this function,
the return value will always be `False`. If the handshake completed
before a timeout was reached, the return value will be `False`
:return: handshake time out status, as a `bool`
"""
if not self.__timer:
return False
if self.__handshake_complete:
return False
return self.__timer_expired | python | def handshake_timed_out(self):
"""
Checks if the handshake has timed out.
If `start_handshake` wasn't called before the call to this function,
the return value will always be `False`. If the handshake completed
before a timeout was reached, the return value will be `False`
:return: handshake time out status, as a `bool`
"""
if not self.__timer:
return False
if self.__handshake_complete:
return False
return self.__timer_expired | [
"def",
"handshake_timed_out",
"(",
"self",
")",
":",
"if",
"not",
"self",
".",
"__timer",
":",
"return",
"False",
"if",
"self",
".",
"__handshake_complete",
":",
"return",
"False",
"return",
"self",
".",
"__timer_expired"
] | Checks if the handshake has timed out.
If `start_handshake` wasn't called before the call to this function,
the return value will always be `False`. If the handshake completed
before a timeout was reached, the return value will be `False`
:return: handshake time out status, as a `bool` | [
"Checks",
"if",
"the",
"handshake",
"has",
"timed",
"out",
"."
] | cf7d49d66f3b1fbc8b0853518a54050182b3b5eb | https://github.com/paramiko/paramiko/blob/cf7d49d66f3b1fbc8b0853518a54050182b3b5eb/paramiko/packet.py#L241-L255 |
32,393 | paramiko/paramiko | paramiko/packet.py | Packetizer.complete_handshake | def complete_handshake(self):
"""
Tells `Packetizer` that the handshake has completed.
"""
if self.__timer:
self.__timer.cancel()
self.__timer_expired = False
self.__handshake_complete = True | python | def complete_handshake(self):
"""
Tells `Packetizer` that the handshake has completed.
"""
if self.__timer:
self.__timer.cancel()
self.__timer_expired = False
self.__handshake_complete = True | [
"def",
"complete_handshake",
"(",
"self",
")",
":",
"if",
"self",
".",
"__timer",
":",
"self",
".",
"__timer",
".",
"cancel",
"(",
")",
"self",
".",
"__timer_expired",
"=",
"False",
"self",
".",
"__handshake_complete",
"=",
"True"
] | Tells `Packetizer` that the handshake has completed. | [
"Tells",
"Packetizer",
"that",
"the",
"handshake",
"has",
"completed",
"."
] | cf7d49d66f3b1fbc8b0853518a54050182b3b5eb | https://github.com/paramiko/paramiko/blob/cf7d49d66f3b1fbc8b0853518a54050182b3b5eb/paramiko/packet.py#L257-L264 |
32,394 | paramiko/paramiko | paramiko/sftp_handle.py | SFTPHandle._get_next_files | def _get_next_files(self):
"""
Used by the SFTP server code to retrieve a cached directory
listing.
"""
fnlist = self.__files[:16]
self.__files = self.__files[16:]
return fnlist | python | def _get_next_files(self):
"""
Used by the SFTP server code to retrieve a cached directory
listing.
"""
fnlist = self.__files[:16]
self.__files = self.__files[16:]
return fnlist | [
"def",
"_get_next_files",
"(",
"self",
")",
":",
"fnlist",
"=",
"self",
".",
"__files",
"[",
":",
"16",
"]",
"self",
".",
"__files",
"=",
"self",
".",
"__files",
"[",
"16",
":",
"]",
"return",
"fnlist"
] | Used by the SFTP server code to retrieve a cached directory
listing. | [
"Used",
"by",
"the",
"SFTP",
"server",
"code",
"to",
"retrieve",
"a",
"cached",
"directory",
"listing",
"."
] | cf7d49d66f3b1fbc8b0853518a54050182b3b5eb | https://github.com/paramiko/paramiko/blob/cf7d49d66f3b1fbc8b0853518a54050182b3b5eb/paramiko/sftp_handle.py#L180-L187 |
32,395 | paramiko/paramiko | paramiko/proxy.py | ProxyCommand.send | def send(self, content):
"""
Write the content received from the SSH client to the standard
input of the forked command.
:param str content: string to be sent to the forked command
"""
try:
self.process.stdin.write(content)
except IOError as e:
# There was a problem with the child process. It probably
# died and we can't proceed. The best option here is to
# raise an exception informing the user that the informed
# ProxyCommand is not working.
raise ProxyCommandFailure(" ".join(self.cmd), e.strerror)
return len(content) | python | def send(self, content):
"""
Write the content received from the SSH client to the standard
input of the forked command.
:param str content: string to be sent to the forked command
"""
try:
self.process.stdin.write(content)
except IOError as e:
# There was a problem with the child process. It probably
# died and we can't proceed. The best option here is to
# raise an exception informing the user that the informed
# ProxyCommand is not working.
raise ProxyCommandFailure(" ".join(self.cmd), e.strerror)
return len(content) | [
"def",
"send",
"(",
"self",
",",
"content",
")",
":",
"try",
":",
"self",
".",
"process",
".",
"stdin",
".",
"write",
"(",
"content",
")",
"except",
"IOError",
"as",
"e",
":",
"# There was a problem with the child process. It probably",
"# died and we can't procee... | Write the content received from the SSH client to the standard
input of the forked command.
:param str content: string to be sent to the forked command | [
"Write",
"the",
"content",
"received",
"from",
"the",
"SSH",
"client",
"to",
"the",
"standard",
"input",
"of",
"the",
"forked",
"command",
"."
] | cf7d49d66f3b1fbc8b0853518a54050182b3b5eb | https://github.com/paramiko/paramiko/blob/cf7d49d66f3b1fbc8b0853518a54050182b3b5eb/paramiko/proxy.py#L61-L76 |
32,396 | paramiko/paramiko | paramiko/_winapi.py | GetTokenInformation | def GetTokenInformation(token, information_class):
"""
Given a token, get the token information for it.
"""
data_size = ctypes.wintypes.DWORD()
ctypes.windll.advapi32.GetTokenInformation(
token, information_class.num, 0, 0, ctypes.byref(data_size)
)
data = ctypes.create_string_buffer(data_size.value)
handle_nonzero_success(
ctypes.windll.advapi32.GetTokenInformation(
token,
information_class.num,
ctypes.byref(data),
ctypes.sizeof(data),
ctypes.byref(data_size),
)
)
return ctypes.cast(data, ctypes.POINTER(TOKEN_USER)).contents | python | def GetTokenInformation(token, information_class):
"""
Given a token, get the token information for it.
"""
data_size = ctypes.wintypes.DWORD()
ctypes.windll.advapi32.GetTokenInformation(
token, information_class.num, 0, 0, ctypes.byref(data_size)
)
data = ctypes.create_string_buffer(data_size.value)
handle_nonzero_success(
ctypes.windll.advapi32.GetTokenInformation(
token,
information_class.num,
ctypes.byref(data),
ctypes.sizeof(data),
ctypes.byref(data_size),
)
)
return ctypes.cast(data, ctypes.POINTER(TOKEN_USER)).contents | [
"def",
"GetTokenInformation",
"(",
"token",
",",
"information_class",
")",
":",
"data_size",
"=",
"ctypes",
".",
"wintypes",
".",
"DWORD",
"(",
")",
"ctypes",
".",
"windll",
".",
"advapi32",
".",
"GetTokenInformation",
"(",
"token",
",",
"information_class",
"... | Given a token, get the token information for it. | [
"Given",
"a",
"token",
"get",
"the",
"token",
"information",
"for",
"it",
"."
] | cf7d49d66f3b1fbc8b0853518a54050182b3b5eb | https://github.com/paramiko/paramiko/blob/cf7d49d66f3b1fbc8b0853518a54050182b3b5eb/paramiko/_winapi.py#L351-L369 |
32,397 | paramiko/paramiko | paramiko/_winapi.py | get_current_user | def get_current_user():
"""
Return a TOKEN_USER for the owner of this process.
"""
process = OpenProcessToken(
ctypes.windll.kernel32.GetCurrentProcess(), TokenAccess.TOKEN_QUERY
)
return GetTokenInformation(process, TOKEN_USER) | python | def get_current_user():
"""
Return a TOKEN_USER for the owner of this process.
"""
process = OpenProcessToken(
ctypes.windll.kernel32.GetCurrentProcess(), TokenAccess.TOKEN_QUERY
)
return GetTokenInformation(process, TOKEN_USER) | [
"def",
"get_current_user",
"(",
")",
":",
"process",
"=",
"OpenProcessToken",
"(",
"ctypes",
".",
"windll",
".",
"kernel32",
".",
"GetCurrentProcess",
"(",
")",
",",
"TokenAccess",
".",
"TOKEN_QUERY",
")",
"return",
"GetTokenInformation",
"(",
"process",
",",
... | Return a TOKEN_USER for the owner of this process. | [
"Return",
"a",
"TOKEN_USER",
"for",
"the",
"owner",
"of",
"this",
"process",
"."
] | cf7d49d66f3b1fbc8b0853518a54050182b3b5eb | https://github.com/paramiko/paramiko/blob/cf7d49d66f3b1fbc8b0853518a54050182b3b5eb/paramiko/_winapi.py#L383-L390 |
32,398 | paramiko/paramiko | paramiko/client.py | SSHClient.set_missing_host_key_policy | def set_missing_host_key_policy(self, policy):
"""
Set policy to use when connecting to servers without a known host key.
Specifically:
* A **policy** is a "policy class" (or instance thereof), namely some
subclass of `.MissingHostKeyPolicy` such as `.RejectPolicy` (the
default), `.AutoAddPolicy`, `.WarningPolicy`, or a user-created
subclass.
* A host key is **known** when it appears in the client object's cached
host keys structures (those manipulated by `load_system_host_keys`
and/or `load_host_keys`).
:param .MissingHostKeyPolicy policy:
the policy to use when receiving a host key from a
previously-unknown server
"""
if inspect.isclass(policy):
policy = policy()
self._policy = policy | python | def set_missing_host_key_policy(self, policy):
"""
Set policy to use when connecting to servers without a known host key.
Specifically:
* A **policy** is a "policy class" (or instance thereof), namely some
subclass of `.MissingHostKeyPolicy` such as `.RejectPolicy` (the
default), `.AutoAddPolicy`, `.WarningPolicy`, or a user-created
subclass.
* A host key is **known** when it appears in the client object's cached
host keys structures (those manipulated by `load_system_host_keys`
and/or `load_host_keys`).
:param .MissingHostKeyPolicy policy:
the policy to use when receiving a host key from a
previously-unknown server
"""
if inspect.isclass(policy):
policy = policy()
self._policy = policy | [
"def",
"set_missing_host_key_policy",
"(",
"self",
",",
"policy",
")",
":",
"if",
"inspect",
".",
"isclass",
"(",
"policy",
")",
":",
"policy",
"=",
"policy",
"(",
")",
"self",
".",
"_policy",
"=",
"policy"
] | Set policy to use when connecting to servers without a known host key.
Specifically:
* A **policy** is a "policy class" (or instance thereof), namely some
subclass of `.MissingHostKeyPolicy` such as `.RejectPolicy` (the
default), `.AutoAddPolicy`, `.WarningPolicy`, or a user-created
subclass.
* A host key is **known** when it appears in the client object's cached
host keys structures (those manipulated by `load_system_host_keys`
and/or `load_host_keys`).
:param .MissingHostKeyPolicy policy:
the policy to use when receiving a host key from a
previously-unknown server | [
"Set",
"policy",
"to",
"use",
"when",
"connecting",
"to",
"servers",
"without",
"a",
"known",
"host",
"key",
"."
] | cf7d49d66f3b1fbc8b0853518a54050182b3b5eb | https://github.com/paramiko/paramiko/blob/cf7d49d66f3b1fbc8b0853518a54050182b3b5eb/paramiko/client.py#L172-L192 |
32,399 | paramiko/paramiko | paramiko/client.py | SSHClient._families_and_addresses | def _families_and_addresses(self, hostname, port):
"""
Yield pairs of address families and addresses to try for connecting.
:param str hostname: the server to connect to
:param int port: the server port to connect to
:returns: Yields an iterable of ``(family, address)`` tuples
"""
guess = True
addrinfos = socket.getaddrinfo(
hostname, port, socket.AF_UNSPEC, socket.SOCK_STREAM
)
for (family, socktype, proto, canonname, sockaddr) in addrinfos:
if socktype == socket.SOCK_STREAM:
yield family, sockaddr
guess = False
# some OS like AIX don't indicate SOCK_STREAM support, so just
# guess. :( We only do this if we did not get a single result marked
# as socktype == SOCK_STREAM.
if guess:
for family, _, _, _, sockaddr in addrinfos:
yield family, sockaddr | python | def _families_and_addresses(self, hostname, port):
"""
Yield pairs of address families and addresses to try for connecting.
:param str hostname: the server to connect to
:param int port: the server port to connect to
:returns: Yields an iterable of ``(family, address)`` tuples
"""
guess = True
addrinfos = socket.getaddrinfo(
hostname, port, socket.AF_UNSPEC, socket.SOCK_STREAM
)
for (family, socktype, proto, canonname, sockaddr) in addrinfos:
if socktype == socket.SOCK_STREAM:
yield family, sockaddr
guess = False
# some OS like AIX don't indicate SOCK_STREAM support, so just
# guess. :( We only do this if we did not get a single result marked
# as socktype == SOCK_STREAM.
if guess:
for family, _, _, _, sockaddr in addrinfos:
yield family, sockaddr | [
"def",
"_families_and_addresses",
"(",
"self",
",",
"hostname",
",",
"port",
")",
":",
"guess",
"=",
"True",
"addrinfos",
"=",
"socket",
".",
"getaddrinfo",
"(",
"hostname",
",",
"port",
",",
"socket",
".",
"AF_UNSPEC",
",",
"socket",
".",
"SOCK_STREAM",
"... | Yield pairs of address families and addresses to try for connecting.
:param str hostname: the server to connect to
:param int port: the server port to connect to
:returns: Yields an iterable of ``(family, address)`` tuples | [
"Yield",
"pairs",
"of",
"address",
"families",
"and",
"addresses",
"to",
"try",
"for",
"connecting",
"."
] | cf7d49d66f3b1fbc8b0853518a54050182b3b5eb | https://github.com/paramiko/paramiko/blob/cf7d49d66f3b1fbc8b0853518a54050182b3b5eb/paramiko/client.py#L194-L216 |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.