Skip to content

Instantly share code, notes, and snippets.

@magmax
Last active August 29, 2015 14:13
Show Gist options
  • Save magmax/ea1dfcc84c06cee12f40 to your computer and use it in GitHub Desktop.
Save magmax/ea1dfcc84c06cee12f40 to your computer and use it in GitHub Desktop.
Run a remote command in several machines, using just one password
from fabric.api import run
def execute(command):
run(command, shell=True)
#!/usr/bin/env python
import os
import argparse
import subprocess
class RunException():
pass
def hosts(cluster):
path = cluster
if not os.path.exists(path):
raise RunException('Cluster not found')
with open(path) as fd:
return ','.join(fd.read().splitlines())
if __name__ == '__main__':
parser = argparse.ArgumentParser(description='Process some integers.')
parser.add_argument('cluster', nargs=1,
help='Cluster where commands should be run')
parser.add_argument('command', nargs='+',
help='Command')
parser.add_argument('-u', '--user',
default=os.getlogin(),
help='select another user')
args = parser.parse_args()
try:
command = 'fab -u "{user}" -H "{hosts}" execute:"{script}"'.format(
script=' '.join(args.command).replace('"', '\"'),
hosts=hosts(args.cluster[0]),
user=args.user
)
subprocess.call(command, shell=True)
except RunException as e:
print(e)
@magmax
Copy link
Author

magmax commented Jan 18, 2015

  1. Create a file with a name of host per host in cluster. Use the cluster name as filename.
  2. Run "run.py CLUSTER -- COMMAND"
    Example:
$ cat cluster.txt
localhost
$ ./run.py cluster.txt -- echo hello
[localhost] Executing task 'execute'
[localhost] run: echo hello
[localhost] Passphrase for private key: 
[localhost] out: hello
[localhost] out: 


Done.
Disconnecting from localhost... done.

@magmax
Copy link
Author

magmax commented Jan 18, 2015

And you can use Fabric directly:

$ fab execute:"echo hello world" -H "$(cat cluster.txt)"                                                         
[localhost] Executing task 'execute'
[localhost] run: echo hello world
[localhost] Passphrase for private key: 
[localhost] out: hello world
[localhost] out: 


Done.
Disconnecting from localhost... done.

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment