Python study day 34 (udp socket, tcp remote command execution)

Today, much of the content is executed on two, udp and tcp sockets remote command

The first is a program error yesterday on disposal of:

Error as follows:

 

 This is because your server still exists time_wait four state waving in the occupied address

1.tcp three-way handshake, waving 2.syn four flood attack time_wait state have a lot of highly concurrent server 3.

method 1:

# Add a socket configuration, ip and port reuse 

Phone = socket (AF_INET, SOCK_STREAM) 
phone.setsockopt (SOL_SOCKET, the SO_REUSEADDR, . 1) # is that it, before adding the bind 
phone.bind (( ' 127.0.0.1 ' , 8080))

Method 2:

This method is more Niubi, I guess you must first take a look at Linux in order to do a set

Found large TIME_WAIT state system is connected, is solved by adjusting the parameters linux kernel, 
VI / etc / the sysctl.conf 

edit file, add the following: 
net.ipv4.tcp_syncookies =. 1 
net.ipv4.tcp_tw_reuse =. 1 
net.ipv4.tcp_tw_recycle = 1 
net.ipv4.tcp_fin_timeout = 30 
 
and then execute / sbin / sysctl - the p-let take effect. 
 
net.ipv4.tcp_syncookies = 1 will indicate on SYN Cookies. When the SYN queue overflow occurs, is enabled to process cookies, a small amount can prevent SYN attacks, defaults to zero disables; 

net.ipv4.tcp_tw_reuse =. 1 indicate on reuse. Allowing TIME - WAIT sockets reused for a new TCP connection, the default is zero disables; 

net.ipv4.tcp_tw_recycle = TCP connection open. 1 represents TIME - Fast Recovery WAIT sockets, the default is 0, indicating off. 

net.ipv4.tcp_fin_timeout modify the system default TIMEOUT time

Second, server-based and client udp socket end

1. Server

Import socket
 # may be possible within the parameters be set before the establishment of service, ease of late changes 
ip_port = ( ' 127.0.0.1 ' , 8080 ) 
back_log = 5 
buffer_size = 1024 # now we have to build a udp protocol server 
tcp_server = socket.socket (socket.AF_INET, socket.SOCK_DGRAM) 
tcp_server.bind (ip_port) # -based udp protocol that does not require listen set 
# also do not need to go through "three-way handshake" required to establish a two-way connection, so do not accept the while True: 
    Data, addr = tcp_server.recvfrom (buffer_size)    # receives two message information is obtained, a message is, and the other is called location Print (data.decode ( ' UTF-. 8 ' ))
    




    Print (addr) 
    tcp_server.sendto (data.upper (), addr)      # when sending content is the need to write the address 

tcp_server.close ()

2. Client

import socket

ip_port=('127.0.0.1',8080)
buffer_size=1024
while True:
    tcp_client = socket.socket(socket.AF_INET,socket.SOCK_DGRAM)
    msg = input('>>>:')
    tcp_client.sendto(msg.encode('utf-8'),ip_port)
    data,addr = tcp_client.recvfrom(buffer_size)
    print(data.decode('utf-8'))

What are the advantages udp socket is it?

The most obvious is that no three-way handshake and four waving of operation, and at the same time so that you can interact with multiple clients, can be seen from the client, she even backlog was all wood

Third, remote command execution based on tcp

1. The subprocess a supplementary module

stdout, stderr: input: This parameter is passed to Popen.communicate (), normal value of this parameter must be a sequence of bytes, if universal_newlines = True, then it should be a string value.

run () function does not capture the default command execution results of normal output and error, if we need to pass subprocess.PIPE to obtain the contents, then the class can be instantiated by CompletedProcess returned stdout and stderr or capture the corresponding content attributes;

call () and check_call () function returns a command execution status code, rather than CompletedProcess class instance, it was for them, stdout and stderr unsuitable assigned subprocess.PIPE;

check_output () function will return the default command execution results, so do not set the value to stdout, if we want to capture error messages in the result, you can perform stderr = subprocess.STDOUT.

Tentatively dir command as an example

subprocess.Popen('dir' , shell = True , stdout = subprocess.PIPE ,stderr = subprocess.PIPE,  stdin = subprocess.PIPE)

Output information corresponding to each of the operation, the error information and the input information

If you do not set these three values, they will default data directly through the "pipe" into the screen, but this time we are the corresponding output results stored in the pipeline

res = subprocess.Popen('dir' , shell = True , stdout = subprocess.PIPE ,stderr = subprocess.PIPE,  stdin = subprocess.PIPE)

res.stdout.read () method read the reason for use, because the value obtained is a direct class object

 

2. End supplementary information subprocess module we can start the actual operation

(1) first hand feedback time trial bar (based on udp socket)

Server:

Import socket, Time
 # can be within the parameters that may arise before the establishment of service settings, easy to post changes 
ip_port = ( ' 127.0.0.1 ' , 8080 ) 
back_log = 5 
buffer_size = 1024 # now we have to build a server udp protocol 
= tcp_server socket.socket (socket.AF_INET, socket.SOCK_DGRAM) 
tcp_server.bind (ip_port) # -based udp protocol that does not require listen set 
# also do not need to go through "three-way handshake" required to establish a two-way connection, so I do not requires Accept the while True: 
    Data, addr = tcp_server.recvfrom (buffer_size)    # receives two message information is obtained, a message is, and the other is called location Print (data.decode ( ' UTF-. 8 ' ))
    




    Print (addr) 
    MSG = data.decode ( ' UTF-. 8 ' )    # Such an arrangement allows the user to set the format of our time 
    IF  Not MSG:                   # judge, user Shurun time format is empty, we can output the default format 
        time_res the time.strftime = ( ' % Y-M-%%% X-D ' )
     the else :                          # is not a null value when the user input parameters prevail 
        time_res = the time.strftime (MSG)    # '%% Y-M- X-% D% ' 
    tcp_server.sendto (time_res.encode ( ' UTF-. 8 ' ), addr)      # when transmitting the content of the write address is the need 

tcp_server.close ()

Client:

import socket

ip_port=('127.0.0.1',8080)
buffer_size=1024
while True:
    tcp_client = socket.socket(socket.AF_INET,socket.SOCK_DGRAM)
    msg = input('>>>:')
    tcp_client.sendto(msg.encode('utf-8'),ip_port)
    data,addr = tcp_client.recvfrom(buffer_size)
    print(data.decode('utf-8'))

Part of the client's largely unchanged, really feel very Bang Bang.

 

Here is the tcp protocol-based, remote command execution, somewhat similar to the Remote Assistance meaning

Server:

from socket import *
import subprocess
ip_port=('127.0.0.1',8080)
back_log=5
buffer_size=1024

tcp_server=socket(AF_INET,SOCK_STREAM)
tcp_server.bind(ip_port)
tcp_server.listen(back_log)

while True:
    conn,addr=tcp_server.accept()
    print('新的客户端链接',addr)
    while True:
        #
        try:
            cmd=conn.recv (buffer_size)
             IF  Not cmd: BREAK 
            Print ( ' client that receives a command ' , cmd) 

            # Run, to obtain the results of the command to run cmd_res 
            RES = subprocess.Popen (cmd.decode ( ' UTF-. 8 ' ), = the shell True, 
                                 stderr = subprocess.PIPE, 
                                 stdout = subprocess.PIPE, 
                                 stdin = subprocess.PIPE) 
            ERR = res.stderr.read ()
             IF ERR: 
                cmd_res= ERR
             the else : 
                cmd_res = res.stdout.read () 

            # hair 
            IF  not cmd_res: 
                cmd_res = ' successfully executed ' .encode ( ' gbk ' ) # gbk Why is it here, where instruction execution system uses the system default encoding system for Windows is GBK 
            conn.send (cmd_res) 
        the except Exception AS E:
             Print (E)
             BREAK

Client:

from socket import *
ip_port=('127.0.0.1',8080)
back_log=5
buffer_size=1024

tcp_client=socket(AF_INET,SOCK_STREAM)
tcp_client.connect(ip_port)

while True:
    cmd=input('>>: ').strip()
    if not cmd:continue
    if cmd == 'quit':break

    tcp_client.send(cmd.encode('utf-8'))
    cmd_res= Tcp_client.recv (buffer_size)
     Print ( ' execution result of the command is ' , cmd_res.decode ( ' GBK ' )) 
tcp_client.close ()

 

Today is the content of these, we learned a lot, in fact, udp socket is very powerful, we use qq is a typical udp, you can ensure multi-line contact, that's it

See gripping evacuated linux, elective procedures that done, may be substantially on the line

Guess you like

Origin www.cnblogs.com/xiaoyaotx/p/12585389.html