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):

      # 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)
      key = t.get_remote_server_key()
      print '%s %s' %(key.get_name(),
                      base64.encodestring(key.__str__()).replace('\n', ''))

    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: paramiko exec_command timeout; Executing a command with paramiko; Implementing SCP with paramiko; Weird paramiko problem; Multiple file support with scp; Terrible pong

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