Home  >  Article  >  Backend Development  >  python learn socket ---ssh

python learn socket ---ssh

巴扎黑
巴扎黑Original
2017-06-23 16:24:531233browse

Write a simplified version of ssh using Scoket

Server:

 1 #!usr/bin/env python 2 #-*-coding:utf-8-*- 3 # Author calmyan 4  5 import socket,os 6  7 s=socket.socket()#实例化一个 socket 8  9 s.bind(('localhost',9100))#绑定一个监听端口10 11 s.listen(5)#监听列表 5 个12 print('监听中...')13 while True:14     conn,addr=s.accept()#监听到新的接连15     print('连接到新的地址:',addr)16     while True:17         data=conn.recv(4092)#接收数据18         if not data:#如果收的数据为空19             print('客户端已经断开!')20             break21         print('指令:',data.decode())22         cmd_res=os.popen(data.decode()).read()#读取数据,指令23         #cmd_res_l=len(cmd_res.encode('utf-8'))#数据大小24 25         if len(cmd_res)==0:26             cmd_res='指令错误!'27             continue28         #conn.recv(1)29         conn.send(str(len(cmd_res.encode('utf-8'))).encode('utf-8') )#发送数据的大小30         #print(len(cmd_res))31         clinet_ack=conn.recv(1024)#为了去粘包32 33         conn.send(cmd_res.encode('utf-8'))#发送指令34         #print(cmd_res.encode('utf-8'))35         print('发送完毕!')36 else:37     s.close()

Client:

 1 #!usr/bin/env python 2 #-*-coding:utf-8-*- 3 # Author calmyan 4 import socket 5 c=socket.socket()#实例化一个socket 6  7 c.connect(('localhost',9100))#客户端连联 8 while True: 9     cho=input('指令:').strip()10     if len(cho)==0:continue11     c.send(cho.encode('utf-8'))#发送数据12     cmd_res_size=c.recv(1024)#接收数据 数据大小13     print('数据大小:',cmd_res_size)14     size_l=0#收数据当前大小15     c.send('确认!'.encode('utf-8'))#为了去粘包16     while size_l< int(cmd_res_size.decode()):17         data=c.recv(1024)#开始接收数据18         size_l+=len(data)#加上19         print(data.decode())20         print(size_l)21     else:22         print('接收完毕',size_l)

Under win10, the ipconfig command will error when recv(1024), and other commands are not found for the time being

The above is the detailed content of python learn socket ---ssh. For more information, please follow other related articles on the PHP Chinese website!

Statement:
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn