4

I am trying to run a python script, and I need to Rsh a command from the script, the command I want to run is : df -Pk|grep "sd\|md"|gawk '{print $2}'

and I do it as -

cmd2='df -Pk|grep \\\"sd\|md\\\"|gawk \'{print $2}\''
process = subprocess.Popen(['rsh',ip,cmd2],stdout=subprocess.PIPE)
output = process.communicate()[0]

However when I do run the script,I get nothing in output.

I am new to python and as far as I know, its a problem with the escape characters.

Any help would be great.

Note: I have to use Rsh only and cannot use ssh

Thanks

Fred Foo
  • 355,277
  • 75
  • 744
  • 836
sudologin
  • 91
  • 1
  • 7
  • Didn't you miss a backslash to escape the one after sd – Sid Feb 02 '12 at 21:22
  • Have you tried using a much simpler command, like ls, to verify the communication? Have you tried executing the df/grep command locally? – Scott Hunter Feb 02 '12 at 21:23
  • @Sid Sorry about that, it was a typo. – sudologin Feb 02 '12 at 21:33
  • @ScottHunter Yes, I have run the command locally and checked the communication as well. It works. The following works as well - cmd = 'df -Pk' process = subprocess.Popen(['rsh',ip,cmd],stdout=subprocess.PIPE) output = process.communicate()[0] – sudologin Feb 02 '12 at 21:34

1 Answers1

0

Enclose the command, with proper shell quoting, in triple quote marks:

"""df -Pk|grep "sd\|md"|gawk '{print $2}'"""

See also the Python tutorial's bit on strings.

Fred Foo
  • 355,277
  • 75
  • 744
  • 836
  • @jdi: you removed the `\` before `|`, which changes the `grep` RE's meaning. – Fred Foo Feb 02 '12 at 21:25
  • withdrawn lol. I was only thinking about the string formatting on its own and forgot to consider the subprocess :-) – jdi Feb 02 '12 at 21:26
  • @larsmans Thanks for the link. However the triple quotes didn't help. – sudologin Feb 02 '12 at 21:41
  • @sudologin: What do you mean by "it didn't help"? Did you try running the command through `sh` instead of `rsh`? – Fred Foo Feb 02 '12 at 21:42
  • @larsmans Yes I did that. However I got to work now, used just 'df -Pk' as 'cmd' and did rest of the parsing on the host(local), works perfect. – sudologin Feb 02 '12 at 21:59