如何通过python套接字运行多个命令

时间:2019-05-09 11:42:08

标签: python sockets

我的代码有问题,我想通过套接字在虚拟机上运行命令。我发现多个任务,命令有问题。例如,如果我打开Excel,我的套接字服务器已冻结,并且在手动关闭excel应用程序之前无法通过cmd运行其他命令。

在虚拟机上一次打开多个应用程序时,应该更改什么代码? (例如,我想一次打开四个xlsx文件)

Server.py

import socket
import subprocess
import os
from threading import Thread


def check_ping(hostname):
    response = os.system("ping " + hostname)
    # and then check the response...
    if response == 0:
        pingstatus = "Network Active"
    else:
        pingstatus = "Network Error"

    return(pingstatus)

def run_path(path):
    response = os.system(path)
    # and then check the response..
    return('ok')



def Main():
    host = "localhost"
    port = 5000

    mySocket = socket.socket()
    mySocket.bind((host,port))

    mySocket.listen(1)
    conn, addr = mySocket.accept()
    print ("Connection from: " + str(addr))
    while True:
            data = conn.recv(1024).decode()
            if not data:
                    break
            #print ("from connected  user: " + str(data))

            #data = str(data)
            #hostname = data.replace('ping ', '')

            print ("sending: " + str(data))
            #print(hostname)
            conn.send(data.encode())
            if 'ping' in str(data):
                hostname = data.replace('ping ', '')
                pingstatus = check_ping(hostname)
                print(pingstatus)
            elif 'open' in str(data):
                path = str(data).replace('open ', '')

                run_path(path)





    conn.close()

if __name__ == '__main__':
    Main()

Client.py

import socket

def Main():
        host = '127.0.0.1'
        port = 5000

        mySocket = socket.socket()
        mySocket.connect((host,port))

        message = input(" -> ")

        while message != 'q':
                mySocket.send(message.encode())
                data = mySocket.recv(1024).decode()

                print ('Received from server: ' + data)

                message = input(" -> ")

        mySocket.close()

if __name__ == '__main__':
    Main()

1 个答案:

答案 0 :(得分:0)

您可以在上一个命令返回之前运行新命令,而不必等待该事件。这意味着您应该使用子流程模块而不是system函数:

def run_path(path):
    response = subprocess.Process(path, shell=True)
    # and then continue without waiting...
    return('ok')

但是,如果您想将任何东西退还给对等方,则没有任何意义。此外,从远程客户端启动GUI程序而无法控制它甚至停止它也没有任何意义。

恐怕你在这里追怪怪的动物...