当前位置: 首页>>代码示例>>Python>>正文


Python Key.fromString方法代码示例

本文整理汇总了Python中twisted.conch.ssh.keys.Key.fromString方法的典型用法代码示例。如果您正苦于以下问题:Python Key.fromString方法的具体用法?Python Key.fromString怎么用?Python Key.fromString使用的例子?那么恭喜您, 这里精选的方法代码示例或许可以为您提供帮助。您也可以进一步了解该方法所在twisted.conch.ssh.keys.Key的用法示例。


在下文中一共展示了Key.fromString方法的15个代码示例,这些例子默认根据受欢迎程度排序。您可以为喜欢或者感觉有用的代码点赞,您的评价将有助于系统推荐出更棒的Python代码示例。

示例1: getKeyPair

# 需要导入模块: from twisted.conch.ssh.keys import Key [as 别名]
# 或者: from twisted.conch.ssh.keys.Key import fromString [as 别名]
def getKeyPair(pubkeyfile, privkeyfile):
    """
    This function looks for RSA keypair files in the current directory. If they
    do not exist, the keypair is created.
    """

    if not (os.path.exists(pubkeyfile) and os.path.exists(privkeyfile)):
        # No keypair exists. Generate a new RSA keypair
        from Crypto.PublicKey import RSA

        rsa_key = Key(RSA.generate(_KEY_LENGTH))
        public_key_string = rsa_key.public().toString(type="OPENSSH")
        private_key_string = rsa_key.toString(type="OPENSSH")

        # save keys for the future.
        with open(privkeyfile, 'wt') as pfile:
            pfile.write(private_key_string)
            print("Created SSH private key in '{}'".format(_PRIVATE_KEY_FILE))
        with open(pubkeyfile, 'wt') as pfile:
            pfile.write(public_key_string)
            print("Created SSH public key in '{}'".format(_PUBLIC_KEY_FILE))
    else:
        with open(pubkeyfile) as pfile:
            public_key_string = pfile.read()
        with open(privkeyfile) as pfile:
            private_key_string = pfile.read()

    return Key.fromString(public_key_string), Key.fromString(private_key_string)
开发者ID:BlauFeuer,项目名称:evennia,代码行数:30,代码来源:ssh.py

示例2: getKeyPair

# 需要导入模块: from twisted.conch.ssh.keys import Key [as 别名]
# 或者: from twisted.conch.ssh.keys.Key import fromString [as 别名]
def getKeyPair(pubkeyfile, privkeyfile):
    """
    This function looks for RSA keypair files in the current directory. If they
    do not exist, the keypair is created.
    """

    if not (os.path.exists(pubkeyfile) and os.path.exists(privkeyfile)):
        # No keypair exists. Generate a new RSA keypair
        print("  Generating SSH RSA keypair ...", end=' ')
        from Crypto.PublicKey import RSA

        KEY_LENGTH = 1024
        rsaKey = Key(RSA.generate(KEY_LENGTH))
        publicKeyString = rsaKey.public().toString(type="OPENSSH")
        privateKeyString = rsaKey.toString(type="OPENSSH")

        # save keys for the future.
        file(pubkeyfile, 'w+b').write(publicKeyString)
        file(privkeyfile, 'w+b').write(privateKeyString)
        print(" done.")
    else:
        publicKeyString = file(pubkeyfile).read()
        privateKeyString = file(privkeyfile).read()

    return Key.fromString(publicKeyString), Key.fromString(privateKeyString)
开发者ID:325975,项目名称:evennia,代码行数:27,代码来源:ssh.py

示例3: _check_public_key

# 需要导入模块: from twisted.conch.ssh.keys import Key [as 别名]
# 或者: from twisted.conch.ssh.keys.Key import fromString [as 别名]
    def _check_public_key (self, key, ) :
        try :
            Key.fromString(data=key, )
        except BadKeyError :
            raise _exceptions.BAD_ARGUMENT("invalid public key.")

        return key.strip()
开发者ID:spikeekips,项目名称:source-over-ssh,代码行数:9,代码来源:shell.py

示例4: test_saveKeysha256

# 需要导入模块: from twisted.conch.ssh.keys import Key [as 别名]
# 或者: from twisted.conch.ssh.keys.Key import fromString [as 别名]
 def test_saveKeysha256(self):
     """
     L{_saveKey} will generate key fingerprint in
     L{FingerprintFormats.SHA256-BASE64} format if explicitly specified.
     """
     base = FilePath(self.mktemp())
     base.makedirs()
     filename = base.child('id_rsa').path
     key = Key.fromString(privateRSA_openssh)
     _saveKey(key, {'filename': filename, 'pass': 'passphrase',
         'format': 'sha256-base64'})
     self.assertEqual(
         self.stdout.getvalue(),
         "Your identification has been saved in %s\n"
         "Your public key has been saved in %s.pub\n"
         "The key fingerprint in <FingerprintFormats=SHA256_BASE64> is:\n"
         "ryaugIFT0B8ItuszldMEU7q14rG/wj9HkRosMeBWkts=\n" % (
             filename,
             filename))
     self.assertEqual(
         key.fromString(
             base.child('id_rsa').getContent(), None, 'passphrase'),
         key)
     self.assertEqual(
         Key.fromString(base.child('id_rsa.pub').getContent()),
         key.public())
开发者ID:esabelhaus,项目名称:secret-octo-dubstep,代码行数:28,代码来源:test_ckeygen.py

示例5: test_saveKey

# 需要导入模块: from twisted.conch.ssh.keys import Key [as 别名]
# 或者: from twisted.conch.ssh.keys.Key import fromString [as 别名]
 def test_saveKey(self):
     """
     L{_saveKey} writes the private and public parts of a key to two
     different files and writes a report of this to standard out.
     """
     base = FilePath(self.mktemp())
     base.makedirs()
     filename = base.child('id_rsa').path
     key = Key.fromString(privateRSA_openssh)
     _saveKey(
         key.keyObject,
         {'filename': filename, 'pass': 'passphrase'})
     self.assertEqual(
         self.stdout.getvalue(),
         "Your identification has been saved in %s\n"
         "Your public key has been saved in %s.pub\n"
         "The key fingerprint is:\n"
         "3d:13:5f:cb:c9:79:8a:93:06:27:65:bc:3d:0b:8f:af\n" % (
             filename,
             filename))
     self.assertEqual(
         key.fromString(
             base.child('id_rsa').getContent(), None, 'passphrase'),
         key)
     self.assertEqual(
         Key.fromString(base.child('id_rsa.pub').getContent()),
         key.public())
开发者ID:0004c,项目名称:VTK,代码行数:29,代码来源:test_ckeygen.py

示例6: test_saveKeyECDSA

# 需要导入模块: from twisted.conch.ssh.keys import Key [as 别名]
# 或者: from twisted.conch.ssh.keys.Key import fromString [as 别名]
 def test_saveKeyECDSA(self):
     """
     L{_saveKey} writes the private and public parts of a key to two
     different files and writes a report of this to standard out.
     Test with ECDSA key.
     """
     base = FilePath(self.mktemp())
     base.makedirs()
     filename = base.child('id_ecdsa').path
     key = Key.fromString(privateECDSA_openssh)
     _saveKey(key, {'filename': filename, 'pass': 'passphrase',
         'format': 'md5-hex'})
     self.assertEqual(
         self.stdout.getvalue(),
         "Your identification has been saved in %s\n"
         "Your public key has been saved in %s.pub\n"
         "The key fingerprint in <FingerprintFormats=MD5_HEX> is:\n"
         "e2:3b:e8:1c:f8:c9:c7:de:8b:c0:00:68:2e:c9:2c:8a\n" % (
             filename,
             filename))
     self.assertEqual(
         key.fromString(
             base.child('id_ecdsa').getContent(), None, 'passphrase'),
         key)
     self.assertEqual(
         Key.fromString(base.child('id_ecdsa.pub').getContent()),
         key.public())
开发者ID:esabelhaus,项目名称:secret-octo-dubstep,代码行数:29,代码来源:test_ckeygen.py

示例7: manhole

# 需要导入模块: from twisted.conch.ssh.keys import Key [as 别名]
# 或者: from twisted.conch.ssh.keys.Key import fromString [as 别名]
def manhole(username, password, globals):
    """Starts a ssh listener with password authentication using
    the given username and password. Clients connecting to the ssh
    listener will find themselves in a colored python shell with
    the supplied globals.

    Args:
        username(str): The username ssh clients should auth with.
        password(str): The password ssh clients should auth with.
        globals(dict): The variables to expose in the shell.

    Returns:
        twisted.internet.protocol.Factory: A factory to pass to ``listenTCP``
    """
    if not isinstance(password, bytes):
        password = password.encode('ascii')

    checker = checkers.InMemoryUsernamePasswordDatabaseDontUse(
        **{username: password}
    )

    rlm = manhole_ssh.TerminalRealm()
    rlm.chainedProtocolFactory = lambda: insults.ServerProtocol(
        SynapseManhole,
        dict(globals, __name__="__console__")
    )

    factory = manhole_ssh.ConchFactory(portal.Portal(rlm, [checker]))
    factory.publicKeys[b'ssh-rsa'] = Key.fromString(PUBLIC_KEY)
    factory.privateKeys[b'ssh-rsa'] = Key.fromString(PRIVATE_KEY)

    return factory
开发者ID:matrix-org,项目名称:synapse,代码行数:34,代码来源:manhole.py

示例8: main

# 需要导入模块: from twisted.conch.ssh.keys import Key [as 别名]
# 或者: from twisted.conch.ssh.keys.Key import fromString [as 别名]
def main(keys_path, username_get=None, gid=None, port=2022):
    settings.username_get = username_get
    settings.gid = gid
    key_path = keys_path + '/id_rsa'

    if not os.path.exists(key_path):
        subprocess.check_call(['ssh-keygen', '-f', key_path,
                               '-t', 'rsa', '-N', ''])

    with open(key_path) as privateBlobFile:
        privateBlob = privateBlobFile.read()
        privateKey = Key.fromString(data=privateBlob)

    with open(key_path + '.pub') as publicBlobFile:
        publicBlob = publicBlobFile.read()
        publicKey = Key.fromString(data=publicBlob)

    factory = SSHFactory()
    factory.privateKeys = {'ssh-rsa': privateKey}
    factory.publicKeys = {'ssh-rsa': publicKey}
    factory.portal = Portal(KeyRealm())
    factory.portal.registerChecker(KeyChecker())

    reactor.listenTCP(port, factory)
    reactor.run()
开发者ID:zielmicha,项目名称:gitjoin,代码行数:27,代码来源:sshd.py

示例9: __init__

# 需要导入模块: from twisted.conch.ssh.keys import Key [as 别名]
# 或者: from twisted.conch.ssh.keys.Key import fromString [as 别名]
    def __init__(self, options):

        self.options = options
        
        # load private key
        with open(options['host-key']) as privateBlobFile:
            privateBlob = privateBlobFile.read()
            privateKey = Key.fromString(data=privateBlob)

        # load public key
        with open(options['host-key']+'.pub') as publicBlobFile:
            publicBlob = publicBlobFile.read()
            publicKey = Key.fromString(data=publicBlob)

        tickets = {}
        factory = AMPSSHFactory(tickets, self.options)
        factory.services['ssh-connection'] = SSHConnection

        # Load in keys the way SSHFactory expects them.
        factory.privateKeys = {'ssh-rsa': privateKey}
        factory.publicKeys = {'ssh-rsa': publicKey}

        # Give it a portal to authenticate clients with
        factory.portal = Portal(SimpleRealm(tickets, options, factory))

        # validate against keys in authorized_keys files
        checker = AuthorizedKeys(options['authorized-keys'])
        factory.portal.registerChecker(checker)

        # init TCPServer with port and factory.
        internet.TCPServer.__init__(self, options['ssh-port'], factory)

        # remember for future reference
        self.factory = factory
开发者ID:bollustrado,项目名称:twisted_conch_pytexas_12,代码行数:36,代码来源:server.py

示例10: test_savingsPreservesExisting

# 需要导入模块: from twisted.conch.ssh.keys import Key [as 别名]
# 或者: from twisted.conch.ssh.keys.Key import fromString [as 别名]
    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,代码行数:30,代码来源:test_knownhosts.py

示例11: getRSAKeys

# 需要导入模块: from twisted.conch.ssh.keys import Key [as 别名]
# 或者: from twisted.conch.ssh.keys.Key import fromString [as 别名]
def getRSAKeys():
    print "running getRSAKeys"
    with open('/home/pi/.ssh/id_rsa') as privateBlobFile:
        privateBlob = privateBlobFile.read()
        privateKey = Key.fromString(data=privateBlob)

    with open('/home/pi/.ssh/id_rsa.pub') as publicBlobFile:
        publicBlob = publicBlobFile.read()
        publicKey = Key.fromString(data=publicBlob)

    return publicKey, privateKey
开发者ID:nahommarie,项目名称:UrbanFlows,代码行数:13,代码来源:sshserver3.py

示例12: test_verifyInvalidKey

# 需要导入模块: from twisted.conch.ssh.keys import Key [as 别名]
# 或者: from twisted.conch.ssh.keys.Key import fromString [as 别名]
 def test_verifyInvalidKey(self):
     """
     Verifying an invalid key should return a L{Deferred} which fires with a
     L{HostKeyChanged} failure.
     """
     hostsFile = self.loadSampleHostsFile()
     wrongKey = Key.fromString(thirdSampleKey)
     ui = FakeUI()
     hostsFile.addHostKey("1.2.3.4", Key.fromString(sampleKey))
     d = hostsFile.verifyHostKey(
         ui, "www.twistedmatrix.com", "1.2.3.4", wrongKey)
     return self.assertFailure(d, HostKeyChanged)
开发者ID:12019,项目名称:OpenWrt_Luci_Lua,代码行数:14,代码来源:test_knownhosts.py

示例13: test_notPresentKey

# 需要导入模块: from twisted.conch.ssh.keys import Key [as 别名]
# 或者: from twisted.conch.ssh.keys.Key import fromString [as 别名]
 def test_notPresentKey(self):
     """
     L{KnownHostsFile.hasHostKey} returns C{False} when a key for the given
     hostname is not present.
     """
     hostsFile = self.loadSampleHostsFile()
     self.assertFalse(hostsFile.hasHostKey(
             b"non-existent.example.com", Key.fromString(sampleKey)))
     self.assertTrue(hostsFile.hasHostKey(
             b"www.twistedmatrix.com", Key.fromString(sampleKey)))
     self.assertFalse(hostsFile.hasHostKey(
             b"www.twistedmatrix.com", Key.fromString(ecdsaSampleKey)))
开发者ID:JohnDoes95,项目名称:project_parser,代码行数:14,代码来源:test_knownhosts.py

示例14: test_verifyValidKey

# 需要导入模块: from twisted.conch.ssh.keys import Key [as 别名]
# 或者: from twisted.conch.ssh.keys.Key import fromString [as 别名]
 def test_verifyValidKey(self):
     """
     Verifying a valid key should return a L{Deferred} which fires with
     True.
     """
     hostsFile = self.loadSampleHostsFile()
     hostsFile.addHostKey("1.2.3.4", Key.fromString(sampleKey))
     ui = FakeUI()
     d = hostsFile.verifyHostKey(ui, "www.twistedmatrix.com", "1.2.3.4",
                                 Key.fromString(sampleKey))
     l = []
     d.addCallback(l.append)
     self.assertEqual(l, [True])
开发者ID:12019,项目名称:OpenWrt_Luci_Lua,代码行数:15,代码来源:test_knownhosts.py

示例15: test_matchesKey

# 需要导入模块: from twisted.conch.ssh.keys import Key [as 别名]
# 或者: from twisted.conch.ssh.keys.Key import fromString [as 别名]
 def test_matchesKey(self):
     """
     L{IKnownHostEntry.matchesKey} checks to see if an entry matches a given
     SSH key.
     """
     twistedmatrixDotCom = Key.fromString(sampleKey)
     divmodDotCom = Key.fromString(otherSampleKey)
     self.assertEqual(
         True,
         self.entry.matchesKey(twistedmatrixDotCom))
     self.assertEqual(
         False,
         self.entry.matchesKey(divmodDotCom))
开发者ID:12019,项目名称:OpenWrt_Luci_Lua,代码行数:15,代码来源:test_knownhosts.py


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