简体   繁体   English

使用python执行CMD命令

[英]Execute CMD commands using python

what i'm trying to do is create a server and a client, the server being able to execute CMD commands. 我想做的是创建一个服务器和一个客户端,该服务器能够执行CMD命令。

I managed to do the server-client communication but i have problems at controlling the command prompt using python. 我设法进行服务器-客户端通信,但是在使用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> . 使用此代码,我能够执行shell命令,但始终会遗漏最后一行,该行显示了当前路径并等待我的输入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. 另外,一段时间不输入任何命令后,它会崩溃pexpect.TIMEOUT ,我知道我可以通过增加超时来解决此问题,但它不会改变我的阅读方法存在缺陷的事实。

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 :) ... 很抱歉,如果我没有描述问题,我已经足够好了,这是我第一次在这里寻求有关stackoverflow的帮助:) ...

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"

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM