def __init__(self, hostname, port=22, username='******', pkey=None, password=None, default_env=None, connect_timeout=10): self.stdout = None self.client = None self.channel = None self.sftp = None self.eof = 'Spug EOF 2108111926' self.already_init = False self.default_env = self._make_env_command(default_env) self.regex = re.compile(r'Spug EOF 2108111926 (-?\d+)[\r\n]?') self.arguments = { 'hostname': hostname, 'port': port, 'username': username, 'password': password, 'pkey': RSAKey.from_private_key(StringIO(pkey)) if isinstance(pkey, str) else pkey, 'timeout': connect_timeout, 'banner_timeout': 30 }
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)
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
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)
def connect(self): """ Открываем низкоуровневое соединение """ self.logger.debug( u'Open SSH connection {server} (reuse={reuse})'.format( server=self.server_name, reuse=self.reuse_connection)) ssh = paramiko.SSHClient() ssh.set_missing_host_key_policy(paramiko.AutoAddPolicy()) if self.pkey: rsakey = RSAKey.from_private_key(StringIO(self.pkey)) ssh.connect(hostname=self.hostname, port=self.port, username=self.username, pkey=rsakey, timeout=self.timeout) else: ssh.connect(hostname=self.hostname, port=self.port, username=self.username, password=self.password, timeout=self.timeout) ssh.get_transport().window_size = 1024**2 # Возвращаем соединение self.ssh = ssh
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=0755) 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)
def save_key_to_file(private_key, public_key, password=None, key_dir='/tmp'): """ read the key string and save it to an file. :param private_key: <str> private key :param public_key: <str> public key :param password: the private key password :param key_dir: the directory to save keys :return: (<str>, <str>), (private key file path, public key file path) """ private = StringIO() private.write(private_key) private.seek(0) if not os.path.exists(key_dir): os.mkdir(key_dir) private_file = os.path.join(key_dir, 'id_rsa') public_file = os.path.join(key_dir, 'id_rsa.pub') key = RSAKey.from_private_key(private, password) key.write_private_key_file(private_file, password) with open(public_file, 'w') as f: f.write(public_key) f.flush() return private_file, public_file
def get_file(url): """ sftp://Some_Compute_UUID/relative/path/from/base_path/file.fastq.gz :param url: :type url: :return: :rtype: """ url = urlparse(url) scheme = url.scheme compute_id = url.host compute = ComputeResource.objects.get(id=compute_id) host = compute.hostname port = compute.port if port is None: port = 22 private_key = compute.private_key username = compute.extra.get('username') base_dir = compute.extra.get('base_dir') params = dict(port=port, username=username, pkey=RSAKey.from_private_key(StringIO(private_key))) storage = SFTPStorage(host=host, params=params) return storage.open(path.join(base_dir, url.path))
def __init__(self, hostname, port=SSH_PORT, username='******', pkey=None, password=None, connect_timeout=10): if pkey is None and password is None: raise Exception( 'public key and password must have one is not None') self.client = None self.arguments = { 'hostname': hostname, 'port': port, 'username': username, 'password': password, 'pkey': RSAKey.from_private_key(StringIO(pkey)) if isinstance(pkey, str) else pkey, 'timeout': connect_timeout, }
def parse_private_key(private_key): try: return RSAKey.from_private_key(StringIO(private_key)) except SSHException: try: return DSSKey.from_private_key(StringIO(private_key)) except SSHException: return None
def create_rsa_key(private_key): """ Creates the RSAKey for paramiko. :param private_key: String version of the private key :return: The RSAKey object to be used in paramiko """ fobj = cStringIO.StringIO(private_key) key = RSAKey.from_private_key(file_obj=fobj) return key
def login_key(run_id): filename = 'import-private-key-%s.pem' % (run_id,) if not os.path.exists(filename): return None with open(filename) as fh: return RSAKey.from_private_key(fh)
def get_ssh_client(hostname, port): ssh_client = SSHClient() ssh_client.set_missing_host_key_policy(AutoAddPolicy) ssh_client.connect(hostname, port=port, username='******', pkey=RSAKey.from_private_key( StringIO(Setting.ssh_private_key))) return ssh_client
def test_gen_and_sign(): ca_buf = StringIO(TEST_RSA_CA) ca_key = RSAKey.from_private_key(ca_buf) cert_file = open('/home/mike/.ssh/id_rsa', 'r') cert_key = RSAKey.from_private_key(cert_file) crt = SSHCertificate(key=cert_key) crt.type = SSH_CERT_TYPE_USER crt.key_id = 'testcert' crt.valid_after = 0 crt.valid_before = 2**64 - 1 crt.principals.append('mike') crt.extensions['permit-X11-forwarding'] = '' crt.extensions['permit-agent-forwarding'] = '' crt.extensions['permit-port-forwarding'] = '' crt.extensions['permit-pty'] = '' crt.extensions['permit-user-rc'] = '' crt.sign(ca_key, 'randomdata') return base64.b64encode(crt.asbytes())
def test_sftp_key_connect(self): server_interface = MyTServerInterface() pub_key_str = ( "AAAAB3NzaC1yc2EAAAADAQABAAAAgQCzvWE391K1pyBvePGpwDWMboSLIp" "5L5sMq+bXPPeJPSLOm9dnm8XexZOpeg14UpsYcmrkzVPeooaqz5PqtaHO46CdK11dS" "cs2a8PLnavGkJRf25/PDXxlHkiZXXbAfW+6t5aVJxSJ4Jt4FV0aDqMaaYxy4ikw6da" "BCkvug2OZQqQ==" ) priv_key_str = u"""-----BEGIN RSA PRIVATE KEY----- MIICXgIBAAKBgQCzvWE391K1pyBvePGpwDWMboSLIp5L5sMq+bXPPeJPSLOm9dnm 8XexZOpeg14UpsYcmrkzVPeooaqz5PqtaHO46CdK11dScs2a8PLnavGkJRf25/PD XxlHkiZXXbAfW+6t5aVJxSJ4Jt4FV0aDqMaaYxy4ikw6daBCkvug2OZQqQIDAQAB AoGASpK9XlIQD+wqafWdFpf3368O8QdI9CbnPNJkG3sKhWidmR0R7l6rEX/UOah5 hUn4km+jfWe4ZU/GGmNbmkznDdOWspDKs7eeYl7saeRzuX2CdTVvrdU7qmD5+JLk mXlWWd6rgRIfrFYXYeDVd8p6/kPR4SJe7dTTHuEKKIt9njECQQDhMqjyoNxftpl4 +mwQu0ZDLCZ4afDCGcsf73W3oSmqLyf401vQ6KAp/PmfxqGXY0ewGMzUJn9LFOyP WOGcDFglAkEAzFL/DI3SYmsvLMt6/vK4qwEwSiJU8byUBj3CL3eL0xjn895GXPzb 9CUMu0fz60Tn7UhbohynPLmQ2w6npbZ9NQJBAN+uujGFpl9LuFV6KCzWV4wRJoUk dYfWpvQpnfuvkPsBq+pzxhdTeQM7y5bwbUE509MOTyXKt1WUiwQ3fKDLgiECQQCb Z4zhSYT4ojlRQrqb6pSWS+Mkn5QoAJw9Wv+1BqHsvwa8rxSpaREKUpuqXgGhsdkM 2noHhO+V+jW4xx6vpWr5AkEAgHoSbQUR5uY8ib3N3mNowVi9NhvBN1FkwGStM9W8 QKHf8Ha+rOx3B7Dbljc+Xdpcn9VyRmDlSqzX9aCkr18mNg== -----END RSA PRIVATE KEY-----""" private_key = RSAKey.from_private_key(file_obj=StringIO(priv_key_str)) # Fail if public key not registered self.assertEqual( server_interface.check_auth_publickey(self.username, private_key), AUTH_FAILED ) pub_key_rec = SFTPPublicKey.objects.create( user = self.user, name = "TestKey", key_type = "ssh-rsa", public_key = pub_key_str ) # Succeed if public key is registered self.assertEqual( server_interface.check_auth_publickey(self.username, private_key), AUTH_SUCCESSFUL ) # Should fail if user is inactive self.user.is_active = False self.user.save() self.assertEqual( server_interface.check_auth_publickey(self.username, private_key), AUTH_FAILED ) self.user.is_active = True self.user.save()
def test_sftp_key_connect(self): server_interface = MyTServerInterface() pub_key_str = ( "AAAAB3NzaC1yc2EAAAADAQABAAAAgQCzvWE391K1pyBvePGpwDWMboSLIp" "5L5sMq+bXPPeJPSLOm9dnm8XexZOpeg14UpsYcmrkzVPeooaqz5PqtaHO46CdK11dS" "cs2a8PLnavGkJRf25/PDXxlHkiZXXbAfW+6t5aVJxSJ4Jt4FV0aDqMaaYxy4ikw6da" "BCkvug2OZQqQ==" ) priv_key_str = """-----BEGIN RSA PRIVATE KEY----- MIICXgIBAAKBgQCzvWE391K1pyBvePGpwDWMboSLIp5L5sMq+bXPPeJPSLOm9dnm 8XexZOpeg14UpsYcmrkzVPeooaqz5PqtaHO46CdK11dScs2a8PLnavGkJRf25/PD XxlHkiZXXbAfW+6t5aVJxSJ4Jt4FV0aDqMaaYxy4ikw6daBCkvug2OZQqQIDAQAB AoGASpK9XlIQD+wqafWdFpf3368O8QdI9CbnPNJkG3sKhWidmR0R7l6rEX/UOah5 hUn4km+jfWe4ZU/GGmNbmkznDdOWspDKs7eeYl7saeRzuX2CdTVvrdU7qmD5+JLk mXlWWd6rgRIfrFYXYeDVd8p6/kPR4SJe7dTTHuEKKIt9njECQQDhMqjyoNxftpl4 +mwQu0ZDLCZ4afDCGcsf73W3oSmqLyf401vQ6KAp/PmfxqGXY0ewGMzUJn9LFOyP WOGcDFglAkEAzFL/DI3SYmsvLMt6/vK4qwEwSiJU8byUBj3CL3eL0xjn895GXPzb 9CUMu0fz60Tn7UhbohynPLmQ2w6npbZ9NQJBAN+uujGFpl9LuFV6KCzWV4wRJoUk dYfWpvQpnfuvkPsBq+pzxhdTeQM7y5bwbUE509MOTyXKt1WUiwQ3fKDLgiECQQCb Z4zhSYT4ojlRQrqb6pSWS+Mkn5QoAJw9Wv+1BqHsvwa8rxSpaREKUpuqXgGhsdkM 2noHhO+V+jW4xx6vpWr5AkEAgHoSbQUR5uY8ib3N3mNowVi9NhvBN1FkwGStM9W8 QKHf8Ha+rOx3B7Dbljc+Xdpcn9VyRmDlSqzX9aCkr18mNg== -----END RSA PRIVATE KEY-----""" private_key = RSAKey.from_private_key(file_obj=StringIO(priv_key_str)) # Fail if public key not registered self.assertEqual( server_interface.check_auth_publickey(self.username, private_key), AUTH_FAILED ) SFTPPublicKey.objects.create( user = self.user, name = "TestKey", key_type = "ssh-rsa", public_key = pub_key_str ) # Succeed if public key is registered self.assertEqual( server_interface.check_auth_publickey(self.username, private_key), AUTH_SUCCESSFUL ) # Should fail if user is inactive self.user.is_active = False self.user.save() self.assertEqual( server_interface.check_auth_publickey(self.username, private_key), AUTH_FAILED ) self.user.is_active = True self.user.save()
def _exec_ssh_cmd(self, cmdline): pkey_buf = StringIO(self.state.pkey) client = SSHClient() client.set_missing_host_key_policy(AutoAddPolicy()) client.connect(self.droplet_ip, username='******', pkey=RSAKey.from_private_key(pkey_buf)) stdin, stdout, stderr = client.exec_command(cmdline) for line in stdout: logging.info(line) for line in stderr: logging.info(line)
def execute(build_directory, source, params): # Add some validation to see if we can find the pydist file first? # Load up the private key for the connection private_key = RSAKey.from_private_key( io.StringIO(source["ssh_private_key"])) # Construct package directory package_directory = os.path.join(build_directory, params["package_directory"]) log_output("Connecting to {}".format(source["ssh_host"])) # connect to the Server ssh = SSHClient() ssh.set_missing_host_key_policy(AutoAddPolicy) ssh.connect(hostname=source["ssh_host"], port=source["ssh_port"], username=source["ssh_user"], pkey=private_key, look_for_keys=False, allow_agent=False) log_output("Connected to {}. Copying over artifiacts from: {}".format( source["ssh_host"], package_directory)) # Before we copy over the file, delete the pydeployer-tmp folder, as SCP's behaviour changes if it already exists # TODO: pydeployer-tmp should be pulled out into a variable and input config execute_command(ssh, "rm -r ~/pydeployer-tmp") def scp_progress(filename, size, sent): sys.stderr.write("%s's progress: %.2f%% \r" % (filename, float(sent) / float(size) * 100)) # Copy over the pydist package with SCPClient(ssh.get_transport(), progress=scp_progress) as scp: scp.put(package_directory, recursive=True, remote_path="~/pydeployer-tmp") log_output("Copied artifacts. Executing deployment") # Install the package # TODO: Add some validation around running these commands execute_command(ssh, "pydeployer deploy *.pydist", working_directory="~/pydeployer-tmp") log_output("Deployment done. Terminating SSH connection.") # Close out the ssh connection ssh.close() version = read_version_from_file(build_directory, params["version_file"]) return {"version": {"version": version}}
def assignKey(self, key): self.origKey = key # dump key to file self.dumpKey(self.keyPath, self.origKey) try: self._pkey = RSAKey.from_private_key(StringIO(self.origKey)) except paramiko.SSHException: try: self._pkey = DSSKey.from_private_key(StringIO(self.origKey)) except paramiko.SSHException: raise "Unknown private key format"
def key_pair(self): """(:class:`boto.ec2.keypair.KeyPair`) The EC2 key pair matched to :attr:`private_key`. """ try: return self._key_pair except AttributeError: self._key_pair = self.ec2_connection.create_key_pair(self.key_name) private_key = str(self._key_pair.material) self._private_key = RSAKey.from_private_key(io.BytesIO(private_key)) self._create_github_deploy_key()
def ssh_ping(hostname, port): ssh_client = SSHClient() ssh_client.set_missing_host_key_policy(AutoAddPolicy) try: ssh_client.connect(hostname, port=port, username='******', pkey=RSAKey.from_private_key( StringIO(Setting.ssh_private_key))) except AuthenticationException: return False ssh_client.close() return True
def key_pair(self): """(:class:`boto.ec2.keypair.KeyPair`) The EC2 key pair matched to :attr:`private_key`. """ try: return self._key_pair except AttributeError: self._key_pair = self.ec2_connection.create_key_pair(self.key_name) private_key = str(self._key_pair.material) self._private_key = RSAKey.from_private_key( io.BytesIO(private_key)) self._create_github_deploy_key()
def clean(self): """Ensures that self is a valid RSA keypair.""" from Crypto import Random Random.atfork() # Generate public key from private key file. try: key = RSAKey.from_private_key(io.StringIO(self.private)) self.public = 'ssh-rsa ' + key.get_base64() except Exception: log.exception("Error while constructing public key " "from private.") raise me.ValidationError("Private key is not a valid RSA key.")
def test_sign_ecdsa_key(): """ Round trip a certificate through the parser and signer. It should result in the same sequence of bytes after the signing. """ ca_buf = StringIO(TEST_RSA_CA) ca_key = RSAKey.from_private_key(ca_buf) crt_data = base64.b64decode(TEST_ECDSA_KEY_RSA_CA) crt = SSHCertificate(data=crt_data) assert crt.signature_key == ca_key.asbytes() crt._bytes = None assert crt._bytes != crt_data crt.sign(ca_key, crt.nonce) assert crt._bytes == crt_data
def create_login_key(ec2, run_id, key_pair_name): try: ec2.delete_key_pair(KeyName=key_pair_name) except ClientError as e: if e.response['Error']['Code'] != 'NotFound': raise response = ec2.create_key_pair(KeyName=key_pair_name) pem = response['KeyMaterial'] key = RSAKey.from_private_key(BytesIO(pem)) filename = 'import-private-key-%s.pem' % (run_id,) with open(filename, 'w') as fh: key.write_private_key(fh) return key
def create_ssh_key_for_bitbucket(env_name): """ Creates an SSH key, deploys it to bitbucket for bulbasaur, then returns the private key. """ import requests from requests.auth import HTTPBasicAuth import json import StringIO from paramiko.rsakey import RSAKey logger.debug("generating RSA keypair") private_key = RSAKey.generate(4096) private_key_file = StringIO.StringIO() private_key.write_private_key(private_key_file) private_key_file.seek(0) public_key = RSAKey.from_private_key(private_key_file) public_key_str = "%s %s" % (public_key.get_name(), public_key.get_base64()) # rewind the private_key_file private_key_file.seek(0) logger.debug("successfully generated RSA keypair") bitbucket_url = "https://api.bitbucket.org/1.0/repositories/importthis/bulbasaur/deploy-keys/" bitbucket_payload = json.dumps({ 'label': 'bulbasaur-deploy-%s' % env_name, 'key': public_key_str }) auth = HTTPBasicAuth(os.environ['BITBUCKET_ID'], os.environ['BITBUCKET_PASSWORD']) headers = {'content-type': 'application/json'} params = {'format': 'json'} response = requests.post(bitbucket_url, data=bitbucket_payload, verify=True, auth=auth, params=params, headers=headers) logger.debug("updating bulbasaur deploy keys") if response.status_code != 200: logger.debug(response.text) raise Exception("Bitbucket deploy key creation was not successful") logger.debug("bulbasaur deploy keys successfully updated!") return private_key_file
def connect(self): """ Открываем низкоуровневое соединение """ self.logger.debug(u'Open SSH connection {server} (reuse={reuse})'.format( server=self.server_name, reuse=self.reuse_connection)) ssh = paramiko.SSHClient() ssh.set_missing_host_key_policy(paramiko.AutoAddPolicy()) if self.pkey: rsakey = RSAKey.from_private_key(StringIO(self.pkey)) ssh.connect(hostname=self.hostname, port=self.port, username=self.username, pkey=rsakey, timeout=self.timeout) else: ssh.connect(hostname=self.hostname, port=self.port, username=self.username, password=self.password, timeout=self.timeout) ssh.get_transport().window_size = 1024**2 # Возвращаем соединение self.ssh = ssh
def connect(self, host, user, ssh_key=None, port=22, timeout=30, term='ansi', pty_width=80, pty_height=24): try: ssh_client = paramiko.SSHClient() ssh_client.set_missing_host_key_policy(paramiko.AutoAddPolicy()) key = RSAKey.from_private_key(StringIO(ssh_key)) if isinstance( ssh_key, str) else ssh_key ssh_client.connect(username=user, hostname=host, port=port, pkey=key, timeout=timeout) transport = ssh_client.get_transport() self.channel = transport.open_session() self.channel.get_pty(term=term, width=pty_width, height=pty_height) self.channel.invoke_shell() for i in range(2): recv = self.channel.recv(1024).decode('utf-8') self.message['status'] = 0 self.message['message'] = recv message = json.dumps(self.message) self.websocker.send(message) self.res += recv # 创建3个线程将服务器返回的数据发送到django websocket(1个线程都可以) Thread(target=self.websocket_to_django).start() except: self.message['status'] = 2 self.message['message'] = 'connection faild...' message = json.dumps(self.message) self.websocker.send(message) self.websocker.close(3001)
def create_ssh_key_for_bitbucket(env_name): """ Creates an SSH key, deploys it to bitbucket for bulbasaur, then returns the private key. """ import requests from requests.auth import HTTPBasicAuth import json import StringIO from paramiko.rsakey import RSAKey logger.debug("generating RSA keypair") private_key = RSAKey.generate(4096) private_key_file = StringIO.StringIO() private_key.write_private_key(private_key_file) private_key_file.seek(0) public_key = RSAKey.from_private_key(private_key_file) public_key_str = "%s %s" % (public_key.get_name(), public_key.get_base64()) # rewind the private_key_file private_key_file.seek(0) logger.debug("successfully generated RSA keypair") bitbucket_url = "https://api.bitbucket.org/1.0/repositories/importthis/bulbasaur/deploy-keys/" bitbucket_payload = json.dumps({'label': 'bulbasaur-deploy-%s' % env_name, 'key': public_key_str}) auth = HTTPBasicAuth(os.environ['BITBUCKET_ID'], os.environ['BITBUCKET_PASSWORD']) headers = {'content-type': 'application/json'} params = {'format': 'json'} response = requests.post(bitbucket_url, data=bitbucket_payload, verify=True, auth=auth, params=params, headers=headers) logger.debug("updating bulbasaur deploy keys") if response.status_code != 200: logger.debug(response.text) raise Exception("Bitbucket deploy key creation was not successful") logger.debug("bulbasaur deploy keys successfully updated!") return private_key_file
def gen_keys(key=""): """ 生成公钥 私钥 """ output = StringIO.StringIO() sbuffer = StringIO.StringIO() key_content = {} if not key: try: key = RSAKey.generate(2048) key.write_private_key(output) private_key = output.getvalue() except IOError: raise IOError('gen_keys: there was an error writing to the file') except SSHException: raise SSHException('gen_keys: the key is invalid') else: private_key = key output.write(key) try: key = RSAKey.from_private_key(output) except SSHException, e: raise SSHException(e)
def gen_keys_by_name(key="", key_path_dir="", name=""): """ 在KEY_DIR下创建一个以用户名命名的目录, 并且在该目录下 生产一对秘钥 :return: 返回目录名(uuid) """ key_basename = name 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') config_file = os.path.join(key_path_dir, 'config') mkdir(key_path_dir, mode=0755) if not key: key = RSAKey.generate(2048) key.write_private_key_file(private_key) config_content = [ 'StrictHostKeyChecking no\n', 'UserKnownHostsFile /dev/null\n', 'GSSAPIAuthentication no\n' ] config = file(config_file, 'w') for c in config_content: config.write(c) config.close() 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)
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 as e: shutil.rmtree(key_path_dir, ignore_errors=True) raise SSHException(e) os.chmod(private_key, 0o644) with open(public_key, 'w') as content_file: for data in [ key.get_name(), " ", key.get_base64(), " %s@%s" % ("jumpserver", os.uname()[1]) ]: content_file.write(data) return key_path_dir
def gen_keys(key="", name='unknown'): from paramiko import SSHException from paramiko.rsakey import RSAKey """ 生成公钥 私钥 """ output = StringIO() sbuffer = StringIO() key_content = {} if not key: try: key = RSAKey.generate(2048) key.write_private_key(output) private_key = output.getvalue() except IOError: raise IOError('gen_keys: there was an error writing to the file') except SSHException: raise SSHException('gen_keys: the key is invalid') else: private_key = key output.write(key) try: key = RSAKey.from_private_key(output) except SSHException as e: raise SSHException(e) for data in [key.get_name(), " ", key.get_base64(), " %s@%s" % (name, os.uname()[1])]: sbuffer.write(data) public_key = sbuffer.getvalue() key_content['public_key'] = public_key key_content['private_key'] = private_key return key_content
def create_key(s): f = StringIO() f.write(s) f.seek(0) return RSAKey.from_private_key(file_obj=f, password=None)
""" output = StringIO.StringIO() sbuffer = StringIO.StringIO() key_content = {} if not key: try: key = RSAKey.generate(2048) key.write_private_key(output) private_key = output.getvalue() except Exception, ex: return False, str(ex) else: private_key = key output.write(key) try: key = RSAKey.from_private_key(output) except Exception, e: return False, str(e) for data in [ key.get_name(), " ", key.get_base64(), " %s@%s" % ("magicstack", os.uname()[1]) ]: sbuffer.write(data) public_key = sbuffer.getvalue() public_key_arr = public_key.split(" ") public_key_arr[-1] = emial key_content['public_key'] = " ".join(public_key_arr) key_content['private_key'] = private_key return True, key_content
def as_pkey(self: 'KeyPair') -> RSAKey: private_key = StringIO(self.private_key) return RSAKey.from_private_key(private_key)