2

I'm using the 'qwinsta' cmd command to get the session ID of a remote computer and output it to a textfile, so I create a new batch file and write the command then I try running the batch file through python but it only returns the first line of the output. When I run the batch file by simply double-clicking it it works properly.

Using python 2.7:

def run_qwinsta(self, computerName):                                                 
        qwinsta_check = open("q.bat", "w")
        qwinsta_check.write('PsExec -u <username> -p <password> \\\\' + computerName + ' qwinsta' + ' > "q.txt" ')
        qwinsta_check.close()

        os.system("q.bat")

Expected results:

 SESSIONNAME       USERNAME                 ID  STATE   TYPE        DEVICE 
>services                                    0  Disc                        
 console           <username>                1  Active                      
 rdp-tcp                                 65536  Listen   

Actual results:

 SESSIONNAME       USERNAME                 ID  STATE   TYPE        DEVICE
Maroya
  • 21
  • 1

1 Answers1

0

I would recommend you to avoid writing the batchfile, If you can. You can execute your batch command from os.system(). Also you can try using subprocess (documentation here) and then redirecting the stdout and stderr to file.

EDIT:

PsExec is a good choice, but If you want another way, you can also use ssh.

You can run PsExec from os.system() and then write the response to text file on the remote machine. The default PsExec working directory is System32 there you can find your text file.

Tested code:

import os

os.system('Psexec \\\\SERVER cmd.exe /c "tasklist > process_list.txt"')

I used tasklist, because I don't have qwinsta on my remote machine.

If you want to store the PsExec response on your machine you can use subprocess and then redirect the stdout to text file.

Tested code:

import subprocess

process_list = open("process_list.txt", "w")
subprocess.call(['Psexec', '\\\\SERVER', 'tasklist'], stdout=process_list)
process_list.close()

Actually I used Python 3.x, because I don't have Python 2.x, but it should work on both.

If this still didn't solve your problem, please provide more details to your question!

Skulaurun Mrusal
  • 2,792
  • 1
  • 15
  • 29
  • The thing is I need to use psexec, or some other way to execute commands on a remote machine – Maroya Sep 04 '19 at 16:06