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.

    Tags for this post: python paramiko host key
    Related posts: Implementing SCP with paramiko; Multiple file support with scp; paramiko exec_command timeout; Weird paramiko problem; Executing a command with paramiko; Packet capture in python

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