Search code examples
pythonstringsubprocesssysinternals

Parse variable in python subprocess


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


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.