extracting key for authorized_keys key from ssh2 public key in python

2.3k views Asked by At

I am trying to extract the needed key for the authorized_keys file. It is different than what i get when i open the key file (.pub). This is my code so far. Whenever I try to run it on a pubfile i get an invalid syntax pointing to SSH2 in the first line of the file. "---- BEGIN SSH2 PUBLIC KEY ----" I don't know why this isn't working. Thanks in advance for any help

#!/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

There are 1 answers

0
Jeffrey Bauer On

Here's my rewrite of your code, sans comments:

#!/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)

Assuming the module was named parsepub.py, it would be executed thus:

$ python parsepub.py id_rsa.pub