您的位置:首页 > 编程语言 > Python开发

python 生成ssh秘钥对

2016-07-25 15:53 696 查看
        工作中要用到ssh-keygen生成的公钥和私钥,查了很多网站,大部分人用的是Crypto.PublicKey包中的RSA类来模拟ssh-keygen生成秘钥对。偶然间发现paramiko也有一个可以用来生成秘钥对的类(
paramiko.rsakey.
RSAKey
),最后选择用paramiko的RSAKey来生成秘钥对。关于paramiko生成不同加密方式的秘钥对的详细信息,请到官网上看http://docs.paramiko.org/en/2.0/api/keys.html

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)

for data in [key.get_name(),
" ",
key.get_base64(),
" %s@%s" % ("magicstack", os.uname()[1])]:
sbuffer.write(data)
public_key = sbuffer.getvalue()
key_content['public_key'] = public_key
key_content['private_key'] = private_key
logger.info('gen_keys: key content:%s'%key_content)
return key_content
我最后是把公钥和私钥放在了一个字典里,你也可以根据需要生成文件,这个类还是很方便的
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签:  ssh python