Write a simple version of SSH with Scoket
Service side:
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 one-S.listen (5) #监听列表 5 print (' Listening ... ') while True:14 conn,addr=s.accept () # Listen to the new successive print (' Connect to New address: ', addr) and true:17 data=conn.recv (4092) #接收数据18 if not data: #如果收的数据为空 Print (' Client disconnected! ') break21 print (' instruction: ', Data.decode ()) Cmd_res=os.popen (Data.decode ()). Read () #读取数据, instruction 23 #cmd_res_l =len (Cmd_res.encode (' Utf-8 ')) #数据大小24 if Len (cmd_res) ==0:26 cmd_res= ' instruction error! ' Continue28 #conn. recv (1) conn.send (str (LEN (cmd_res.encode (' Utf-8 '))). Encode (' Utf-8 ')) #发送 The size of the data is #print (len (cmd_res)) to Clinet_ack=conn.recv (1024x768) #为了去粘包32 conn.send (Cmd_res.encode (' UTF -8 ')) #发送指令34 #print (Cmd_res.encode (' Utf-8 ')) print (' Send complete! ') 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.conn ECT ((' localhost ', 9100)) #客户端连联 8 while True:9 cho=input (' directive: '). Strip () if Len (cho) ==0:continue11 C.send (Cho.encode (' Utf-8 ')) #发送数据12 cmd_res_size=c.recv (1024x768) #接收数据 data size print (' Data size: ', cmd_res_size) 14 size_l=0# The current size of the data c.send (' Confirm! '). Encode (' Utf-8 ')) #为了去粘包16 while size_l< Int (Cmd_res_size.decode ()): data=c.recv (1024x768) #开始接收数据18 Size_l+=len (data) #加上19 print (Data.decode ()) print (size_l) else:22 Print (' Receive complete ', size_l)
Under Win10, recv (1024) ipconfig instructions will go wrong, other commands are not found at the moment.