从python中的ssh2公钥中提取authorized_keys键的密钥

时间:2014-01-16 21:24:26

标签: python public-key-encryption public-key authorized-keys

我正在尝试为authorized_keys文件提取所需的密钥。它与我打开密钥文件(.pub)时得到的不同。到目前为止这是我的代码。每当我尝试在pubfile上运行它时,我会在文件的第一行中找到指向SSH2的无效语法。 “----开始SSH2公共密钥----”我不知道为什么这不起作用。在此先感谢您的任何帮助

#!/bin/env python

import fileinput
import subprocess
import sys



def parse_pubkey( pubfile ):
    """This routine returns the key-type and key from a public-key file.
    """
    try:
        # try to parse the Windows-format file into an OpenSSH-compatible representation
        # by calling the Unix "ssh-keygen" utility. This call will fail if the keyfile
        # is already in OpenSSH format
        keystr = subprocess.check_output( 'ssh-keygen -i -f %s 2>/dev/null' % pubfile,    shell=True )

    except subprocess.CalledProcessError:
        # we caught an exception, so the file must already be in OpenSSH format.  Just
        # read in the contents
        keystr = open( pubfile, 'r' ).read()

    # now split the resulting string on whitespace and return the first two fields
    return keystr.split()[0:2]


parse_pubkey(pubfilename.pub)

1 个答案:

答案 0 :(得分:1)

这是我对你的代码的重写,没有评论:

#!/usr/bin/env python

import subprocess
import sys

def parse_pubkey(pubfile):
    """Return the key-type and key from a public-key file.
    """
    try:
        keystr = subprocess.check_output(
            'ssh-keygen -i -f %s 2>/dev/null' % pubfile,
            shell=True)
    except subprocess.CalledProcessError:
        with open(pubfile) as f:
            keystr = f.read()
    return keystr.split()[0:2]

if __name__ == '__main__':
    pubfilename = sys.argv[1]
    print parse_pubkey(pubfilename)

假设模块名为parsepub.py,它将被执行:

  

$ python parsepub.py id_rsa.pub