def __ssh_private_key_check(self): prvfile = self.get_config('ssh_keys') pubfile = "%s.pub" % prvfile prv = None if not os.path.exists(prvfile): try: self.log_info("generating %s" % prvfile) prv = RSAKey.generate(bits=1024) prv.write_private_key_file(prvfile) except Exception as e: self.log_critical("error: %s" % e) raise if not os.path.exists(pubfile): try: self.log_info("generating %s" % pubfile) pub = RSAKey(filename=prvfile) with open(pubfile, 'w') as f: f.write("%s %s" % (pub.get_name(), pub.get_base64())) except Exception as e: self.log_critical("error: %s" % e) raise if not prv: prv = RSAKey(filename=prvfile) self.ssh_host_key = prv self.ssh_host_hash = paramiko.py3compat.u( hexlify(prv.get_fingerprint())) self.log_info("SSH fingerprint: %s" % self.ssh_host_hash)
def clean(self): data = super(KeyAddForm, self).clean() key_type = data.get('key_type') public_key = data.get('public_key') try: if key_type == "ssh-rsa": k = RSAKey(data=base64.b64decode(public_key)) elif key_type == "ssh-dss": k = DSSKey(data=base64.b64decode(public_key)) elif key_type.startswith('ecdsa'): k = ECDSAKey(data=base64.b64decode(public_key)) else: raise forms.ValidationError( _("Unsupport key type: %(keytype)s"), code='invalid keytype', params={'key_type': key_type} ) data['key_type'] = k.get_name() data['public_key'] = base64.b64encode(k.get_base64()) except (TypeError, SSHException, UnicodeDecodeError) as err: if len(public_key) > 30: body = public_key[0:30] else: body = public_key raise forms.ValidationError( _("Body of SSH public key is invalid:\n%(body)s\n" "Error: %(err)s"), code='invalid key body', params={'body': body + "...", 'err': err} ) return data
def generate_key(): if not os.path.exists(keyfile): keydir = os.path.dirname(keyfile) if not os.path.exists(keydir): os.mkdir(keydir) prv = RSAKey.generate(bits=1024) prv.write_private_key_file(keyfile) pub = RSAKey(filename=keyfile) with open("%s.pub" % keyfile, 'w') as f: f.write("%s %s" % (pub.get_name(), pub.get_base64())) print("Made new Wharf SSH key")
def generate_keypair(key_pair_name): # generating private key prv = RSAKey.generate(bits=2048) prv.write_private_key_file(key_pair_name) # generating public key pub = RSAKey(filename=key_pair_name) with open("%s.pub" % key_pair_name, "w") as f: f.write("%s %s" % (pub.get_name(), pub.get_base64())) #Read public key fp = open(os.path.expanduser('./%s.pub' % key_pair_name)) pub_key = fp.read() fp.close() return pub_key
def generate_ssh_key_pairs(filename, phrase): """ SSH key pairs generator for remote docker host provider Args: filename (str):The filename path where ssh keys will be saved. phrase (str):The password phrase. Returns: """ # generating private key prv = RSAKey.generate(bits=2048, progress_func=None) prv.write_private_key_file(filename, password=phrase) # generating public key pub = RSAKey(filename=filename, password=phrase) with open("%s.pub" % filename, "w") as f: f.write("%s %s" % (pub.get_name(), pub.get_base64())) f.write(" %s" % "moitoi_docker_hive_key")
def generate_host_key(self, filename): from paramiko import RSAKey bits = 4096 if self.config.has_option('ssh', 'HostKeyBits'): bits = self.config.getint('ssh', 'HostKeyBits') # generate private key and save, self.log.info('Generating {bits}-bit RSA public/private keypair.' .format(bits=bits)) priv_key = RSAKey.generate(bits=bits) priv_key.write_private_key_file(filename, password=None) self.log.debug('{filename} saved.'.format(filename=filename)) # save public key, pub = RSAKey(filename=filename, password=None) with open('{0}.pub'.format(filename,), 'w') as fp: fp.write("{0} {1}".format(pub.get_name(), pub.get_base64())) self.log.debug('{filename}.pub saved.'.format(filename=filename)) return priv_key
def generate_key(host: str, key_type: KeyType = KeyType.RSA) -> str: """Generates a new private-public key pair and returns the path to the private key. Private key is saved in a directory determined by :func:`get_free_private_key_location`. :param host: Host name for identification purposes. :param key_type: Key type to generate. """ if key_type != KeyType.RSA: raise NotImplementedError("Only RSA keys are supported for now.") key = RSAKey.generate(bits=RSA_BITS) private_key_location = get_free_private_key_location(key_type=key_type) key.write_private_key_file(filename=private_key_location) public_key = RSAKey(filename=private_key_location) now_down_to_minutes = datetime.datetime.now().isoformat()[:16] comment = "idact/{host}/{now_down_to_minutes}".format( host=host, now_down_to_minutes=now_down_to_minutes) public_key_value = "{name} {base64} {comment}".format( name=public_key.get_name(), base64=public_key.get_base64(), comment=comment) public_key_location = get_public_key_location( private_key_location=private_key_location) with open(public_key_location, 'w') as file: file.write(public_key_value) return private_key_location
def clean(self): data = super().clean() key_type = data.get('key_type') public_key = data.get('public_key') try: if key_type == "ssh-rsa": k = RSAKey(data=base64.b64decode(public_key)) elif key_type == "ssh-dss": k = DSSKey(data=base64.b64decode(public_key)) elif key_type.startswith('ecdsa'): k = ECDSAKey(data=base64.b64decode(public_key)) else: raise forms.ValidationError( _("Unsupport key type: %(keytype)s"), code='invalid keytype', params={'key_type': key_type} ) data['key_type'] = k.get_name() data['public_key'] = k.get_base64() except (TypeError, SSHException, UnicodeDecodeError) as err: if len(public_key) > 30: body = public_key[0:30] else: body = public_key raise forms.ValidationError( _("Body of SSH public key is invalid:\n%(body)s\n" "Error: %(err)s"), code='invalid key body', params={'body': body + "...", 'err': err} ) return data
from paramiko import RSAKey filename = 'mytestkey' # generating private key prv = RSAKey.generate(bits=2048) prv.write_private_key_file(filename) # generating public key pub = RSAKey(filename=filename) with open("%s.pub" % filename, "w") as f: f.write("%s %s" % (pub.get_name(), pub.get_base64()))