Skip to content

Instantly share code, notes, and snippets.

@Pristavkin
Last active May 25, 2020 05:51
Show Gist options
  • Save Pristavkin/e3d6b909d0745656064c7525942ca7e3 to your computer and use it in GitHub Desktop.
Save Pristavkin/e3d6b909d0745656064c7525942ca7e3 to your computer and use it in GitHub Desktop.
Python implementation of ssh-keyscan utility
#!/usr/bin/env python3
import argparse
import paramiko
import os.path
parser = argparse.ArgumentParser()
parser.add_argument('host', action='store', help='host to connect to')
parser.add_argument('-p', '--port', action='store', dest='port', default='22', help='port to connect to')
parser.add_argument('--known_hosts', action='store', dest='known_hosts', default='~/.ssh/known_hosts', help='known_hosts file')
args = parser.parse_args()
host = args.host
address = args.host+':'+args.port
if os.path.isfile(args.known_hosts):
known_hosts = args.known_hosts
else:
open(args.known_hosts, 'w').close()
known_hosts = args.known_hosts
transport = paramiko.Transport(address)
transport.connect()
key = transport.get_remote_server_key()
transport.close()
hostfile = paramiko.HostKeys(filename=known_hosts)
hostfile.add(hostname = host, key=key, keytype=key.get_name())
hostfile.save(filename=known_hosts)
@bitinerant
Copy link

Very helpful - thanks! I found a bug though. Line 23 should be: transport = paramiko.Transport((host, port)), i.e. the first parameter is a tuple. See paramiko.Transport. As it is, I think you're setting the default_window_size!

@Pristavkin
Copy link
Author

@bitinerant, thank you for your reply!
All fixed up!

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment