将cmd传递给subprocess.check_output()

时间:2018-08-31 00:23:09

标签: python sockets subprocess

程序在Windows框内设置命令提示符,然后Linux框可使用该命令提示符执行Windows命令。因此,一旦我在Linux中打开cmd并键入dir以查看Windows计算机上的文件,就会触发异常:

try块失败,并传回异常字符串。如果我进行打印以查看raw_command是什么:“内置函数目录”

while "\n" not in cmd_buffer:
    received_bytes=client_socket.recv(1024)
    cmd_buffer += received_bytes.decode()
    response = run_command(cmd_buffer)
    client_socket.send(str.encode(response))

#____run the command output locally and send it back to the client____
def run_command(command):
    raw_command = command.rstrip('\n')
    try:
        output = subprocess.check_output(raw_command, stderr=subprocess.STDOUT, shell=True)
    except:
        output = "Command failed \r\n" 
    return output

1 个答案:

答案 0 :(得分:1)

您的run_command函数起作用。因此问题出在将命令传递给它的方式上。
但是,在使用try...except块时,您可以检查打印出来的异常。

import subprocess

def run_command(command):
    raw_command = command.rstrip('\n')
    try:
        output = subprocess.check_output(raw_command, stderr=subprocess.STDOUT, shell=True)
    except subprocess.CalledProcessError as e:
        output = "Command failed because: " + e.output.decode()

    return output

print(run_command("ls"))