• 设为首页
  • 点击收藏
  • 手机版
    手机扫一扫访问
    迪恩网络手机版
  • 关注官方公众号
    微信扫一扫关注
    公众号

Python knownhosts.KnownHostsFile类代码示例

原作者: [db:作者] 来自: [db:来源] 收藏 邀请

本文整理汇总了Python中twisted.conch.client.knownhosts.KnownHostsFile的典型用法代码示例。如果您正苦于以下问题:Python KnownHostsFile类的具体用法?Python KnownHostsFile怎么用?Python KnownHostsFile使用的例子?那么恭喜您, 这里精选的类代码示例或许可以为您提供帮助。



在下文中一共展示了KnownHostsFile类的20个代码示例,这些例子默认根据受欢迎程度排序。您可以为喜欢或者感觉有用的代码点赞,您的评价将有助于我们的系统推荐出更棒的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)])
开发者ID:12019,项目名称:OpenWrt_Luci_Lua,代码行数:28,代码来源:test_knownhosts.py


示例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()))
开发者ID:12019,项目名称:OpenWrt_Luci_Lua,代码行数:7,代码来源:test_knownhosts.py


示例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)
开发者ID:AlexanderHerlan,项目名称:syncpy,代码行数:32,代码来源:test_endpoints.py


示例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())))
开发者ID:12019,项目名称:OpenWrt_Luci_Lua,代码行数:8,代码来源:test_knownhosts.py


示例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())
开发者ID:12019,项目名称:OpenWrt_Luci_Lua,代码行数:15,代码来源:test_knownhosts.py


示例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)
开发者ID:wellbehavedsoftware,项目名称:wbs-graphite,代码行数:26,代码来源:echoclient_ssh.py


示例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)))
开发者ID:0004c,项目名称:VTK,代码行数:7,代码来源:endpoints.py


示例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)
开发者ID:fredericlepied,项目名称:zgerrit,代码行数:28,代码来源:zgerrit.py


示例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)
开发者ID:Mato-Z,项目名称:cowrie,代码行数:29,代码来源:session.py


示例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")))
开发者ID:wangbinxiang,项目名称:flocker,代码行数:25,代码来源:_conch.py


示例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)
开发者ID:pdh,项目名称:beatlounge,代码行数:8,代码来源:console.py


示例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)
开发者ID:12019,项目名称:OpenWrt_Luci_Lua,代码行数:17,代码来源:test_knownhosts.py


示例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))
开发者ID:AlexanderHerlan,项目名称:syncpy,代码行数:17,代码来源:test_endpoints.py


示例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
开发者ID:eddking,项目名称:metis,代码行数:9,代码来源:client.py


示例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)
开发者ID:matanmaz,项目名称:SshTelnetProxy,代码行数:10,代码来源:TcpSshConverter.py


示例16: loadSampleHostsFile

 def loadSampleHostsFile(self, content=(
         sampleHashedLine + otherSamplePlaintextLine +
         "\n# That was a blank line.\n"
         "This is just unparseable.\n"
         "|1|This also unparseable.\n")):
     """
     Return a sample hosts file, with keys for www.twistedmatrix.com and
     divmod.com present.
     """
     return KnownHostsFile.fromPath(self.pathWithContent(content))
开发者ID:12019,项目名称:OpenWrt_Luci_Lua,代码行数:10,代码来源:test_knownhosts.py


示例17: setUp

 def setUp(self):
     """
     Patch 'open' in verifyHostKey.
     """
     self.fakeFile = FakeFile()
     self.patch(default, "_open", self.patchedOpen)
     self.hostsOption = self.mktemp()
     self.hashedEntries = {}
     knownHostsFile = KnownHostsFile(FilePath(self.hostsOption))
     for host in (b"exists.example.com", b"4.3.2.1"):
         entry = knownHostsFile.addHostKey(host, Key.fromString(sampleKey))
         self.hashedEntries[host] = entry
     knownHostsFile.save()
     self.fakeTransport = FakeObject()
     self.fakeTransport.factory = FakeObject()
     self.options = self.fakeTransport.factory.options = {
         'host': b"exists.example.com",
         'known-hosts': self.hostsOption
         }
开发者ID:JohnDoes95,项目名称:project_parser,代码行数:19,代码来源:test_knownhosts.py


示例18: test_loadNonExistent

 def test_loadNonExistent(self):
     """
     Loading a L{KnownHostsFile} from a path that does not exist should
     result in an empty L{KnownHostsFile} that will save back to that path.
     """
     pn = self.mktemp()
     knownHostsFile = KnownHostsFile.fromPath(FilePath(pn))
     self.assertEqual([], list(knownHostsFile._entries))
     self.assertEqual(False, FilePath(pn).exists())
     knownHostsFile.save()
     self.assertEqual(True, FilePath(pn).exists())
开发者ID:AmirKhooj,项目名称:VTK,代码行数:11,代码来源:test_knownhosts.py


示例19: test_loadNonExistentParent

 def test_loadNonExistentParent(self):
     """
     Loading a L{KnownHostsFile} from a path whose parent directory does not
     exist should result in an empty L{KnownHostsFile} that will save back
     to that path, creating its parent directory(ies) in the process.
     """
     thePath = FilePath(self.mktemp())
     knownHostsPath = thePath.child("foo").child("known_hosts")
     knownHostsFile = KnownHostsFile.fromPath(knownHostsPath)
     knownHostsFile.save()
     knownHostsPath.restat(False)
     self.assertEqual(True, knownHostsPath.exists())
开发者ID:12019,项目名称:OpenWrt_Luci_Lua,代码行数:12,代码来源:test_knownhosts.py


示例20: test_readExisting

    def test_readExisting(self):
        """
        Existing entries in the I{known_hosts} file are reflected by the
        L{KnownHostsFile} created by L{_NewConnectionHelper} when none is
        supplied to it.
        """
        key = CommandFactory().publicKeys['ssh-rsa']
        path = FilePath(self.mktemp())
        knownHosts = KnownHostsFile(path)
        knownHosts.addHostKey("127.0.0.1", key)
        knownHosts.save()

        msg("Created known_hosts file at %r" % (path.path,))

        # Unexpand ${HOME} to make sure ~ syntax is respected.
        home = os.path.expanduser("~/")
        default = path.path.replace(home, "~/")
        self.patch(_NewConnectionHelper, "_KNOWN_HOSTS", default)
        msg("Patched _KNOWN_HOSTS with %r" % (default,))

        loaded = _NewConnectionHelper._knownHosts()
        self.assertTrue(loaded.hasHostKey("127.0.0.1", key))
开发者ID:AlexanderHerlan,项目名称:syncpy,代码行数:22,代码来源:test_endpoints.py



注:本文中的twisted.conch.client.knownhosts.KnownHostsFile类示例由纯净天空整理自Github/MSDocs等源码及文档管理平台,相关代码片段筛选自各路编程大神贡献的开源项目,源码版权归原作者所有,传播和使用请参考对应项目的License;未经允许,请勿转载。


鲜花

握手

雷人

路过

鸡蛋
该文章已有0人参与评论

请发表评论

全部评论

专题导读
上一篇:
Python endpoints.SSHCommandClientEndpoint类代码示例发布时间:2022-05-27
下一篇:
Python avatar.ConchUser类代码示例发布时间:2022-05-27
热门推荐
阅读排行榜

扫描微信二维码

查看手机版网站

随时了解更新最新资讯

139-2527-9053

在线客服(服务时间 9:00~18:00)

在线QQ客服
地址:深圳市南山区西丽大学城创智工业园
电邮:jeky_zhao#qq.com
移动电话:139-2527-9053

Powered by 互联科技 X3.4© 2001-2213 极客世界.|Sitemap