Skip to content

Instantly share code, notes, and snippets.

@arielzn
Created March 4, 2020 15:22
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save arielzn/ae220ec7b354c49d8e0aa9f48a736ed9 to your computer and use it in GitHub Desktop.
Save arielzn/ae220ec7b354c49d8e0aa9f48a736ed9 to your computer and use it in GitHub Desktop.
#!/usr/bin/env python3
import os
import socket
import logging
import paramiko
import argparse
def create_ssh_client(hostname):
"""Create a paramiko ssh_client object for a 'hostname' that is defined on
the ~/.ssh/config file and ssh keys are used to authenticate"""
config = paramiko.config.SSHConfig()
config.parse(open(os.path.expanduser('~/.ssh/config')))
host = config.lookup(hostname)
params = {}
params["timeout"] = 5
for key in host.keys():
if key == "hostname":
params[key] = host[key]
elif key == "user":
params["username"] = host[key]
elif key == "port":
params[key] = int(host[key])
elif key == "identityfile":
params["key_filename"] = host[key][0]
client = paramiko.SSHClient()
client.load_system_host_keys()
client.set_missing_host_key_policy(paramiko.RejectPolicy())
try:
client.connect(**params)
except socket.timeout:
logging.error("Connection timed out for host '{0}'"
.format(hostname))
return None
except socket.gaierror:
logging.exception("Connection error: if [Errno -2] the host '{0}'"
"is not found in ssh_config\n".format(hostname))
return None
except paramiko.SSHException as e:
logging.exception("Connection error on '{0}': {1}".format(hostname, e))
return None
return client
def check_remote_hostname(remote):
ssh_client = create_ssh_client(remote)
stdin, stdout, stderr = ssh_client.exec_command('hostname')
if stdout.channel.recv_exit_status() == 0:
out = stdout.readlines()
print(out[0])
else:
print("Error running 'hostname' command on {0}".format(remote))
if __name__ == '__main__':
parser = argparse.ArgumentParser(
description='Print a remote ssh server hostname (ssh authentication'
' already setup on ssh_config)')
parser.add_argument('server', type=str, help='remote server hostname as'
' in your ssh_config')
args = parser.parse_args()
remote = args.server
check_remote_hostname(remote)
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment