Python执行复杂的shell命令

2024-10-01 17:33:16 发布

您现在位置:Python中文网/ 问答频道 /正文

嗨,我必须执行一个shell命令:diff<;(ssh-n)root@10.22.254.34cat/vms系统/云突发.qcow2.*)lt;(ssh-nroot@10.22.254.101cat/vms系统/云突发.qcow2) 我试过了

cmd="diff <(ssh -n root@10.22.254.34 cat /vms/cloudburst.qcow2.*) <(ssh -n root@10.22.254.101 cat /vms/cloudburst.qcow2)"
args = shlex.split(cmd)
output,error = subprocess.Popen(args,stdout = subprocess.PIPE, stderr= subprocess.PIPE).communicate()

但是我得到了一个错误diff:extra operand cat

我对python很陌生。任何帮助都将不胜感激


Tags: 命令ltcmd系统argsdiffrootshell
2条回答

您使用的是<(...)(进程替换)语法,由shell解释。向Popen提供shell=True以使其使用shell:

cmd = "diff <(ssh -n root@10.22.254.34 cat /vms/cloudburst.qcow2.*) <(ssh -n root@10.22.254.101 cat /vms/cloudburst.qcow2)"
output,error = subprocess.Popen(cmd, shell=True, executable="/bin/bash", stdout=subprocess.PIPE, stderr=subprocess.PIPE).communicate()

由于不需要bourneshell(/bin/sh),请使用executable参数来确定要使用的shell。在

您正在命令行中使用一种称为processsubstitution的特殊语法。大多数现代shell(bash,zsh)都支持这一点,但是/bin/sh不支持它。因此,Ned建议的方法可能行不通。(如果另一个shell提供了/bin/sh,并且没有“正确地模仿”sh的行为,那么它可能会这样做,但不能保证会这样做)。 试试这个:

cmd = "diff <(ssh -n root@10.22.254.34 cat /vms/cloudburst.qcow2.*) <(ssh -n root@10.22.254.101 cat /vms/cloudburst.qcow2)"
output,error = subprocess.Popen(['/bin/bash', '-c', cmd], stdout=subprocess.PIPE, stderr=subprocess.PIPE).communicate()

这基本上就是shell=True参数所做的,但是使用/bin/bash而不是/bin/sh(如subprocess docs中所述)。在

相关问题 更多 >

    热门问题