本文整理汇总了Python中twisted.conch.ssh.keys.Key类的典型用法代码示例。如果您正苦于以下问题:Python Key类的具体用法?Python Key怎么用?Python Key使用的例子?那么恭喜您, 这里精选的类代码示例或许可以为您提供帮助。
在下文中一共展示了Key类的20个代码示例,这些例子默认根据受欢迎程度排序。您可以为喜欢或者感觉有用的代码点赞,您的评价将有助于我们的系统推荐出更棒的Python代码示例。
示例1: __init__
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,代码行数:34,代码来源:server.py
示例2: getKeyPair
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,代码行数:28,代码来源:ssh.py
示例3: 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
示例4: test_saveKey
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,代码行数:27,代码来源:test_ckeygen.py
示例5: _check_public_key
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,代码行数:7,代码来源:shell.py
示例6: getKeyPair
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,代码行数:25,代码来源:ssh.py
示例7: test_saveKeyECDSA
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,代码行数:27,代码来源:test_ckeygen.py
示例8: test_saveKeysha256
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,代码行数:26,代码来源:test_ckeygen.py
示例9: verify_SSL_key_and_cert
def verify_SSL_key_and_cert(keyfile, certfile):
"""
This function looks for RSA key and certificate in the current
directory. If files ssl.key and ssl.cert does not exist, they
are created.
"""
if not (os.path.exists(keyfile) and os.path.exists(certfile)):
# key/cert does not exist. Create.
import subprocess
from Crypto.PublicKey import RSA
from twisted.conch.ssh.keys import Key
print(" Creating SSL key and certificate ... ", end=' ')
try:
# create the RSA key and store it.
KEY_LENGTH = 1024
rsaKey = Key(RSA.generate(KEY_LENGTH))
keyString = rsaKey.toString(type="OPENSSH")
file(keyfile, 'w+b').write(keyString)
except Exception as err:
print(NO_AUTOGEN.format(err=err, keyfile=keyfile))
sys.exit(5)
# try to create the certificate
CERT_EXPIRE = 365 * 20 # twenty years validity
# default:
# openssl req -new -x509 -key ssl.key -out ssl.cert -days 7300
exestring = "openssl req -new -x509 -key %s -out %s -days %s" % (keyfile, certfile, CERT_EXPIRE)
try:
subprocess.call(exestring)
except OSError as err:
raise OSError(NO_AUTOCERT.format(err=err, certfile=certfile, keyfile=keyfile, exestring=exestring))
print("done.")
开发者ID:helix-0311,项目名称:evennia,代码行数:35,代码来源:ssl.py
示例10: manhole
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,代码行数:32,代码来源:manhole.py
示例11: main
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,代码行数:25,代码来源:sshd.py
示例12: addKeyFile
def addKeyFile(self, kfile, password=None):
if not os.path.exists(kfile):
raise Exception("Key file not found %s", kfile)
try:
self.keys.append(Key.fromFile(kfile))
except EncryptedKeyError:
self.keys.append(Key.fromFile(kfile, passphrase=password))
开发者ID:calston,项目名称:tensor,代码行数:8,代码来源:ssh.py
示例13: makeFactory
def makeFactory(self):
"""Create and start the factory that our SSH server uses."""
factory = Factory(
get_portal(None, None),
private_key=Key.fromFile(
get_key_path(PRIVATE_KEY_FILE)),
public_key=Key.fromFile(
get_key_path(PUBLIC_KEY_FILE)))
factory.startFactory()
return factory
开发者ID:pombreda,项目名称:UnnaturalCodeFork,代码行数:10,代码来源:test_daemon.py
示例14: __init__
def __init__(self, settings):
self.settings = settings
self.portal = Portal(OpenRukoRealm(settings))
self.portal.registerChecker(OpenRukoCredentialChecker(settings))
self.privateKeys = {
'ssh-rsa': Key.fromFile(settings['gitmouth_private_key']),
}
self.publicKeys = {
'ssh-rsa': Key.fromFile(settings['gitmouth_public_key']),
}
开发者ID:boffbowsh,项目名称:gitmouth,代码行数:10,代码来源:server.py
示例15: __init__
def __init__(self, settings):
self.settings = settings
self.portal = Portal(Realm(settings))
self.portal.registerChecker(Checker(settings))
self.privateKeys = {
'ssh-rsa': Key.fromFile(settings['hadoukngit']['private_key']),
}
self.publicKeys = {
'ssh-rsa': Key.fromFile(settings['hadoukngit']['public_key']),
}
开发者ID:hadoukn,项目名称:hadoukn-git-server,代码行数:10,代码来源:server.py
示例16: getRSAKeys
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,代码行数:11,代码来源:sshserver3.py
示例17: test_notPresentKey
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,代码行数:12,代码来源:test_knownhosts.py
示例18: test_verifyInvalidKey
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,代码行数:12,代码来源:test_knownhosts.py
示例19: test_verifyValidKey
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,代码行数:13,代码来源:test_knownhosts.py
示例20: test_matchesKey
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,代码行数:13,代码来源:test_knownhosts.py
注:本文中的twisted.conch.ssh.keys.Key类示例由纯净天空整理自Github/MSDocs等源码及文档管理平台,相关代码片段筛选自各路编程大神贡献的开源项目,源码版权归原作者所有,传播和使用请参考对应项目的License;未经允许,请勿转载。 |
请发表评论