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

使用python在集群上运行shell命令,python,shell,Python,Shell,我想要/正在尝试在集群(spark cluster 1主节点和3工作节点)上运行shell命令(通常是文件操作) 群集中所有机器之间都有无密码ssh 所有群集节点上的文件目录都相同 目前我正在通过shell命令处理文件操作 #let's say copy or move a file from one dir to other dir import os, sys os.system('ssh user@Ip_of_worker-1 "cp directory_1/file1.csv di

我想要/正在尝试在集群(spark cluster 1主节点和3工作节点)上运行shell命令(通常是文件操作)

群集中所有机器之间都有无密码ssh

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

目前我正在通过shell命令处理文件操作

 #let's say copy or move a file from one dir to other dir
 import os, sys
 os.system('ssh user@Ip_of_worker-1 "cp directory_1/file1.csv directory_2"')
 os.system('ssh user@Ip_of_worker-2 "cp directory_1/file1.csv directory_2"')
 os.system('ssh user@Ip_of_worker-3 "cp directory_1/file1.csv directory_2"')
我正在寻找一个python包来实现这一点,一般来说,每次我想要运行shell命令时,我都会尝试避免系统调用(在运行python脚本日志的不同cluster_节点上运行每个命令时,我应该获得stdout&stderr)

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


如果你们知道或曾经使用过这样的软件包,请指导。

你们可以这样做:

#!/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"

如果您对系统或子流程不满意,可以使用实现ssh协议的库,例如paramiko


Hannu

尝试查找pdsh并使用python调用它

范例

听起来你想要面料-

从他们的基本例子来看:

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
是一个非阻塞并行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)

你的意思是线程。启动新线程(删除线程文件,而不是线程。启动新线程,运行远程,可以同时运行ssh连接,您还可以使用paramiko或fabric作为ssh库设置:sys启动的线程中未处理的异常。excepthook丢失……似乎我需要使用线程模块来代替线程??我可以查看您的脚本吗?主机也必须是user@Ip_of_worker-1(带有用户和@)。subprocess.Popen应该是下一个:subprocess.Popen(['ssh','-oStrictHostKeyChecking=no','user@Ip_of_worker-如果ssh,-oStrictHostKeyChecking=no,user@Ip_of_worker-1“cp目录\u 1/file1.csv目录\u 2”正在工作