Question

This is follow on from Python script not executing sysinternals command

My script takes input

python ps.py sender-ip=10.10.10.10

The sender-ip gets read into a variable, userIP. However, when I pass userIP into the following subprocess

pst = subprocess.Popen(
        ["D:\pstools\psloggedon.exe", "-l", "-x", "\\\\", userIP],
        stdout = subprocess.PIPE,
        stderr = subprocess.PIPE
    )

out, error = pst.communicate()

userLoggedOn = out.split('\n')[1].strip()
print 'userId={}'.format(userloggedon)

The script will output

userId=

How do I make the subprocess read the userIP so it will execute

D:\pstools\psloggedon.exe  -l -x \\userIP

And output

userId=DOMAIN\user

EDIT

Command-line to execute the script is

python py.ps sender-ip=10.10.10.10

When I manually execute

D:\PSTools\PsLoggedon.exe -l -x \\10.10.10.10

I get the result I am looking for

Was it helpful?

Solution

'\\\\' and userIP are not separate options, but you pass it as if they were separate to psloggedon.exe.

Glue them into one string:

userIP="\\\\"+userIP
pst = subprocess.Popen(
        ["D:\pstools\psloggedon.exe", "-l", "-x",  userIP],
        stdout = subprocess.PIPE,
        stderr = subprocess.PIPE
    )

Check out your print statement also. You set userLoggedOn variable, and then print using userloggedon.

OTHER TIPS

Your trouble is in name of executable. Single backslash works just as escape character, so if you would print name of the command you are going to start, you would see the backslashes being lost.

The options are:

cmd = r"D:\pstools\psloggedon.exe" # raw string prefix r
print cmd
cmd = "D:\\pstools\\psloggedon.exe" # double backslash
print cmd
cmd = "D:/pstools/psloggedon.exe" # forward slash works also on windows
print cmd

You may try using following idiom, which allows better detection of problems

userIP="\\\\"+userIP

cmd = ["D:\\pstools\\psloggedon.exe"]
cmd.extend(["-l", "-x", userIP])
print "cmd", cmd # do it only, if you are developing
pst = subprocess.Popen(
        cmd,
        stdout = subprocess.PIPE,
        stderr = subprocess.PIPE
    )

This allows you to print out cmd and see, if there are possible problems visible.

note: the code above builds on the accepted answer solution (which adds solution for proper userIP but might have problems with backslashes).

The simplest way to make it work is to use raw-string literal to avoid escaping backslashes inside string literals and to pass the command as a string on Windows:

from subprocess import check_output

output = check_output(r"D:\pstools\psloggedon.exe  -l -x \\userIP")
print(output.splitlines())
Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top