Skip to content

Commit

Permalink
Adds _marker attribute to HostKeyEntry
Browse files Browse the repository at this point in the history
* Adds some type annotations
* Includes _marker in the output of `to_line`
* Sets _marker when constructing `HostKeyEntry` in `from_line`
  • Loading branch information
MajorDallas committed Dec 17, 2023
1 parent 34299ff commit e908acc
Showing 1 changed file with 21 additions and 6 deletions.
27 changes: 21 additions & 6 deletions paramiko/hostkeys.py
Original file line number Diff line number Diff line change
Expand Up @@ -19,6 +19,7 @@

from base64 import encodebytes, decodebytes
from enum import Enum
from typing import Iterable, Optional
import binascii
import os
import re
Expand Down Expand Up @@ -177,9 +178,7 @@ def __setitem__(self, key, val):

def keys(self):
return [
e.key.get_name()
for e in self._entries
if e.key is not None
e.key.get_name() for e in self._entries if e.key is not None
]

entries = []
Expand Down Expand Up @@ -322,13 +321,19 @@ class HostKeyEntry:
Representation of a line in an OpenSSH-style "known hosts" file.
"""

def __init__(self, hostnames=None, key=None):
def __init__(
self,
hostnames: Optional[Iterable[str]] = None,
key: Optional[PKey] = None,
marker: Optional[HostKeyMarkers] = None,
):
self.valid = (hostnames is not None) and (key is not None)
self.hostnames = hostnames
self.key = key
self._marker = marker

@classmethod
def from_line(cls, line, lineno=None):
def from_line(cls, line: str, lineno: Optional[int] = None):
"""
Parses the given line of text to find the names for the host,
the type of key, and the key data. The line is expected to be in the
Expand All @@ -340,6 +345,7 @@ def from_line(cls, line, lineno=None):
that should be taken care of before sending the line to us.
:param str line: a line from an OpenSSH known_hosts file
:param int|None lineno: the line number on which the entry appears
"""
log = get_logger("paramiko.hostkeys")
fields = re.split(" |\t", line)
Expand Down Expand Up @@ -375,7 +381,9 @@ def from_line(cls, line, lineno=None):
raise InvalidHostKey(line, e)

try:
return cls(names, PKey.from_type_string(key_type, key_bytes))
return cls(
names, PKey.from_type_string(key_type, key_bytes), marker=marker
)
except UnknownKeyType:
# TODO 4.0: consider changing HostKeys API so this just raises
# naturally and the exception is muted higher up in the stack?
Expand All @@ -389,6 +397,13 @@ def to_line(self):
included.
"""
if self.valid:
if self._marker:
return "{} {} {} {}\n".format(
self._marker.value,
",".join(self.hostnames),
self.key.get_name(),
self.key.get_base64(),
)
return "{} {} {}\n".format(
",".join(self.hostnames),
self.key.get_name(),
Expand Down

0 comments on commit e908acc

Please sign in to comment.