iNoob
iNoob

Reputation: 1395

subprocess function displaying odd output

I've got a function def tldomaint that executes the Tasklist command via a subprocess call_checkout. All is working as expected but I'm getting odd output from TaskList. I'm not sure if it's due to my error capturing or if its just an oddity of Tasklist. I'm hoping someone can help pin-point the issue.

Output example:

Attempting to make remote connections and gather data:

Targeted User: xpuser

ERROR: The RPC server is unavailable.

1
WARNING: User credentials cannot be used for local connections

ERROR: The RPC server is unavailable.

1

The 1 in the output is the oddity I'm referring to.

Below is the function.

def tldomaint(serverlist, domain, username, password, targetuser):
    nlist = serverlist
    print "\nAttempting to make remote connections and gather data:\n"
    print "Targeted User: {0}\n" .format(targetuser)
    for serverl in nlist:
        try:
            out = subprocess.check_output(["tasklist", "/V", "/S", serverl, "/U", domain + "\\" + username, "/P", password, "/FO", "List", "/FI", "USERNAME eq %s\\%s" % (domain, targetuser)])
            users = [item for item in out.split() if domain in item and targetuser in item]
            sortedl = set(users)
            for name in sortedl: 
                if name in sortedl != '':
                    print "Targeted User Found On {0}\n" .format(serverl)
                    print name
                else:
                    print "User Not Found"            
        except CalledProcessError as e:
            print(e.returncode)
    return sortedl      

Upvotes: 0

Views: 95

Answers (1)

Martijn Pieters
Martijn Pieters

Reputation: 1121834

You are printing the process return code:

except CalledProcessError as e:
    print(e.returncode)

From the subprocess.check_output() documentation:

If the return code was non-zero it raises a CalledProcessError.

When an error occured, the tasklist writes an error message to stderr, and sets the exit code to 1. subprocess.check_output() then raises the CalledProcessError exception (as documented) and you catch that exception and then print the return code.

Remove the print() statement and your mysterious 1s will go away.

If you wanted to handle the problem in Python, redirect stderr to stdout; the exception will still be raised but you can read the output still:

out = subprocess.check_output(["tasklist", "/V", "/S", serverl, "/U",
                               domain + "\\" + username, "/P", password, "/FO", "List", 
                               "/FI", "USERNAME eq %s\\%s" % (domain, targetuser)],
                              stderr=subprocess.STDOUT)

and in your exception handler:

except CalledProcessError as e:
    errormessage = e.output
    # do something with the error message

Upvotes: 1

Related Questions