Skip to content

Instantly share code, notes, and snippets.

@mihow
Last active Jan 30, 2019
Embed
What would you like to do?
Import existing PEM file as EC2 Key Pair with boto3 & paramiko
import os
import base64
import struct
import boto3
import paramiko
from paramiko.util import deflate_long
PEM_FILEPATH = '~/.ssh/test-key.pem'
ec2 = boto2.resource('ec2')
key = paramiko.RSAKey.from_private_key_file(PEM_FILEPATH)
output = b''
parts = [b'ssh-rsa', deflate_long(key.public_numbers.e), deflate_long(key.public_numbers.n)]
for part in parts:
output += struct.pack('>I', len(part)) + part
public_key = b'ssh-rsa ' + base64.b64encode(output) + b'\n'
# alternatively? : printable_key = '%s %s' %(key.get_name(), base64.b64encode(key.asbytes()).replace('\n', ''))
key_name = os.path.splitext(os.path.basename(PEM_FILEPATH))[0]
aws_key_pair = ec2.import_key_pair(KeyName=key_name, PublicKeyMaterial=public_key)
aws_key_pair.delete()
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment