Python---socket module

Source: Internet
Author: User

Here is a socket programming example that emulates the SSH Remote execution command

The socket establishes the connection process and simulates the call process.

socket_server.py

#!/usr/bin/env python#-*-coding:utf-8-*-ImportSocketImportSubprocess#Import Execution Command Module#define "calling card"Ip_port= ('127.0.0.1', 9998)#Defining tuples#"Buy a cell phone"S=socket.socket ()#binding protocol, raw complete sockets#"bind card and Phone"S.bind (Ip_port)#Binding ip+ protocol + port: used to uniquely identify a process, ip_port must be a tuple format#"Powering on"S.listen (5)#to define the maximum number of pending connections#waiting for a call whileTrue:#used to repeatedly receive a new connectionConn,addr=s.accept ()#receives a client connection request, returns conn (equivalent to a specific connection), addr is the client Ip+port    #Receive Message     whileTrue:#used to repeatedly send and receive messages based on a connection           #Snapping Client exception shutdown (CTRL + C)           #If the client shuts down unexpectedly (Close () is not executed), the connection exception is caused and the service side is also abnormal           Try: Recv_data=CONN.RECV (1024)#message received, blocked after receipt, receive size between 1024 and 8192                #print (len (recv_data))                #if the client exits normally (close () is executed), the server recv function will receive an empty message, and the servers side also exits                ifLen (recv_data) = =0:Print("client exits normally")                     BreakP=subprocess. Popen (str (recv_data,encoding='UTF8'), shell=true,stdout=subprocess. PIPE)#Execute system CommandRes=p.stdout.read ()#Get standard output                #If you execute a command error, the standard output is empty, you must determine if the standard output is empty, if the null send_data is ' cmd err ', it will cause the client recv () to block                ifLen (res) = =0:send_data='cmd err'                Else:                    #the standard output of the Windows Platform command is GBK encoding, which needs to be converted to a string first (because the strings in various encodings are the same)Send_data=str (res,encoding='GBK')                #Convert to UTF8, note that Python3 needs to be converted to bytes in order to send, Python2 can send the string directlySend_data=bytes (send_data,encoding='UTF8')                #solving Sticky pack problemsready_tag='ready|%s'%Len (send_data) conn.send (bytes (ready_tag,encoding='UTF8'))#tell client side data lengthFEEDBACK=CONN.RECV (1024)#Receive confirmation InformationFeedback=str (feedback,encoding='UTF8')#The received is also bytes, which need to be converted into a string                ifFeedback.startswith ('Start'):#If the confirmation message starts with "Start"Conn.send (Send_data)#The execution result of the Send command           exceptException:Print("Client Exception Exit")             Break    #"Hang up the phone"Conn.close ()
View Code

socket_client.py

#!/usr/bin/env python#-*-coding:utf-8-*-ImportSocketip_port=('127.0.0.1', 9998)#"Buy a cell phone"s=Socket.socket ()#"Dial-up"S.connect (Ip_port)#connection Server, if a good connection already exists on the server, then Hang whileTrue:#to loop a message based on a connection established by connectSend_data=input (">>:"). Strip ()ifSend_data = ='Exit': Break    ifLen (send_data) = = 0:Continues.send (bytes (send_data,encoding='UTF8'))    #solving Sticky pack problemsREADY_TAG=S.RECV (1024)#to charge bytes with data length: ready|9998Ready_tag=str (ready_tag,encoding='UTF8')    ifReady_tag.startswith (' Ready'):#ready|9998Msg_size=int (Ready_tag.split ('|') [-1])#get the length of data to receivestart_tag='Start's.send (bytes (start_tag,encoding='UTF8'))#Send confirmation message "Start"    #Loop over received data based on the length of data received to receiveRecv_size=0 recv_msg=b"'    #represents an empty byte     whileRecv_size <Msg_size:recv_data=S.RECV (1024) recv_msg+=Recv_data recv_size+=Len (recv_data)Print('MSG Size%s rece size%s'%(msg_size,recv_size))Print(Str (recv_msg,encoding='UTF8'))    #Hang up the phoneS.close ()
View Code

Python---socket module

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.