使用python在集群上运行shell命令

时间:2017-01-19 09:56:11

标签: python shell

我想/我正在尝试在群集上运行shell命令(通常是文件操作)(spark cluster 1 master和3 worker node)。

群集中的所有计算机之间都有无密码的ssh。

所有群集节点上的文件目录都是相同的。

目前我正在通过

处理文件操作shell命令
try_files

我正在寻找一个python包来做到这一点,通常我试图避免系统调用每次我想运行一个shell命令(我应该得到stdout& stderr为运行python中不同的cluster_Nodes上运行的每个命令脚本日志。)。

shell命令应该在所有目标节点上并行/同时运行。

请指导,如果你们之前知道或使用过任何此类套餐。

5 个答案:

答案 0 :(得分:0)

您可以这样做:

#!/usr/bin/python

import thread
import subprocess

# Define a function for the thread
def run_remote(host, delay):
    remote_cmd='cp directory_1/file1.csv directory_2'
    ssh = subprocess.Popen(['ssh', '-oStrictHostKeyChecking=no', host, remote_cmd],
                           shell=False,
                           stdout=subprocess.PIPE,
                           stderr=subprocess.PIPE)
    result = ssh.stdout.readlines()

    if result == []:
        error = ssh.stderr.readlines()
        print "ERROR: %s" % error
    else:
        print result


# Create two threads as follows
try:
   thread.start_new_thread( run_remote, ("Ip_of_worker-1", 1, ) )
   thread.start_new_thread( run_remote, ("Ip_of_worker-2", 1, ) )
   thread.start_new_thread( run_remote, ("Ip_of_worker-3", 1, ) )


except:
   print "Error: unable to start thread"

答案 1 :(得分:0)

如果您对系统或子进程不满意,可以使用实现ssh协议的库,例如paramiko。 http://docs.paramiko.org/en/2.1/

哈努哈利

答案 2 :(得分:0)

答案 3 :(得分:0)

听起来你想要Fabric - http://www.fabfile.org/

从他们的基本例子:

from fabric.api import run

def host_type():
    run('uname -s')

获取你:

$ fab -H localhost,linuxbox host_type
[localhost] run: uname -s
[localhost] out: Darwin
[linuxbox] run: uname -s
[linuxbox] out: Linux

答案 4 :(得分:0)

parallel-ssh是一个非阻塞的并行ssh客户端,可以执行此操作:

from pssh.pssh2_client import ParallelSSHClient

client = ParallelSSHClient(['host1', 'host2']
output = client.run_command('cp directory_1/file1.csv directory_2')
client.join(output)