python socket客户端等待服务端多次连接

之前用socket都是服务端等待客户端连接;

最近有个需求,同一个局域网内,客户端等待服务端多次连接,多次接收服务端的命令在客户端执行,拿到执行结果并返回给服务端,且如果一方断掉,另一方要继续保持,等待对方的下一次连接

不废话,直接上代码;

无论是先运行server或者是先运行client,都可以进行多次连接

server

#-*-coding:utf8-*-
import socket
from threading import  Thread
import time
class Windows(object):
    def __init__(self):
        self.socket=socket.socket()
        self.socket.setsockopt(socket.SOL_SOCKET,socket.SO_REUSEADDR,1)
        self.socket.settimeout(300)
        self.addr=("0.0.0.0",9999)
        self.socket.bind(self.addr)
        self.socket.listen(5)
        self.socket.setblocking(True)
        print("wait for sut connecting......")
        self.conn, self.addr = self.socket.accept()

    def enter_to_windows(self):
        if self.conn:
            print("connect sut ip>>>{}:{}".format(self.conn.getpeername()[0],self.conn.getpeername()[1]))
            return True
        else:
            return False

    def execute(self,cmd):
        while True:
            if 0<len(cmd)<1024:
                n=self.conn.send(str(cmd).encode())
                print("send cmd'{}' to sut {} total bytes".format(cmd, n))
                cmd=""
            if not cmd:
                break
        val=""
        while True:
            ret_val=self.conn.recv(1024).decode()
            if not ret_val:
                break
            # print ("receive cmd '{}''s response from sut >>>".format(cmd),ret_val)
            val+=ret_val
        print("from sut receive data: {}".format(val))
        self.conn.close()
        self.socket.close()
        return val
w=Windows()
print(w.enter_to_windows())
w.execute("ipconfig")
w=Windows()
w.execute("systeminfo")
w=Windows()
w.execute("dir")

client

import socket
import sys
import subprocess
import os
import time


while True:
    s = socket.socket()
    # addr=("127.0.0.1",9999)
    addr = ("pengfe5x-MOBL", 9999)
    print("{}:wait for server connect...".format(time.ctime()))
    while True:
        time.sleep(5)
        try:
            res=s.connect(addr)
            print(res)
            if not res:
                print("connect server",addr)
                break
        except:
            pass
    while True:
        try:
            data=s.recv(1024).decode()
            if not data:
                break
            print data

            print("receive from server data:",data.decode())

            res=subprocess.Popen([data],shell=True,stdout=subprocess.PIPE)
            if not res:
                print ">>>>>>>>>>>>>>>>execute command {} success!!!{}".format(data,res)
            n=s.send(res.stdout.read())
            print "send {}".format(n)
        except Exception as e:
            print("{}".format(e))
            break
        print ("close client socket")
        s.close()
posted @ 2020-04-25 14:17  腹肌猿  阅读(1812)  评论(0编辑  收藏  举报