1

what i'm trying to do is create a server and a client, the server being able to execute CMD commands.

I managed to do the server-client communication but i have problems at controlling the command prompt using python.

My current code is:

import time
import _thread
import winpexpect
class CommandPrompt(object):
    def __init__(self):
        self.cmd = winpexpect.winspawn('cmd.exe')
    def read(self):
        while True:
            if self.cmd.readline():
                print(self.cmd.before)
    def send(self,usinput):
        self.cmd.sendline(usinput)
    def close(self):
        self.cmd.close()
cmd = CommandPrompt()
_thread.start_new_thread(cmd.read,())
time.sleep(1)
while True:
    cmd.send(input('>>'))

With this code i am able to execute shell commands but it always i missing the last line, the one showing the current path and waiting for my input ex:C:\Windows\system32>. I think the reason it's not showing that line is because it wasn't entered.

Also, after some time of not inputting any command it crashes pexpect.TIMEOUT, i know i could solve this by raising the timeout but it doesn't change the fact that my reading method is flawed.

Can anyone help me to read the output of the command prompt?

I'm sorry if i didn't describe the problem i have good enough, it's my first time asking for help here on stackoverflow :) ...

1 Answer 1

1

You could try to pipe the output into an output file and read that file. For example:

import time
import _thread
import winpexpect
class CommandPrompt(object):
    def __init__(self):
        self.cmd = winpexpect.winspawn('cmd.exe')
    def read(self):
        while True:
            if self.cmd.readline():
                print(self.cmd.before)
    def send(self,usinput):
        self.cmd.sendline(usinput)
    def close(self):
        self.cmd.close()
cmd = CommandPrompt()
_thread.start_new_thread(cmd.read,())
time.sleep(1)
while True:
    cmd.send(input('>>') + " > out.txt")

    # some sort of function to request the contents of "out.txt"

    # some sort of function to remove "out.txt"
Sign up to request clarification or add additional context in comments.

3 Comments

Yes but everytime i run a command in os.system it is ran in a different cmd instance. I need that all the commands to be ran in the same cmd instance so i can do things like "cd foo" then "dir /d". Thank you for fast response though
@PopescuIonutAlexandru No worries! I will edit the post accordingly
When trying to run your code, I always get the error: pywintypes.error: (2, 'CreateProcess', 'The system cannot find the file specified.'), referring to the winspawn line... Do you know why?

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.