本文整理汇总了Python中twisted.conch.client.knownhosts.KnownHostsFile类的典型用法代码示例。如果您正苦于以下问题:Python KnownHostsFile类的具体用法?Python KnownHostsFile怎么用?Python KnownHostsFile使用的例子?那么恭喜您, 这里精选的类代码示例或许可以为您提供帮助。
在下文中一共展示了KnownHostsFile类的15个代码示例,这些例子默认根据受欢迎程度排序。您可以为喜欢或者感觉有用的代码点赞,您的评价将有助于系统推荐出更棒的Python代码示例。
示例1: test_savingsPreservesExisting
def test_savingsPreservesExisting(self):
"""
L{KnownHostsFile.save} will not overwrite existing entries in its save
path, even if they were only added after the L{KnownHostsFile} instance
was initialized.
"""
# Start off with one host/key pair in the file
path = self.pathWithContent(sampleHashedLine)
knownHosts = KnownHostsFile.fromPath(path)
# After initializing the KnownHostsFile instance, add a second host/key
# pair to the file directly - without the instance's help or knowledge.
with path.open("a") as hostsFileObj:
hostsFileObj.write(otherSamplePlaintextLine)
# Add a third host/key pair using the KnownHostsFile instance
key = Key.fromString(thirdSampleKey)
knownHosts.addHostKey("brandnew.example.com", key)
knownHosts.save()
# Check that all three host/key pairs are present.
knownHosts = KnownHostsFile.fromPath(path)
self.assertEqual([True, True, True], [
knownHosts.hasHostKey(
"www.twistedmatrix.com", Key.fromString(sampleKey)),
knownHosts.hasHostKey(
"divmod.com", Key.fromString(otherSampleKey)),
knownHosts.hasHostKey("brandnew.example.com", key)])
示例2: test_defaultInitializerIgnoresExisting
def test_defaultInitializerIgnoresExisting(self):
"""
The default initializer for L{KnownHostsFile} disregards any existing
contents in the save path.
"""
hostsFile = KnownHostsFile(self.pathWithContent(sampleHashedLine))
self.assertEqual([], list(hostsFile.iterentries()))
示例3: test_mismatchedHostKey
def test_mismatchedHostKey(self):
"""
If the SSH public key presented by the SSH server does not match the
previously remembered key, as reported by the L{KnownHostsFile}
instance use to construct the endpoint, for that server, the
L{Deferred} returned by L{SSHCommandClientEndpoint.connect} fires with
a L{Failure} wrapping L{HostKeyChanged}.
"""
differentKey = Key.fromString(privateDSA_openssh).public()
knownHosts = KnownHostsFile(self.mktemp())
knownHosts.addHostKey(self.serverAddress.host, differentKey)
knownHosts.addHostKey(self.hostname, differentKey)
# The UI may answer true to any questions asked of it; they should
# make no difference, since a *mismatched* key is not even optionally
# allowed to complete a connection.
ui = FixedResponseUI(True)
endpoint = SSHCommandClientEndpoint.newConnection(
self.reactor, b"/bin/ls -l", b"dummy user",
self.hostname, self.port, password=b"dummy password",
knownHosts=knownHosts, ui=ui)
factory = Factory()
factory.protocol = Protocol
connected = endpoint.connect(factory)
server, client, pump = self.connectedServerAndClient(
self.factory, self.reactor.tcpClients[0][2])
f = self.failureResultOf(connected)
f.trap(HostKeyChanged)
示例4: test_iterentriesUnsaved
def test_iterentriesUnsaved(self):
"""
If the save path for a L{KnownHostsFile} does not exist,
L{KnownHostsFile.iterentries} still returns added but unsaved entries.
"""
hostsFile = KnownHostsFile(FilePath(self.mktemp()))
hostsFile.addHostKey("www.example.com", Key.fromString(sampleKey))
self.assertEqual(1, len(list(hostsFile.iterentries())))
示例5: test_defaultInitializerClobbersExisting
def test_defaultInitializerClobbersExisting(self):
"""
After using the default initializer for L{KnownHostsFile}, the first use
of L{KnownHostsFile.save} overwrites any existing contents in the save
path.
"""
path = self.pathWithContent(sampleHashedLine)
hostsFile = KnownHostsFile(path)
entry = hostsFile.addHostKey(
"www.example.com", Key.fromString(otherSampleKey))
hostsFile.save()
# Check KnownHostsFile to see what it thinks the state is
self.assertEqual([entry], list(hostsFile.iterentries()))
# And also directly check the underlying file itself
self.assertEqual(entry.toString() + "\n", path.getContent())
示例6: fromCommandLine
def fromCommandLine(cls, reactor, argv):
config = EchoOptions()
config.parseOptions(argv)
keys = []
if config["identity"]:
keyPath = os.path.expanduser(config["identity"])
if os.path.exists(keyPath):
keys.append(readKey(keyPath))
knownHostsPath = FilePath(os.path.expanduser(config["knownhosts"]))
if knownHostsPath.exists():
knownHosts = KnownHostsFile.fromPath(knownHostsPath)
else:
knownHosts = None
if config["no-agent"] or "SSH_AUTH_SOCK" not in os.environ:
agentEndpoint = None
else:
agentEndpoint = UNIXClientEndpoint(
reactor, os.environ["SSH_AUTH_SOCK"])
return cls(
reactor, config["host"], config["port"],
config["username"], config["password"], keys,
knownHosts, agentEndpoint)
示例7: _knownHosts
def _knownHosts(cls):
"""
@return: A L{KnownHostsFile} instance pointed at the user's personal
I{known hosts} file.
@type: L{KnownHostsFile}
"""
return KnownHostsFile.fromPath(FilePath(expanduser(cls._KNOWN_HOSTS)))
示例8: fromConfig
def fromConfig(cls, reactor):
keys = []
if "identity" in _CONFIG:
keyPath = os.path.expanduser(_CONFIG["identity"])
if os.path.exists(keyPath):
keys.append(readKey(keyPath))
knownHostsPath = FilePath(os.path.expanduser(_CONFIG["knownhosts"]))
if knownHostsPath.exists():
knownHosts = KnownHostsFile.fromPath(knownHostsPath)
else:
knownHosts = None
if "no-agent" in _CONFIG or "SSH_AUTH_SOCK" not in os.environ:
agentEndpoint = None
else:
agentEndpoint = UNIXClientEndpoint(
reactor, os.environ["SSH_AUTH_SOCK"])
if "password" in _CONFIG:
password = _CONFIG["password"]
else:
password = None
return cls(
reactor, _CONFIG["host"], _CONFIG["port"],
_CONFIG["username"], password, keys,
knownHosts, agentEndpoint)
示例9: __init__
def __init__(self, *args, **kw):
channel.CowrieSSHChannel.__init__(self, *args, **kw)
keyPath = CONFIG.get('proxy', 'private_key')
self.keys.append(keys.Key.fromFile(keyPath))
try:
keyPath = CONFIG.get('proxy', 'private_key')
self.keys.append(keys.Key.fromFile(keyPath))
except NoOptionError:
self.keys = None
knownHostsPath = CONFIG.get('proxy', 'known_hosts')
self.knownHosts = KnownHostsFile.fromPath(knownHostsPath)
self.host = CONFIG.get('proxy', 'host')
self.port = CONFIG.getint('proxy', 'port')
self.user = CONFIG.get('proxy', 'user')
try:
self.password = CONFIG.get('proxy', 'password')
except NoOptionError:
self.password = None
log.msg("knownHosts = {0}".format(repr(self.knownHosts)))
log.msg("host = {0}".format(self.host))
log.msg("port = {0}".format(self.port))
log.msg("user = {0}".format(self.user))
self.client = ProxyClient(self)
示例10: get_connection_helper
def get_connection_helper(reactor, address, username, port):
"""
Get a :class:`twisted.conch.endpoints._ISSHConnectionCreator` to connect to
the given remote.
:param reactor: Reactor to connect with.
:param bytes address: The address of the remote host to connect to.
:param bytes username: The user to connect as.
:param int port: The port of the ssh server to connect to.
:return _ISSHConnectionCreator:
"""
try:
agentEndpoint = UNIXClientEndpoint(
reactor, os.environ["SSH_AUTH_SOCK"])
except KeyError:
agentEndpoint = None
return _NewConnectionHelper(
reactor, address, port, None, username,
keys=None,
password=None,
agentEndpoint=agentEndpoint,
knownHosts=KnownHostsFile.fromPath(FilePath("/dev/null")),
ui=ConsoleUI(lambda: _ReadFile(b"yes")))
示例11: verifyHostKey
def verifyHostKey(transport, host, pubKey, fingerprint):
log.msg("verifying host key")
actualHost = transport.factory.options["host"]
actualKey = keys.Key.fromString(pubKey)
kh = KnownHostsFile.fromPath(
FilePath(transport.factory.options["known-hosts"] or os.path.expanduser("~/.ssh/known_hosts"))
)
return kh.verifyHostKey(console, actualHost, host, actualKey).addErrback(log.err)
示例12: test_unsavedEntryHasKeyMismatch
def test_unsavedEntryHasKeyMismatch(self):
"""
L{KnownHostsFile.hasHostKey} raises L{HostKeyChanged} if the host key is
present in memory (but not yet saved), but different from the expected
one. The resulting exception has a C{offendingEntry} indicating the
given entry, but no filename or line number information (reflecting the
fact that the entry exists only in memory).
"""
hostsFile = KnownHostsFile(FilePath(self.mktemp()))
entry = hostsFile.addHostKey(
"www.example.com", Key.fromString(otherSampleKey))
exception = self.assertRaises(
HostKeyChanged, hostsFile.hasHostKey,
"www.example.com", Key.fromString(thirdSampleKey))
self.assertEqual(exception.offendingEntry, entry)
self.assertEqual(exception.lineno, None)
self.assertEqual(exception.path, None)
示例13: setUp
def setUp(self):
"""
Configure an SSH server with password authentication enabled for a
well-known (to the tests) account.
"""
SSHCommandClientEndpointTestsMixin.setUp(self)
knownHosts = KnownHostsFile(FilePath(self.mktemp()))
knownHosts.addHostKey(
self.hostname, self.factory.publicKeys['ssh-rsa'])
knownHosts.addHostKey(
self.serverAddress.host, self.factory.publicKeys['ssh-rsa'])
self.endpoint = SSHCommandClientEndpoint.newConnection(
self.reactor, b"/bin/ls -l", self.user, self.hostname, self.port,
password=self.password, knownHosts=knownHosts,
ui=FixedResponseUI(False))
示例14: __init__
def __init__(self, factory):
self.factory = factory
self._state = b'STARTING'
self.knownHosts = KnownHostsFile.fromPath(
FilePath(os.path.expanduser('~/.ssh/known_hosts'))
)
self._hostKeyFailure = None
self._user_auth = None
self._connection_lost_reason = None
示例15: connectionMade
def connectionMade(self):
script_dir = os.getcwd()
rel_path = "hostkeys"
abs_file_path = os.path.join(script_dir, rel_path)
knownHosts = KnownHostsFile.fromPath(abs_file_path)
self.point = SSHCommandClientEndpoint.newConnection(reactor, 'cmd', 'user', '127.0.0.1', port=5122,
password='password', knownHosts=PermissiveKnownHosts())
self.sshSide = FzSSHClient()
self.sshSide.tcpSide = self
connectProtocol(self.point, self.sshSide)