Calculating a SSH host key with paramiko

    I needed to compare a host key from something other than a known_hosts file with what paramiko reports as part of the SSH connection today. If you must know, the host keys for these machines are retrieved a XMLRPC API... It turned out to be a lot easier than I thought. Here's how I produced the host key entry as it appears in that API (as well as in the known_hosts file):

      
      #!/usr/bin/python
      
      
      
      # A host key calculation example for Paramiko.
      
      # Args:
      
      #   1: hostname
      
      
      
      import base64
      
      import os
      
      import paramiko
      
      import socket
      
      import sys
      
      
      
      # Socket connection to remote host
      
      sock = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
      
      sock.connect((sys.argv[1], 22))
      
      
      
      # Build a SSH transport
      
      t = paramiko.Transport(sock)
      
      t.start_client()
      
      key = t.get_remote_server_key()
      
      
      
      print '%s %s' %(key.get_name(),
      
                      base64.encodestring(key.__str__()).replace('\n', ''))
      
      
      
      t.close()
      
      sock.close()
      
      


    Note that I could also have constructed a paramiko key object based on the output of the XMLRPC API and then compared those two objects, but I prefer the human readable strings.

posted at: 16:28 | path: /python/paramiko | permanent link to this entry

    Add a comment to this post:

    Your name:

    Your email: Email me new comments on this post
      (Your email will not be published on this site, and will only be used to contact you directly with a reply to your comment if needed. Oh, and we'll use it to send you new comments on this post it you selected that checkbox.)


    Your website:

    Comments: