本文整理汇总了Python中paramiko.rsakey.RSAKey类的典型用法代码示例。如果您正苦于以下问题:Python RSAKey类的具体用法?Python RSAKey怎么用?Python RSAKey使用的例子?那么恭喜您, 这里精选的类代码示例或许可以为您提供帮助。
在下文中一共展示了RSAKey类的15个代码示例,这些例子默认根据受欢迎程度排序。您可以为喜欢或者感觉有用的代码点赞,您的评价将有助于系统推荐出更棒的Python代码示例。
示例1: gen_keys
def gen_keys(key="", key_path_dir=""):
"""
在KEY_DIR下创建一个 uuid命名的目录,
并且在该目录下 生产一对秘钥
:return: 返回目录名(uuid)
"""
key_basename = "key-" + uuid4().hex
if not key_path_dir:
key_path_dir = os.path.join(KEY_DIR, 'role_key', key_basename)
private_key = os.path.join(key_path_dir, 'id_rsa')
public_key = os.path.join(key_path_dir, 'id_rsa.pub')
mkdir(key_path_dir, mode=755)
if not key:
key = RSAKey.generate(2048)
key.write_private_key_file(private_key)
else:
key_file = os.path.join(key_path_dir, 'id_rsa')
with open(key_file, 'w') as f:
f.write(key)
f.close()
with open(key_file) as f:
try:
key = RSAKey.from_private_key(f)
except SSHException, e:
shutil.rmtree(key_path_dir, ignore_errors=True)
raise SSHException(e)
示例2: public_key_fingerprint
def public_key_fingerprint(key):
paramiko_key = ParamikoRSAKey(vals=(key.e, key.n))
fp = hexlify(paramiko_key.get_fingerprint())
openssh_fp = ":".join([a+b for a, b in zip(fp[::2], fp[1::2])])
return openssh_fp
示例3: public_key_fingerprint
def public_key_fingerprint(key):
# paramiko can compute the OpenSSH-style fingerprint
# Only fingerprints the public key
paramiko_key = ParamikoRSAKey(vals=(key.e, key.n))
fp = hexlify(paramiko_key.get_fingerprint())
# OpenSSH puts a ":" character between every pair of hex-digits.
# For whatever reason. Readability, I guess.
openssh_fp = ":".join([a + b for a, b in zip(fp[::2], fp[1::2])])
return openssh_fp
示例4: __init__
def __init__(self, private_key=None, private_key_path=None, pub_data=None, _key=None, password=None):
if private_key:
self._key = RSAKey(file_obj=io.StringIO(private_key))
elif private_key_path:
self._key = RSAKey(filename=private_key_path, password=password)
elif pub_data:
if pub_data.startswith(self.SSH_PUB_KEY_PREFIX):
pub_data = pub_data[len(self.SSH_PUB_KEY_PREFIX):]
self._key = RSAKey(data=b64decode(pub_data.encode('utf-8')))
elif _key:
self._key = _key
else:
self._key = RSAKey.generate(self.KEY_SIZE)
示例5: test_public_key
def test_public_key(fx_app, fx_key_store,
fx_authorized_identity,
fx_token_id):
key = RSAKey.generate(1024)
fx_key_store.register(fx_authorized_identity, key)
with fx_app.test_client() as client:
response = client.get(
get_url(
'public_key',
token_id=fx_token_id,
fingerprint=key.get_fingerprint()
)
)
assert response.status_code == 200
assert response.mimetype == 'text/plain'
assert parse_openssh_pubkey(response.data.decode()) == key
with fx_app.test_client() as client:
response = client.get(
get_url(
'public_key',
token_id=fx_token_id,
fingerprint=os.urandom(16)
)
)
assert response.status_code == 404
assert response.mimetype == 'application/json'
error = json.loads(response.data.decode('utf-8'))
assert error['error'] == 'not-found'
示例6: __init__
def __init__(self,
hostname,
username=None,
password=None,
port=22,
private_key=None,
connect_timeout=None,
missing_host_key=None,
sock=None):
super(SshShell, self).__init__(hostname=hostname,
username=username,
password=password,
port=port,
connect_timeout=connect_timeout,
missing_host_key=missing_host_key)
try:
self._pkey = RSAKey.from_private_key(StringIO(private_key))
except SSHException:
try:
self._pkey = DSSKey.from_private_key(StringIO(private_key))
except SSHException:
raise ValidatorException("Unknown private key format")
self._sock = sock
示例7: sign_token
def sign_token(key_path, fingerprint, data):
# from agent
pkey = get_key_from_agent(fingerprint)
if not pkey:
# or from file (without passphrase)
# assuming '.pub' file extension
if not os.path.exists(key_path[:-4]):
raise SignatureException('WrongKeyPath')
try:
pkey = RSAKey.from_private_key_file(key_path[:-4])
except PasswordRequiredException:
raise SignatureException('EncryptedKey')
if not pkey:
raise SignatureException('KeyNotFound')
try:
# paramiko is inconsistent here in that the agent's key
# returns Message objects for 'sign_ssh_data' whereas RSAKey
# objects returns byte strings.
# Workaround: cast both return values to string and build a
# new Message object
s = str(pkey.sign_ssh_data(data))
m = Message(s)
m.rewind()
if not m.get_string() == 'ssh-rsa':
raise SignatureException('RSAKeyRequired')
return base64.b64encode(m.get_string())
except Exception:
raise SignatureException('SignatureCreateFailure')
示例8: _op_user
def _op_user(self, op, server, cmd_subs, quiet=False):
"""common code for adding/removing users."""
pkey_f = StringIO(self.private_key)
pkey = RSAKey.from_private_key(pkey_f)
pkey_f.close()
cmd = getattr(self, "%s_user_command" % op) % cmd_subs
cmd = cmd + "; echo $?"
out, err = server.exec_command(
cmd,
username=str(self.admin_username),
pkey=pkey,
)
lines = out.strip().split("\n")
ret = int(lines[-1])
if ret != 0:
error = "".join(lines[:-1])
if not quiet:
# msg example
msg = "Failed to %s user on %s. Output was:\n%s" \
% (op, server, error),
post_message_to_current_user(
msg,
msg_type=DatedMessage.TYPE_ERROR,
)
# end msg example
raise Exception(msg)
示例9: test_authorize_remote
def test_authorize_remote(fx_app, fx_authorized_servers, fx_master_key,
fx_authorized_remote_set, fx_authorized_identity,
fx_token_id, fx_key_store):
public_key = RSAKey.generate(1024)
fx_key_store.register(fx_authorized_identity, public_key)
alias, remote = dict(fx_authorized_remote_set).popitem()
with fx_app.test_client() as client:
response = client.post(
get_url('authorize_remote', token_id=fx_token_id, alias=alias)
)
assert response.status_code == 200
assert response.mimetype == 'application/json'
result = json.loads(response.data)
assert result['success'] == 'authorized'
assert result['remote'] == remote_dict(remote)
expires_at = parse_date(result['expires_at'])
thread, path, ev = fx_authorized_servers[remote.port]
authorized_keys_path = path.join('.ssh', 'authorized_keys')
with authorized_keys_path.open() as f:
saved_keys = map(parse_openssh_pubkey, f)
assert frozenset(saved_keys) == {fx_master_key, public_key}
while datetime.datetime.now(datetime.timezone.utc) <= expires_at:
time.sleep(1)
time.sleep(1)
with authorized_keys_path.open() as f:
saved_keys = map(parse_openssh_pubkey, f)
assert frozenset(saved_keys) == {fx_master_key}
示例10: test_delete_public_key
def test_delete_public_key(fx_app, fx_key_store,
fx_authorized_identity,
fx_token_id):
key = RSAKey.generate(1024)
fx_key_store.register(fx_authorized_identity, key)
with fx_app.test_client() as client:
response = client.delete(
get_url(
'delete_public_key',
token_id=fx_token_id,
fingerprint=key.get_fingerprint()
)
)
assert response.status_code == 200
assert key not in fx_key_store.list_keys(fx_authorized_identity)
with fx_app.test_client() as client:
response = client.delete(
get_url(
'delete_public_key',
token_id=fx_token_id,
fingerprint=key.get_fingerprint()
)
)
assert response.status_code == 404
assert response.mimetype == 'application/json'
error = json.loads(response.data.decode('utf-8'))
assert error['error'] == 'not-found'
示例11: renew_master_key
def renew_master_key(servers: collections.abc.Set, key_store: MasterKeyStore) -> PKey:
"""Renew the master key. It creates a new master key, makes ``servers``
to authorize the new key, replaces the existing master key with the
new key in the ``key_store``, and then makes ``servers`` to deauthorize
the old key. All these operations are done in a two-phase renewal
transaction.
:param servers: servers to renew the master key.
every element has to be an instance of
:class:`~.remote.Remote`
:type servers: :class:`collections.abc.Set`
:param key_store: the master key store to update
:type key_store: :class:`MasterKeyStore`
:returns: the created new master key
:rtype: :class:`paramiko.pkey.PKey`
"""
logger = logging.getLogger(__name__ + ".renew_master_key")
logger.info("renew the master key...")
old_key = key_store.load()
logger.info("the existing master key: %s", get_key_fingerprint(old_key))
new_key = RSAKey.generate(1024)
logger.info("created new master key: %s", get_key_fingerprint(new_key))
logger.info("authorize the new master key...")
with TwoPhaseRenewal(servers, old_key, new_key):
logger.info("the new master key is authorized; " "update the key store...")
key_store.save(new_key)
logger.info("master key store is successfully updated; " "deauthorize the existing master key...")
logger.info("master key renewal has finished")
return new_key
示例12: create_test_ssh_key
def create_test_ssh_key(self):
self.test_key = RSAKey.generate(1024)
self.test_pubkey = "\nssh-rsa %s %s\n" % \
(self.test_key.get_base64(), Tests.TEST_KEY_COMMENT)
f = open(os.path.expanduser("~/.ssh/authorized_keys"), "a")
f.write(self.test_pubkey)
f.close()
示例13: start_server
def start_server(path: str, host: str, port: int, terminated: threading.Event):
server_socket = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
server_socket.settimeout(1)
server_socket.setsockopt(socket.SOL_SOCKET, socket.SO_REUSEADDR, True)
server_socket.bind((host, port))
server_socket.listen(1)
stub_cls = type('StubSFTPServer', (StubSFTPServer,), {'ROOT': path})
host_key = RSAKey.generate(1024)
def accept(server_socket, mask):
conn, addr = server_socket.accept()
transport = Transport(conn)
transport.add_server_key(host_key)
transport.set_subsystem_handler('sftp', SFTPServer, stub_cls)
server = StubServer(path)
transport.start_server(server=server)
while not terminated.is_set():
channel = transport.accept(1)
if channel is not None and not terminated.is_set():
while transport.is_active() and not terminated.is_set():
terminated.wait(1)
break
sel = selectors.DefaultSelector()
sel.register(server_socket, selectors.EVENT_READ, accept)
last_used = time.time()
while not terminated.is_set() and last_used + 10 > time.time():
events = sel.select(1)
for key, mask in events:
key.data(key.fileobj, mask)
last_used = time.time()
示例14: __init__
def __init__(self, cb, config=None, address='', port=58337, backlog=100):
self.cb = cb
# Parse config <3
if config is not None:
with open(config, 'r') as f:
cfg = yaml.load(f)
else:
cfg = {}
logfile = cfg.get('logfile', None)
if logfile is not None:
paramiko.util.log_to_file(logile)
host_key_path = cfg.get('host_key', 'server.key')
host_key_password = cfg.get('host_key_password', None)
try:
self.host_key = RSAKey.from_private_key_file(host_key_path, host_key_password)
except paramiko.ssh_exception.PasswordRequiredException:
print 'Invalid host_key_password'
sys.exit(1)
except IOError:
print '*****************************************'
print '** host_key does not exists! **'
print '** In the name of security by default, **'
print '** Sheet will generate one for you. **'
print '*****************************************'
RSAKey.generate(2048).write_private_key_file(host_key_path, host_key_password)
self.handler = Broker.get(cfg.get('auth_handler', 'BaseAuth'))
self.handler_conf = cfg.get('auth_handler_config', {})
try:
self.socket = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
self.socket.setsockopt(socket.SOL_SOCKET, socket.SO_REUSEADDR, 1)
self.socket.bind((address, port))
except Exception as e:
print 'Bind failed: ', str(e)
traceback.print_exc()
sys.exit(1)
try:
self.socket.listen(backlog)
except Exception as e:
print 'Listen/accept failed:', str(e)
traceback.print_exc()
sys.exit(1)
示例15: test_add_public_key_415
def test_add_public_key_415(fx_app, fx_key_store, fx_authorized_identity, fx_token_id):
pkey = RSAKey.generate(1024)
with fx_app.test_client() as c:
response = c.post(get_url("add_public_key", token_id=fx_token_id), data={"key": format_openssh_pubkey(pkey)})
assert response.status_code == 415
error = json.loads(response.data)
assert error["error"] == "unsupported-content-type"
assert pkey not in fx_key_store.list_keys(fx_authorized_identity)