python11 - 작업(서버에 명령 입력)

2007 단어

서버에 실행을 입력하면 서버가 결과를 되돌려줍니다.


서버:
import socket
import subprocess

server = socket.socket()
ip_port = ('127.0.0.1', 8001)
server.bind(ip_port)
server.listen(5)
print(' ......')

while True:
    conn, addr = server.accept()
    conn.sendall(bytes(' ', encoding='utf-8'))

    while True:
        try:
            recv_byte = conn.recv(1024)
            if not recv_byte:
                raise Exception(' ')
        except Exception as e:
            print(e)
            break
        else:
            recv_str = str(recv_byte, encoding='utf-8')
            flag, command = recv_str.split("|")
            if flag == 'cmd':
                #  , 
                ret = subprocess.getoutput(command)
                ret_bytes = bytes(ret, encoding='utf-8')

                length = len(ret_bytes)
                print(length)
                ret = bytes(str(length),encoding='utf-8')
                conn.sendall(ret)
                ready = conn.recv(1024)
                print(ready)
                conn.sendall(ret_bytes)
        finally:
            pass

클라이언트
import socket

client = socket.socket()
ip_port = ('127.0.0.1', 8001)
client.connect(ip_port)
print('client start')

recv_bytes = client.recv(1024)
print(str(recv_bytes, encoding='utf-8'))

while True:
    command = input(' :
>>>').strip() client.sendall(bytes('cmd|%s' % command, encoding='utf-8')) total_lenngth = int(str(client.recv(1024), encoding='utf-8')) recv_length = 0 content_bytes = bytes() client.sendall(bytes('start accept', encoding='utf-8')) while recv_length < total_lenngth: recv_bytes = client.recv(1024) recv_length += len(recv_bytes) content_bytes += recv_bytes ret = str(content_bytes, encoding='utf-8') print(ret)

좋은 웹페이지 즐겨찾기