1

I'm trying to execute remote command over ssh. all working well from the ssh connection and also with an other simple cmd command like 'ls'. but, i would like to using ls and grep for a value stored in a variable(ptrn) but i always failed. i tried using:

  • cmd="ls -ltrd /export/home| grep %s ptrn"
  • cmd="ls -ltrd /export/home| grep" + ptrn
  • cmd="ls -ltrd /export/home| grep", ptrn

but no luck ):

my code:

BuildServer = 1.2.3.4
ptrn = "abc"
cmd="ls -ltrd /export/home| grep ptrn"
ssh = subprocess.Popen(["ssh", "%s" % BuildServer, cmd],shell=False, stdout=subprocess.PIPE, stderr=subprocess.PIPE)
print (ssh)

Can anyone please help me with that?

Thank you all.

Asfbar
  • 259
  • 6
  • 21

2 Answers2

3

If I read you correctly, you want to grep for the contents of the ptrn Python variable, so you need to pass that to grep, rather than its name, which doesn't mean anything in that context.

#!/usr/bin/env python
import subprocess
from pipes import quote

BuildServer = "1.2.3.4" # you pass it as a string to ssh
ptrn = "abc"
cmd="ls -ltrd /export/home| grep " + quote(ptrn) # Don't forget the space after grep.
ssh = subprocess.Popen(["ssh", "%s" % BuildServer, cmd], shell=False, stdout=subprocess.PIPE, stderr=subprocess.PIPE)
print ssh.communicate()[0]

As for quote, this answer mentions it for quoting shell arguments, so that grep will consider it a single argument.

communicate() reads output from the process and waits for it to end.

Community
  • 1
  • 1
Vlad
  • 18,195
  • 4
  • 41
  • 71
1

You can try these:

  • cmd="ls -ltrd /export/home| grep %s"%ptrn
  • cmd="ls -ltrd /export/home| grep " + ptrn #notice the space
Lyon
  • 11
  • 1