Run 'query session' from python

2019-08-08 08:39发布

问题:

So I am making a program in python that will report the users on a system who connected with RGS.

One way to get users on windows is the query session command. I have tried with both os.popen and subprocess.Popen with and without shell=True. I even specified the full path of the command.

All I get is this error:

'C:/Windows/System32/query.exe' is not recognized as an internal or external command, operable program or batch file.

I can get it working using PsLoggedon.exe, but that wont tell me session type.

So I guess my question is: how can I get this command to work, or what is another way to address this problem?

回答1:

import subprocess

args = ['C:\\Windows\\system32\\query.exe', 'user']
process = subprocess.Popen(args, stdout=subprocess.PIPE)
output, err = process.communicate()

users = [line[1:].split('  ')[0] for line in output.strip().split('\n')[1:]]
print(users)

Prints ['poke'] for me.