Skip to content

Instantly share code, notes, and snippets.

@pmbuko
Last active March 1, 2020 07:03
Show Gist options
  • Star 2 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save pmbuko/787b2042986d62f21b3a to your computer and use it in GitHub Desktop.
Save pmbuko/787b2042986d62f21b3a to your computer and use it in GitHub Desktop.
parallel ssh commands. key-based auth *highly* recommended
#!/usr/bin/env python
#
# Pass any number of short hostnames to run cmd on all
# hosts in parallel and display the results nicely.
import sys
import subprocess
import multiprocessing
PROCESSES = 8
domain = 'site.example.com'
# you can string together multiple commands if you want
cmd = """command -with options; \
simple_command; \
even_more -optiony things"""
def do_ssh_command(host):
ssh = subprocess.Popen(["ssh", "-oStrictHostKeyChecking=no", str(host), cmd],
shell=False,
stdout=subprocess.PIPE,
stderr=subprocess.PIPE)
result = ssh.stdout.readlines()
if result == []:
error = ssh.stderr.readlines()
SSH_ERRORS.append("[%s]: %s" % ( host.split('.')[0], error[0].strip()) )
else:
results = "[%s]\n%s" % ( host.split('.')[0], ''.join(result) )
SSH_RESULTS.append(results)
if __name__ == '__main__':
inputs = sys.argv[1:]
if len(inputs) < 1:
print "Please supply at least one short hostname."
else:
print "\nNow running commands...\n"
hosts = [ h + '.' + domain for h in inputs ]
ssh_manager = multiprocessing.Manager()
SSH_RESULTS = ssh_manager.list()
SSH_ERRORS = ssh_manager.list()
p = multiprocessing.Pool(processes=PROCESSES)
p.map(do_ssh_command, hosts)
p.close()
if len(SSH_RESULTS) > 0:
print "=======\nRESULTS\n-------"
for result in SSH_RESULTS: print result
if len(SSH_ERRORS) > 0:
print "======\nERRORS\n------"
for error in SSH_ERRORS: print error
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment