我想从远程计算机上的python代码运行以下命令:
/bin/cat < abc.txt | tee >(echo $(md5sum) > /tmp/abc.md5sum) | some-other-command
。
我必须使用Cumin将此命令发送到远程计算机。我的代码如下:
from multiprocessing import Pipe, Process
import os
import cumin
from cumin import query, transport, transports
from mypackage.RemoteExecution import CommandReturn, RemoteExecution
def run_subprocess(host, command, input_pipe):
e = CuminExecution()
result = e.run(host, command)
input_pipe.send(result)
class CuminExecution(RemoteExecution):
"""
RemoteExecution implementation using Cumin
"""
def __init__(self, options={}):
self._config = None
self.options = options
@property
def config(self):
if not self._config:
self._config = cumin.Config()
return self._config
def format_command(self, command):
if isinstance(command, str):
return command
else:
return ' '.join(command)
def run(self, host, command):
hosts = query.Query(self.config).execute(host)
if not hosts:
return CommandReturn(1, None, 'host is wrong or does not match rules')
target = transports.Target(hosts)
worker = transport.Transport.new(self.config, target)
worker.commands = [self.format_command(command)]
worker.handler = 'sync'
return_code = worker.execute()
for nodes, output in worker.get_results():
if host in nodes:
result = str(bytes(output), 'utf-8')
return CommandReturn(return_code, result, None)
return CommandReturn(return_code, None, None)
def start_job(self, host, command):
output_pipe, input_pipe = Pipe()
job = Process(target=run_subprocess, args=(host, command, input_pipe))
job.start()
input_pipe.close()
return {'process': job, 'pipe': output_pipe}
def monitor_job(self, host, job):
if job['process'].is_alive():
return CommandReturn(None, None, None)
else:
result = job['pipe'].recv()
job['pipe'].close()
return result
def kill_job(self, host, job):
if job['process'].is_alive():
job['process'].terminate()
def wait_job(self, host, job):
job['process'].join()
result = job['pipe'].recv()
job['pipe'].close()
return result
src_command = "/bin/cat < abc.txt | tee >(echo $(md5sum) > /tmp/abc.md5sum) | some-other-command"
result = CuminExecution.run(host, src_command)
当我从终端运行命令/bin/cat < abc.txt | tee >(echo $(md5sum) > /tmp/abc.md5sum) | some-other-command
时,它正在按预期方式工作。但是,当我尝试使用上述代码使用python3运行它时,它可以正确处理所有命令,除了写入/tmp/abc.md5sum
部分!运行后,文件abc.md5sum包含错误的哈希。
有人可以帮我解决这个问题吗?
我已经以这种方式更改了命令:
/bin/cat < abc.txt | tee >(md5sum > /tmp/abc.md5sum) | some-other-command
并且现在正在工作!谢谢大家的帮助!