"Python Tour" fifth (iv): A simple version of SSH program based on Python SOCKCT multi-Threading

Source: Internet
Author: User

Or continue the example of the previous V, by tinkering with the code, change it to a program that can execute server-side commands on the client side after connecting, so it's a bit like the SSH connection program.

As for the previous example to change it, because the class has been so dry, and the teacher also speak very good, oneself absorbed also as a learning record, because it is really very good!

The reason for such a modification of the previous example is that the server side can return a string of input from the client side, so if the client input is a Linux shell command, Can the server side execute these commands and return the results of the execution?

So it is based on this idea to improve the previous example, to achieve this effect, need some other module support, of course, also need to make some improvements in the details, the code given below will be described in more detail.

Just take a look at this simple version of the SSH program is what kind of stuff.


Server-Side program code:

import socketserverimport commands     #使用其中的getstatusoutput () function, Allow the server side to recognize the commands sent by the client side and execute import time        #. The Time.sleep () function is used primarily to resolve the "block" problem of sending data on the server side Class mysockserver (socketserver.baserequesthandler):d ef  Handle (self):p rint  ' Got a new connection from ', self.client_addresswhile  TRUE:CMD = SELF.REQUEST.RECV (1024x768) if not cmd:print  ' Last connection with: ', Self.client_addressbreakcmd_result = commands.getstatusoutput (CMD)     # Gets the client's instruction and executes, the returned result is a tuple that stores two elements, the first element is 0 for successful execution, the second element is the execution result of the command Self.request.send (Len (cmd_result[1)))       #发送命令执行结果的大小长度, if the client wants to receive execution results of any size, it will need to select the policy based on the size of the command execution result, it is important to note that the data sent is a string, So it is necessary to make type conversion time.sleep (0.2)          #睡眠0.2s, which is to solve the "even block" Question Self.request.sendall (cmd_result[1])   #发送命令执行结果if  __name__ ==  ' __main__':host =  ' Port = 50007s = socketserver.threadingtcpserver (HOST, PORT),  mysockserver) S.serve_forever ()


Client Terminal program code:

import sockethost =  ' 192.168.1.13 ' Port = 50007s = socket.socket (socket.AF_ Inet, socket. Sock_stream) S.connect ((Host, port)) Def data_all (obj, lenth_size):d ata =  '                  # Used to store the data received by the socket at each time of the loop, resolving the socket's buffer bottleneck limit of about 20,000 multibyte while lenth_size != 0:   # If the received data length is not 0, start executing the Receive data processing policy if lenth_size <= 4096:     #这里以4096为单位块, DATA_RECV&NBSP;=&NBSP;OBJ.RECV (lenth_size)      #通过recv () receive data as each data processing amount is lenth_size =  0     #通过这一步的处理, the data are all received, the lenth_size is 0, the end of the cycle, the completion of data processing work else:data_recv =  OBJ.RECV (4096)      #以4096为单位块, receive 4096 data size at a time lenth_size -= 4096              #处理完一次4096字节的数据后, subtract the lenth_size from the 4096data += data _recv                      #判断外层, Use local data to store the received data, because there is no limit to the local data size, so there is no data saturation cannot continue to store the problem, but the previous socket recv () function can only receive the maximum amount of data at a time limit, This depends on the buffer size of the socket, so the Data_all function works by using multiple recv () functions, and storing the data locally after each receive of a certain amount until all the data is received return datawhile  True:user_input = raw_input (' cmd to send: '). Strip () If len (user_input)  == 0: Continues.sendall (user_input) data_size = int (S.RECV (1024x768))       # Get the size length of the command execution result, because the data sent is a string, so here is the type conversion print  ' \033[32;1mdata size:\033[0m ',data_size      #打印命令执行结果的大小result  = data_all (s, data_size)      #通过data_ The all function executes the corresponding data receive processing policy print result                         #打印命令执行结果s. Close ()                                      #关闭套接字


Demonstrate:

Step 1:server Run the server-side program

[Email protected]:/mnt/hgfs/python/day5$ Python ssh_server5.py ===> cursor is here in wait state

Step 2:client Run the client program and observe the returned results

[Email protected]:/mnt/hgfs/python/day5$ python ssh_client5.py cmd to send: dfdata size: 502                                 == /= the size of the result of the command execution df:  "/VAR/LIB/LIGHTDM/.GVFS":  Insufficient permissions         === > Command execution result file system            1k-block         used      available   used%  mount point/dev/sda3         8781832   3458300 4877428   42% /udev               493784          4  493780    1% /devtmpfs              201040       784  200256     1% /runnone                 5120         0    5120     0% /run/locknone               502592       144  502448    1%  /run/shm/dev/sda1          93207      30139   58256   35% /boot.host:/         162256468 152391980 9864488   94% /mnt/hgfscmd to  send:pwd                                ===> perform the pwd command data size: 21/mnt/hgfs/python/ Day5cmd to send:lsdata size: 357[1]sec_4_ver1 (single threaded, non-interactive) [2]sec_4_ver2 (Single threaded, interactive, blocking mode general demo) [3] Sec_4_ver3 (single threaded, interactive, blocking mode advanced presentation) [4]sec_4_ver3 (Single threaded, interactive, multi-concurrency) Client4.pyduotiao_jian_biao3.pyjian_biao2.pymy_ conn1.pyserver4.pyssh_client5.pyssh_server5.pythread_socket_server4.pycmd to send:top -bn  3        ===> Note that the execution result (size) of the command exceeds the buffer size of the socket. Therefore, the program code in the client terminal above is mainly to solve this problem, which is also the key to the client side data size: 34378              ===> the execution result of this command is 30,000 multibyte, beyond the socket buffer, the socket's recv () function is not able to receive that much data at once ... Omit output result cmd to send:ls                ===> continue to execute command, return results normal data size: 357[1]sec_4_ver1 (single threaded, non-interactive) [2]sec_4_ver2 (Single threaded, interactive, blocking mode general demo) [3]sec_4_ver3 (Single threaded, interactive, blocking mode advanced presentation) [4]sec_4_ver3 (Single threaded, interactive, multi-andHair) client4.pyduotiao_jian_biao3.pyjian_biao2.pymy_conn1.pyserver4.pyssh_client5.pyssh_server5.pyThread_socket_ server4.py

You can see that the above two programs have been better implemented command execution function, the main problem is focused on:

1.Server Send Data "block" problem, that is, when sending two of data, if the sending interval is relatively short, the socket will send two data sent together to send, here through the Time.sleep () function to solve.

2.socket buffer size problem, that is, when the execution of Top-bn 3, such as the result of large-length command, the socket buffer can not store so much data at a time, so only a few times to receive data, so the client side will bring some problems, such as command execution of the different steps, The workaround is to make the data sent by the local storage server by using a loop-received method.

Of course, if you want to execute the man and other query commands, the above program is also unable to do, so here is said, this is just a simple version of the SSH program, as a Python socket learning, and really want to use SSH, it is not as good as directly next SSH connection software.

This article is from the "fragrant fluttering leaves" blog, please make sure to keep this source http://xpleaf.blog.51cto.com/9315560/1700072

"Python Tour" fifth (iv): A simple version of SSH program based on Python SOCKCT multi-Threading

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.