1

I'm using python 3.7 on Windows. I'm trying to execute a simple scan command and get its output as a string.

When I execute the command in python I only get the first line:

import subprocess

def execute(command):
    proc = subprocess.run(command, stdout=subprocess.PIPE, stderr=subprocess.PIPE, universal_newlines=True)
    output = proc.stdout if proc.stdout else proc.stderr

path = "Somepath"
command = ['ecls.exe', '/files', path]
print(execute(command))

output:

WARNING! The scanner was run in the account of a limited user.

But when I run it in the CMD:

$ ecls.exe /files "SomePath"
WARNING! The scanner was run in the account of a limited user.
ECLS Command-line scanner ...
Command line: /files SomePath
Scan started at:   11/24/18 14:18:11
Scan completed at: 11/24/18 14:18:11 Scan time:         0 sec (0:00:00) 
Total:    files - 1, objects 1 Infected:    files - 0, objects 0 Cleaned:    files - 0, objects 0

I think that the command spawn a child process and it produces the scan output. I also tried to iterate over stdout but got the same output.

EDIT: I tried other methods like check_output, Popen, etc with using PIPE but I only get the first line of output. I also tried to use shell=True but didn't make any difference. As I already said the command spawn a child process and I need to capture its output which seems that subprocess can't do it directly.

scytale
  • 12,346
  • 3
  • 32
  • 46
Masoud Rahimi
  • 5,785
  • 15
  • 39
  • 67

1 Answers1

3

As I couldn't find a direct way to solve this problem, with help of this reference, the output can be redirected to a text file and then read it back.

import subprocess
import os
import tempfile

def execute_to_file(command):
    """
    This function execute the command
    and pass its output to a tempfile then read it back
    It is usefull for process that deploy child process
    """
    temp_file = tempfile.NamedTemporaryFile(delete=False)
    temp_file.close()
    path = temp_file.name
    command = command + " > " + path
    proc = subprocess.run(command, shell=True, stdout=subprocess.PIPE, stderr=subprocess.PIPE, universal_newlines=True)
    if proc.stderr:
        # if command failed return
        os.unlink(path)
        return
    with open(path, 'r') as f:
        data = f.read()
    os.unlink(path)
    return data

if __name__ == "__main__":
    path = "Somepath"
    command = 'ecls.exe /files ' + path
    print(execute(command))
Masoud Rahimi
  • 5,785
  • 15
  • 39
  • 67