Skip to content

Instantly share code, notes, and snippets.

@Ankit-Kulkarni
Created November 27, 2018 09:11
Show Gist options
  • Select an option

  • Save Ankit-Kulkarni/7bb173abdd46f18b4be4edb197add3d8 to your computer and use it in GitHub Desktop.

Select an option

Save Ankit-Kulkarni/7bb173abdd46f18b4be4edb197add3d8 to your computer and use it in GitHub Desktop.
A pssh type client to run commands in parallel on multiple server. The script output is only shown after gathering all outputs.
#!/usr/bin/env python3
""" This script is used to ssh parallel on multiple machines and get the output
Sample run is - python pssh.py ubuntu@31.215.xx.xx ubuntu@xx.xx.xx.xx:port
"""
import sys
from fabric import ThreadingGroup as Group
def validate_command():
""" validates the command and returns True/False """
pass
def show_results(gresults):
""" Display the results of the command run """
# import pdb; pdb.set_trace()
for connection, result in gresults.items():
print("********Op start ***********\n")
print("{0.host}\n: {1.stdout}".format(connection, result))
print("*********Op end **********\n")
return
def run_command(con_ob, command):
"""
Runs specified commands on the host and returns host:output mapping
"""
gresults = con_ob.run(command, hide=True)
show_results(gresults)
# returning group results
return gresults
def create_connection(hosts):
"""
Takes space seperated hosts list and returns connection object
"""
try:
print("Trying to establish ssh connections....")
con_ob = Group(*hosts)
print("Connection is established")
return con_ob
except Exception as e:
print("Error creating the connection to the server.Look the exception ")
print(e)
exit(1)
return None
def main(con_ob):
""" takes connection object and runs command on hosts """
while True:
# validate command is not run yet
command = raw_input("Please type your command to run on hosts: ")
if command == "":
print("blank input: exiting, case needs to handle")
break
else:
run_command(con_ob, command)
if __name__ == '__main__':
# no command line error checking defined yet
# if sys.argv == "":
# print("Pass the hostname list please of format username@ip:port")
# get hosts
hostlist = sys.argv[1:]
# create con object
con_ob = create_connection(hostlist)
main(con_ob)
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment