python 生成ssh秘钥对

来源:互联网 发布:淘宝订单没有代付选项 编辑:程序博客网 时间:2024/06/05 04:13

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

0 0
原创粉丝点击