# service-side code
#!/usr/bin/env python#-*-coding:utf-8-*-__author__="Loki"ImportSocketImportSubprocessserver=Socket.socket (socket.af_inet, socket. SOCK_STREAM) server.setsockopt (socket. Sol_socket, SOCKET. SO_REUSEADDR,1) Ip_port= ('127.0.0.1', 8011) Server.bind (ip_port) Server.listen (5)#Link Loops while1: Print('Waiting ...') conn, addr=server.accept ()Print('-->conn:', conn)Print('-->addr:', addr)Print('Got it ...') while1: Try: cmd= CONN.RECV (1024) Res= subprocess. Popen (Cmd.decode ('Utf-8'), Shell=True, stdout=subprocess. PIPE, stderr=subprocess. PIPE) Conn.send (Res.stdout.read ()) Conn.send (Res.stderr.read () )exceptException: Breakconn.close ()#server.close ()
Client
#!/usr/bin/env python#-*-coding:utf-8-*-__author__="Loki"Importsocketclient=Socket.socket (socket.af_inet, socket. SOCK_STREAM) Ip_port= ('127.0.0.1', 8011) Client.connect (ip_port)#Communication Cycle while1: #Send Messagecmd = input ('>>:'). Strip ()if notcmd:Continueclient.send (bytes (cmd, encoding='Utf-8')) #Receive Messagedata = CLIENT.RECV (8196) Print(Data.decode ('GBK'))#client.close ()
The above code is based on the TCP-streaming mode of C/s control, note that the encoding of Linux for Utf-8,windows for GBK
Known Bugs:
1. There may be a sticky packet problem when the received information is greater than 8196 (or the value you define yourself)
2. Execute executable program or CMD command that requires interaction, client will be down and need to re-open clients
3. If it is used as a pure PY script also need to make sys.platform system judgment, if it is win using encoding Gbk,linux encoding Utf-8
4. The above code is only for learning reference use
Python module--socket (for simple c/S architecture end-of-communication operation CMD)