python 生成ssh秘钥对

        工作中要用到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
我最后是把公钥和私钥放在了一个字典里,你也可以根据需要生成文件,这个类还是很方便的

  • 2
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值