Created
September 26, 2022 15:41
-
-
Save marsyang1/0a2458a8d3031dfcadcd574cb3704780 to your computer and use it in GitHub Desktop.
Small Utility class for getting ssh connection remote host public key with md5_fingerprint
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
#!/usr/bin/env python3 | |
import paramiko | |
from sshpubkeys import SSHKey | |
# | |
# Small Utility class for getting ssh connection remote host public key | |
# for add Bitbucket pipeline ssh key with md5_fingerprint and sha256_fingerprint | |
# | |
def get_hostfile(host): | |
# 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() | |
port = "22" | |
address = host + ':' + port | |
# https://docs.paramiko.org/en/stable/api/transport.html | |
transport = paramiko.Transport(address) | |
transport.connect() | |
key = transport.get_remote_server_key() | |
keyname = key.get_name() | |
base64 = key.get_base64() | |
print(f"key type:{key.get_name()},key.base64:{base64}") | |
transport.close() | |
hostfile = Hostfile(hostname=host, public_key=base64, keytype=keyname) | |
hostfile = get_sshkey_fingerprint(hostfile) | |
return hostfile | |
# SSH Key library | |
# https://github.com/ojarva/python-sshpubkeys | |
# https://stackoverflow.com/questions/6682815/deriving-an-ssh-fingerprint-from-a-public-key-in-python | |
def get_sshkey_fingerprint(hostfile): | |
print(f"target hostfile:{hostfile.__dict__}") | |
key = SSHKey(hostfile.keytype + " " + hostfile.public_key) | |
md5_finger = key.hash_md5().replace("MD5:", "") | |
sha_finger = key.hash_sha256() | |
print(f"md5_fingerprint:{md5_finger}") | |
print(f"sha256_fingerprint:{sha_finger}") | |
hostfile.md5_fingerprint = md5_finger | |
hostfile.sha256_fingerprint = sha_finger | |
print(f"fingerprint:{hostfile}") | |
return hostfile | |
class Hostfile: | |
md5_fingerprint = '' | |
sha256_fingerprint = '' | |
def __init__(self, hostname, public_key, keytype): | |
self.hostname = hostname | |
self.public_key = public_key | |
self.keytype = keytype |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment