Skip to content

Instantly share code, notes, and snippets.

Embed
What would you like to do?
SSH Key Generation tool - made to run from command line, but I used it as a module when I wrote it
# PyKeyGen - Simplified SSH Key Generation
import getpass, os, sys
class PyKeyGen():
def __init__(self):
# Base Command To Use
self.baseCMD = 'ssh-keygen -t {0} -b {1} -C "{2}" -N "{3}" -f {4}'
self.sshDir = '~/.ssh/'
# Default SSH Key Settings
self.defaultFormat = 'rsa'
self.defaultBits = '2048'
self.defaultOU = 'cds'
self.defaultFileName = 'id_rsa'
# Available Options
self.availableFormats = ['dsa', 'ecdsa', 'ed25519', 'rsa', 'rsa1']
self.presetBits = ['1024', '2048', '4098']
# Acceptable Yes / No Arguments
self.yesStrings = ['y', 'ys', 'yes']
self.noStrings = ['n', 'no']
# Get all of the properties for the key
def getProperties(self):
userEmpty = True
shortNameEmpty = True
emptyPass = True
while emptyPass:
keyPass = getpass.getpass('Enter the password you would like to use: ')
#if not keyPass or len(keyPass) < 5:
# print('Password cannot be blank, and must be at least 5 characters!')
#if keyPass and len(keyPass) >= 5:
# emptyPass = False
emptyPass = False
self.keyPass = keyPass
self.bitStrength = raw_input('How many bits in the key would you like to create? [2048]: ')
if not self.bitStrength:
self.bitStrength = self.defaultBits
self.keyFormat = raw_input('What format would you like to use? [rsa]: ')
if not self.keyFormat:
self.keyFormat = self.defaultFormat
self.orgUnit = raw_input('What OU (Organizational Unit) is this key being generated for? [cds]: ')
if not self.orgUnit:
self.orgUnit = self.defaultOU
while userEmpty:
self.emailOrUsername = raw_input('What is the email address or username you wish to use for this key?: ')
if not self.emailOrUsername:
print('You must provide a value for this property!')
if self.emailOrUsername:
userEmpty = False
if self.emailOrUsername:
while shortNameEmpty:
self.shortName = raw_input('Provide a short name for the key\'s file name: ')
if not self.shortName:
print('You must provide a short name for the key file name. Under 10 chars is recommended.')
if self.shortName:
shortNameEmpty = False
self.assembledFileName = self.sshDir + self.orgUnit + '_' + self.shortName + '_' + self.defaultFileName
# Generate the SSH key pair
def genKeyPair(self):
keyGenCommand = self.baseCMD.format(self.keyFormat, self.bitStrength, self.emailOrUsername, self.keyPass, self.assembledFileName)
os.system(keyGenCommand)
def main():
pkg = PyKeyGen()
pkg.getProperties()
pkg.genKeyPair()
if __name__ == "__main__":
try:
main()
except KeyboardInterrupt:
print('\nProgram terminated by user (Ctrl+C)')
except Exception as e:
sys.exit('Unhandled Exception: ' + str(e))
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
You can’t perform that action at this time.