Last active
May 31, 2023 00:45
-
-
Save mihow/c963e1054aa3b2c24c56501ffcb26fb6 to your computer and use it in GitHub Desktop.
Import existing PEM file as EC2 Key Pair with boto3 & paramiko
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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