Python network programming (remote execution commands and sticky packets)

Source: Internet
Author: User

Remote execution commands

First to learn a new module, one will use.

= subprocess. Popen ('ls', shell=true,stdout=subprocess. Pipe,                     stderr= True indicates that the  command I am currently executing is System command c: Output pipeline that represents the correct information D: An output pipeline that represents an error message

Directly below the code, a look will understand. TCP's

ImportSocketImportSubprocesssk=socket.socket () Sk.bind ('127.0.0.1', 9090) ) Sk.listen () conn,addr=sk.accept () while1: cmd= Conn.recv (1024x768). Decode ('Utf-8') Res= subprocess. Popen (cmd,shell=true,stdout=subprocess. PIPE, stderr=subprocess. PIPE) Std_out= Res.stdout.read ()#read the correct return informationStd_err = Res.stderr.read ()#read the return information of the error    ifstd_out:conn.send (std_out)Else: Conn.send (Std_err) conn.close () sk.close ()
Remote Service side
 import   Socketsk  = Socket.socket () sk.connect_ex (( "  127.0.0.1   ", 9090  While  1: cmd  = input ( "  Please enter a command >>>  "  ) Sk.send (Cmd.encode (  " utf-8   "  print  ( SK.RECV (204800000). Decode ( '  GBK   " )) Sk.close ()  
Remote Client

Refers to the function of a module, the other is simple transceiver function.

Res=subprocess. Popen (Cmd.decode ('utf-8'), Shell=True,stderr=subprocess. Pipe,stdout=subprocess. PIPE) The result of the encoding is based on the current system, if it is windows, then Res.stdout.read () read out is GBK encoded, at the receiving end needs to use GBK decoding and can only read the results from the pipeline attention

--------------------Sticky Bag---------------------------

UDP does not occur sticky packets--------

UDP (User Datagram Protocol, Subscriber Datagram Protocol) is non-connected, message-oriented, providing efficient service. The Block merging optimization algorithm is not used, because UDP supports a one-to-many pattern, so the Skbuff (socket buffer) on the receiving end uses a chain structure to record each incoming UDP packet.

That is, message-oriented communication is a message-protected boundary. For the empty message: TCP is based on data flow, so send and receive messages can not be empty, which requires the client and the server to add a null message processing mechanism, to prevent the program to get stuck,
And UDP is based on the datagram, even if you enter the empty content (direct carriage return), can also be sent, the UDP protocol will help you encapsulate the message hair sent over. Unreliable non-sticky UDP protocol: UDP recvfrom is blocked, a recvfrom (x) must be the only one sendinto (y), after the completion of the X-byte data, if the y;x data is lost,
This means that UDP does not stick to the packet at all, but it loses data and is unreliable.

Additional notes:

When sending using the UDP protocol, the maximum data length with the SendTo function is: 65535-ip header (20) –UDP header (8) = 65507 bytes.
When sending data with the SendTo function, the function returns an error if the sending data is longer than the value. (Discard this package, do not send) when sent with the TCP protocol, because TCP is the data flow protocol, there is no limit on the size of the packet (regardless of the size of the buffer), which means that the data length parameter is not restricted when using the Send function.
In fact, the specified data is not necessarily sent out at one time, if the data is longer, will be segmented sent, if relatively short, may wait and the next time the data sent together.

Summary

Sticky packets occur only in the TCP protocol:

1. On the surface, the sticky packet problem is mainly due to the caching mechanism of the sender and receiver, and the characteristic of the TCP protocol oriented stream communication.

2. In fact, mainly because the receiver does not know the boundary between the message, do not know how many bytes of data extracted at once caused by

Solution------------

We can use a module that converts the length of data to be sent to a fixed-length byte. In this way, each time a client receives a message, it takes a fixed-length byte to take a look at the size of the information that is to be received, so that the final accepted data is stopped as soon as it reaches that value, and it will be able to receive the complete data in just a few more.

File Upload solution Sticky Package code: Use the dictionary to pass the file size before ....

ImportSocketImportJSONImportStructsk=socket.socket () Sk.bind ('127.0.0.1', 9090) ) Sk.listen () conn,addr=sk.accept () dic_size= CONN.RECV (4)#accept a bytes of 4 bytes in length, representing the size of the dictionaryDic_size = Struct.unpack ('I', dic_size) [0]#Turn This special bytes into the original number.Dic_str = Conn.recv (dic_size). Decode ('Utf-8')#to get a dictionary based on the size of the dictionary, so as not to get the file content with the bottom sticky packetDIC = Json.loads (DIC_STR)#deserialization get dictionary opt filename filesizeifdic['opt'] =='Upload':    " "Receiving Files" "filename='1'+dic['filename']#Modify the name of the file to prevent duplicate nameswith open (filename,'WB') as F: whiledic['filesize']: Content= CONN.RECV (1024) f.write (content) dic['filesize'] -=len (content)elifdic['opt'] =='Download':    " "transferring files to clients" "conn.close () sk.close ( )
File Upload service side

ImportSocketImportOSImportJSONImportStructsk=socket.socket () Sk.connect ('127.0.0.1', 9090)) L= ['Upload','Download'] forI,vinchEnumerate (L):Print(i+1, v) DiC= {'opt': None,'filename': None,'filesize': None} while1: Opt= Input ("Please enter feature options >>>")#action options to be performed by the customer    ifopt = ='1':        " "Upload" "File_dir= Input ('Please enter file path >>>')#' e:/sylar/python_workspace/day34/job/time synchronization mechanism _client.py 'file_name = Os.path.basename (File_dir)#Get file nameFile_size = Os.path.getsize (File_dir)#Get File Sizedic['opt'] = L[int (opt)-1] dic['filename'] =file_name dic['filesize'] =file_size dic_str= Json.dumps (DIC)#serializes a dictionary into a dictionary as a stringDic_size = Len (dic_str)#get the size of the dictionaryds = Struct.pack ('I', dic_size)#turn a number less than 21.3E into a 4-byte bytesSk.send (ds + Dic_str.encode ('Utf-8'))#Send to ServerWith open (File_dir,'RB') as F: whilefile_size:content= F.read (1024)#File Contentssk.send (content) File_size-=len (content)elifopt = ='2':        " "Download" "        Pass    Else:        Print('wrong') Sk.close ()
File Upload Client

Send and receive summary

Python network programming (remote execution commands and sticky packets)

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.