本文整理汇总了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)
示例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)
示例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()
示例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())
示例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())
示例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())
示例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
示例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()
示例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
示例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)])
示例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
示例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)
示例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)))
示例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])
示例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))