Based on tcp socket communication protocols: remote command execution

1.struct module

# 1, the integer number converted into bytes Type 
# 2, is transformed into a fixed length of bytes 

Import struct
 Import JSON 

header_dic = {
     ' total_size ' : 31,222,222,222,121 ,
     ' MD5 ' : ' 123svsaef123sdfasdf ' ,
     ' filename ' : ' A. TXT ' 
} 

# serialized: the data structures in memory ---- "converted into an intermediate format (string) ----" to a file in 
header_json = json.dumps (header_dic)
 Print (header_json, type ( header_json)) 

# code: results of encoded bytes type
header_bytes=header_json.encode('utf-8')
header_size=len(header_bytes)
print(header_size)  # 81

#打包
obj=struct.pack('i',header_size)
print(obj,len(obj))  # b'Q\x00\x00\x00' 4

#解包
obj2=struct.unpack('i',obj)
print(obj2)  # (81,)
View Code

Print Results:

{"total_size": 31222222222121, "md5": "123svsaef123sdfasdf", "filename": "a.txt"} <class 'str'>
81
b'Q\x00\x00\x00' 4
(81,)
result

2. Communication entire process:

'' ' 
Process: 
    the server: production header, the header information header thrown dictionary, Dictionary of the sequences obtained json string, encode give bytes 
          ----> transmitter header length (struct.pack labeled 4 bytes) - -> transmission header ----> real data sent 
          
    client: receiving first four bytes: struct.unpack unpacking header length ---> header received -> 
             parse headers: decode string obtained, to give deserialization header ---> according to information in the header to collect real data 

'' '

3. The specific code as follows:

Server:

from Socket Import *
 Import The subprocess
 Import struct
 Import JSON 

Server = Socket (AF_INET, SOCK_STREAM) 
server.bind (( ' 127.0.0.1 ' , 8080 )) 
server.listen ( . 5)                # listening client link requests 

the while True: 
    Conn, client_addr server.accept = () # (connection object, the client's ip and port) conn: a three-way handshake tcp product can be used to send and receive messages 
    Print (client_addr)      # role here client_addr of which clients can build links to know , and communications unrelated to 
    the while True:
         the try :
            cmd = conn.recv (1024)    # cmd type is bytes, 
            obj = subprocess.Popen (cmd.decode ( ' UTF-. 8 ' ),    
                                 the shell = True, 
                                 stdout = subprocess.PIPE, 
                                 stderr = subprocess.PIPE 
                                 ) 
            stdout = obj .stdout.read ()   # system commands, decoding requires GBK 
            stderr = obj.stderr.read () 

            # . 1, the header produced 
            header_dic = {
                 ' total_size ' : len (stdout) +len (stderr),
                 ' MD5 ' : ' 123svsaef123sdfasdf ' ,
                 ' filename ' : ' a.txt ' 
            } 
            header_json = json.dumps (header_dic)          # JSON serialization header 
            header_bytes = header_json.encode ( ' UTF-. 8 ' )    # character string type ----> bytes type transmission 

            # 2, the length of the first transmission header 
            header_size = len (header_bytes) 
            conn.send (struct.pack ( ' I ', header_size)) 

            # . 3, transmission header 
            conn.send (header_bytes) 

            # . 4, the transmission of real data 
            conn.send (stdout)      # Send only send bytes type 
            conn.send (stderr)
         the except ConnectionResetError:
             BREAK 
    conn.Close () 
server.close ()

Client:

from Socket Import *
 Import struct
 Import JSON           
 
Client = Socket (AF_INET, SOCK_STREAM) 
the client.connect (( ' 127.0.0.1 ' , 8080 ))
 # Print (Client) 

the while True: 
    cmd = INPUT ( ' >>>: ' ). Strip ()
     IF  Not cmd: Continue 
    client.send (cmd.encode ( ' UTF-. 8 ' ))      # the results of the command to the server 
    # 1, the first collection header length according to the information within the header, real data collected 
    header_size = struct.unpack (' I ' , client.recv (. 4)) [0]     # bytes type, want to get the length of the header bytes should be solved to 

    # 2, receives the header 
    header_bytes = client.recv (header_size)    # corresponding to the server transmission header 

    # 3 parsing the header 
    header_json = header_bytes.decode ( ' UTF-. 8 ' )     # bytes type ----> string type 
    header_dic = json.loads (header_json)          # deserialization get header 
    Print (header_dic) 

    total_size = header_dic [ ' total_size ' ]
     # Print (total_size) # 1025 
    # . 4, receives data 

    recv_size = 0 
    RES=b''
    while recv_size < total_size:
        recv_data=client.recv(1024)
        res+=recv_data
        recv_size+=len(recv_data)

    print(res.decode('gbk'))
client.close()

 

Guess you like

Origin www.cnblogs.com/zh-xiaoyuan/p/11783058.html