Execute CMD commands using python

拥有回忆 提交于 2021-02-11 15:55:48

问题


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

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!