Skip to content

Instantly share code, notes, and snippets.

@mihow
Last active May 31, 2023 00:45
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 2 You must be signed in to fork a gist
  • Save mihow/c963e1054aa3b2c24c56501ffcb26fb6 to your computer and use it in GitHub Desktop.
Save mihow/c963e1054aa3b2c24c56501ffcb26fb6 to your computer and use it in GitHub Desktop.
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