python 生成ssh秘钥对
2016-07-25 15:53
696 查看
工作中要用到ssh-keygen生成的公钥和私钥,查了很多网站,大部分人用的是Crypto.PublicKey包中的RSA类来模拟ssh-keygen生成秘钥对。偶然间发现paramiko也有一个可以用来生成秘钥对的类(
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
我最后是把公钥和私钥放在了一个字典里,你也可以根据需要生成文件,这个类还是很方便的
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
我最后是把公钥和私钥放在了一个字典里,你也可以根据需要生成文件,这个类还是很方便的
相关文章推荐
- Python动态类型的学习---引用的理解
- Python3写爬虫(四)多线程实现数据爬取
- 垃圾邮件过滤器 python简单实现
- 下载并遍历 names.txt 文件,输出长度最长的回文人名。
- Linux Generating SSH Keys
- install and upgrade scrapy
- Scrapy的架构介绍
- Centos6 编译安装Python
- 使用Python生成Excel格式的图片
- 让Python文件也可以当bat文件运行
- [Python]推算数独
- Python中zip()函数用法举例
- Python中map()函数浅析
- Python将excel导入到mysql中
- Python在CAM软件Genesis2000中的应用
- 使用Shiboken为C++和Qt库创建Python绑定
- FREEBASIC 编译可被python调用的dll函数示例