Python:用ssh连接替换shell管道

时间:2018-07-19 13:32:43

标签: python subprocess pipe piping

我有以下不错的bash命令:

cat SomePythonScript.py | ssh remote_machine 'cat - | python'

效果很好,我想用Python编写。我尝试使用“子流程”,但没有走那么远。有人能帮我吗 ?

from subprocess import  PIPE , Popen

p1 = Popen(["cat ", "SomePythonScript.py"], stdout=PIPE)
p2 = Popen(["remote_machine"], stdin=p1.stdout, stdout=PIPE)
p3 = Popen(["cat -", "python"], stdin=p2.stdout, stdout=PIPE)

p1.stdout.close()  
p2.stdout.close()  

output = p3.communicate()[0]

我也尝试了2个进程/管道

from  subprocess import PIPE , Popen  
p1 = Popen([["cat", "SomePythonScript.py"], stdout=PIPE)
p2 = Popen(["remote_machine","cat", "- python"], stdin=p1.stdout,    stdout=PIPE)
p1.stdout.close() 
output = p2.communicate()[0]

对于任何帮助,建议,建议,解释解决方案……我都会很高兴

2 个答案:

答案 0 :(得分:0)

首先,即使您需要管道的其余部分,也不值得复制useless use of cat

第二,很明显,尽管您包括了完全毫无意义的cat命令,但您忽略了唯一实际执行某项命令的命令-根本没有尝试运行ssh。< / p>


编辑以供将来参考-由于接受的答案仍然是 still ,它们沉迷于cat的相同无用用途,因此代码应如下所示:

from subprocess import  PIPE , Popen

p = Popen(["ssh", "remote_machine", "python"], 
          stdin=open("SomePythonScript.py",'r'), stdout=PIPE)
output = p.communicate()[0]

就是原始shell代码应该放在首位的东西:

< SomePythonScript.py ssh remote_machine python

包含的原始代码

  • p1 = Popen([["cat", "SomePythonScript.py"], stdout=PIPE)
    

    open("SomePythonScript.py",'r')的作用相同,但以运行子进程为代价,根本没有任何好处。

  • p2 = Popen(["ssh", "remote_machine", "cat - | python"], ...
    

    在远程计算机上运行附加的冗余进程。由于cat -只是将其stdin复制到stdout,因此您可以完全省略它

答案 1 :(得分:-1)

您使用 • Couldn't match type ‘Maybe (Key Dealership)’ with ‘Key Dealership’ Expected type: Control.Monad.Trans.Reader.ReaderT SqlBackend m0 (Key Dealership) Actual type: SqlPersistT m0 (Maybe (Key Dealership)) • In the second argument of ‘($)’, namely ‘getVehicleDealership vehicleKey’ In the expression: mapM selectDealership $ getVehicleDealership vehicleKey In an equation for ‘findDealership’: findDealership vehicleKey = mapM selectDealership $ getVehicleDealership vehicleKey | 46 | findDealership vehicleKey = mapM selectDealership $ getVehicleDealership vehicleKey | ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ 并没有错。唯一有问题的地方是,您缺少Popen命令,并且当您要模仿的bash命令中只有两个时,您正在尝试运行三个进程-ssh是只是'cat - | python'命令的一个参数。

以下内容应更好地模仿您的bash命令:

ssh