0

i want to convert from os.system into subprocess the following

os.system("egrep 'Invalid user' /home/bits/Desktop/Assessment/auth.log | cut -d ' ' -f 11 >tempfile.txt ") 

it works but when i write the same statement using subprocess it will create an empty file , does some1 know why and how to resolve that ? thx

a1=subprocess.Popen(["egrep \"Invalid users\" /home/bits/Desktop/Assessment/auth.log"],shell=True,stdout=subprocess.PIPE)   ### instead of /home/bits/Desktop/Assessment/auth.log please modify with your full path of auth.log
a2=subprocess.Popen(["cut -d \" \" -f 11 > /home/bits/Desktop/Assessment/rezolvare/tempfile.txt"],shell=True,stdin=a1.stdout,stdout=subprocess.PIPE)
gzc
  • 8,180
  • 8
  • 42
  • 62
Bonfel
  • 11
  • 4
  • You should redirect stdout to file using `stdout` parameter. Look at this https://stackoverflow.com/questions/4856583/how-do-i-pipe-a-subprocess-call-to-a-text-file – gzc May 28 '17 at 12:03
  • i modified it but i has the same result:an empty file a2=subprocess.Popen(["cut -d \" \" -f 11 "],shell=True,stdin=a1.stdout,stdout=open_file) – Bonfel May 28 '17 at 12:09

1 Answers1

0

You should provide the output file as stdout:

with open("/home/bits/Desktop/Assessment/rezolvare/tempfile.txt", "wb") as output:
    a1 = subprocess.Popen(["egrep",  "Invalid users", "/home/bits/Desktop/Assessment/auth.log"], stdout=subprocess.PIPE)
    a2 = subprocess.Popen(["cut", "-d", " ", "-f", "11"], stdin=a1.stdout, stdout=output)

writing in pure python is even simpler:

with open("/home/bits/Desktop/Assessment/auth.log") as lines:
    with open("/home/bits/Desktop/Assessment/rezolvare/tempfile.txt", "wb") as output:
        for line in lines:
            if "Invalid users" in line:
                output.write(line.split(" ")[10] + "\n")
Daniel
  • 42,087
  • 4
  • 55
  • 81
  • Daniel , i tried the first and the second but i think i have a problem here , i get an empty file everytime i run it ? with os.system works or with bash but the way u got it does not work , maybe i have a problem here , do u have the answer to it ?thx – Bonfel May 28 '17 at 12:33