Skip to content

Instantly share code, notes, and snippets.

@arielzn
Last active December 12, 2017 06:40
Show Gist options
  • Star 1 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save arielzn/3915a07d50169f98d65c71a681906f6a to your computer and use it in GitHub Desktop.
Save arielzn/3915a07d50169f98d65c71a681906f6a to your computer and use it in GitHub Desktop.
Running commands with paramiko on remote hosts defined on ssh_config
#!/usr/bin/env python
import os
import paramiko
import argparse
import socket
import logging
def create_ssh_client(hostname):
"""Create a paramiko ssh_client object for a 'hostname' defined on
the ~/.ssh/config file and public ssh key authentication used"""
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
if __name__ == '__main__':
parser = argparse.ArgumentParser(
description='This script will run a command in a remote host with \
ssh access (login information to host must be defined in \
~/.ssh/config file and pubkey authentication setup)')
parser.add_argument('host', type=str, help='remote host with ssh access')
parser.add_argument('command', type=str, help='command to run')
args = parser.parse_args()
host = args.host
command = args.command
ssh = create_ssh_client(host)
stdin, stdout, stderr = ssh.exec_command(command)
err = stderr.readlines()
out = stdout.readlines()
if(len(err) > 0):
for line in err:
print(line.strip())
else:
for line in out:
print(line.strip())
ssh.close()
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment