问题
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:
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"
来源:https://stackoverflow.com/questions/40978986/execute-cmd-commands-using-python