An example on how to use python’s subprocess.Popen function:
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29
| #!/usr/bin/env python
import subprocess
import os
#import pdb; pdb.set_trace()
def find():
y = raw_input("Enter a text you want to search on the system!")
s = y.rstrip("\n")
print "string", s
# command = "find /bin -name " + str(y)
# arg = ['/usr/bin/find', '/bin', '-name', s '-print']
# print "command", command
find = subprocess.Popen([r"/usr/bin/find", "/", "-name", y, "-print"], stdout=subprocess.PIPE)
#find_stdout = find.communicate()[0]
#print (find_stdout)
for line in find.stdout.readlines():
print "line", line
l = line.rstrip("\n")
list = subprocess.Popen([r"ls", "-l", l], stdout=subprocess.PIPE)
list_stdout = list.communicate()[0]
print list_stdout
file = subprocess.Popen([r"file", l], stdout=subprocess.PIPE)
file_stdout = file.communicate()[0]
print file_stdout
def main():
find()
main() |
You can also catch stdout and stderr using subprocess below is a simple example…
1 2 3 4 5 6 7
| >>> import subprocess
>>> proc = subprocess.Popen([r"ls /etc /etc/nonexistant"], shell=True, stderr=subprocess.PIPE, stdout=subprocess.PIPE)
>>> stdout,stderr = proc.communicate()
>>> print stdout
blah blah ..output from ls stripped...
>>> print stderr
ls: cannot access /etc/nonexistant: No such file or directory |
more examples:
1 2 3 4 5
| >>> import subprocess
>>> proc = subprocess.Popen([r"uname -a"], shell=True, stdout=subprocess.PIPE, stderr=subprocess.PIPE)
>>> stdout,stderr = proc.communicate()
>>> print stdout
Linux cce-syslog-001.ceremonies.local 2.6.32-71.29.1.el6.x86_64 #1 SMP Mon Jun 27 19:49:27 BST 2011 x86_64 x86_64 x86_64 GNU/Linux |
you can feed the standard output of one command into the standard input of another command, this example shows you how:
1 2 3 4 5 6 7 8 9 10 11
| >>> import subprocess
>>> proc = subprocess.Popen("cat /etc/passwd", shell=True, stdout=subprocess.PIPE,stdin=subprocess.PIPE)
>>> filter = subprocess.Popen("grep root ", shell=True, stdin=proc.stdout,stdout=subprocess.PIPE)
>>> for i in filter.stdout:
... print i
...
root:x:0:0:root:/root:/bin/bash
operator:x:11:0:operator:/root:/sbin/nologin
>>> |